text
stringlengths
13
6.01M
using GardenControlRepositories.Entities; using GardenControlRepositories.Interfaces; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GardenControlRepositories { public class VideoFeedRepository : IVideoFeedsRepository { private GardenControlContext _context { get; init; } private ILogger<VideoFeedRepository> _logger { get; init; } public VideoFeedRepository(GardenControlContext context, ILogger<VideoFeedRepository> logger) { _context = context; _logger = logger; } public async Task DeleteVideoFeedAsync(int id) { var videoFeedEntity = await _context.VideoFeedEntities .Where(x => x.VideoFeedId == id).FirstOrDefaultAsync(); if (videoFeedEntity == null) { _logger.LogWarning($"Tried deleting Video Feed that does not exist, VideoFeedId: {id}"); return; } try { _context.VideoFeedEntities.Remove(videoFeedEntity); await _context.SaveChangesAsync(); } catch (Exception ex) { _logger.LogError($"Error deleting Video Feed ({id}): {ex.Message}"); throw; } } public async Task<IEnumerable<VideoFeedEntity>> GetAllVideoFeedsAsync() { return await _context.VideoFeedEntities.ToListAsync(); } public async Task<VideoFeedEntity> GetVideoFeedByIdAsync(int id) { return await _context.VideoFeedEntities .Where(x => x.VideoFeedId == id) .FirstOrDefaultAsync(); } public async Task<VideoFeedEntity> InsertVideoFeedAsync(VideoFeedEntity videoFeed) { if (videoFeed == null) throw new NullReferenceException(nameof(videoFeed)); try { _context.VideoFeedEntities.Add(videoFeed); await _context.SaveChangesAsync(); } catch (Exception ex) { _logger.LogError($"Error inserting Video Feed: {ex.Message}"); throw; } return videoFeed; } public async Task<VideoFeedEntity> UpdateVideoFeedAsync(VideoFeedEntity videoFeed) { if (videoFeed == null) throw new NullReferenceException(nameof(videoFeed)); try { _context.Entry(videoFeed).State = EntityState.Modified; await _context.SaveChangesAsync(); } catch (Exception ex) { _logger.LogError($"Error updating Video Feed: {videoFeed.VideoFeedId}, {ex.Message}"); throw; } return videoFeed; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EX_2A___Calculating_Averages { class Program { static void Main(string[] args) { Console.WriteLine("This application will accept an arbitrary number of test scores between 0 and 100, then report their average and letter grade\n"); double numSum = 0; double numAvg = 0; try { Console.WriteLine("Enter the number of tests you need to average:"); int numTests = int.Parse(Console.ReadLine()); for (int i = 0; i < numTests; i++) { Console.WriteLine("Enter the grade for test {0}", i + 1); double numGrade = double.Parse(Console.ReadLine()); while (numGrade < 0) { Console.WriteLine("Your number must be greater than 0"); numGrade = double.Parse(Console.ReadLine()); while (numGrade > 100) { Console.WriteLine("Your number must be less than 100"); numGrade = double.Parse(Console.ReadLine()); } } while (numGrade > 100) { Console.WriteLine("Your number must be less than 100"); numGrade = double.Parse(Console.ReadLine()); while (numGrade < 0) { Console.WriteLine("Your number must be greater than 0"); numGrade = double.Parse(Console.ReadLine()); } } numSum += numGrade; } numAvg = numSum / numTests; if (numAvg >= 90) { Console.WriteLine("The numerical average is {0} and the letter grade is A", numAvg); } else if (numAvg >= 80) { Console.WriteLine("The numerical average is {0} and the letter grade is B", numAvg); } else if (numAvg >= 70) { Console.WriteLine("The numerical average is {0} and the letter grade is C", numAvg); } else if (numAvg < 70) { Console.WriteLine("The numerical average is {0} and the letter grade is F", numAvg); } } catch (FormatException e) { Console.WriteLine("You must enter a number, not a letter or word"); } catch (OverflowException e) { Console.WriteLine("You must enter a number between 0 and 255"); } catch (Exception e) { Console.WriteLine("An unknown error occurred"); } finally { Console.WriteLine("Error Handling Complete!"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; using System.ComponentModel; namespace KartSystem { public class RestSaleReportRecord:Entity { [DBIgnoreAutoGenerateParam] [DBIgnoreReadParam] public override string FriendlyName { get { return "Строка отчета продажи с остатками"; } } /// <summary> /// Артикул /// </summary> [DisplayName("Артикул")] public string Articul { get; set; } /// <summary> /// Наименование товара /// </summary> [DisplayName("Наименование товара")] public string NameGood { get; set; } /// <summary> /// Ассортимент /// </summary> [DisplayName("Ассортимент")] public string NameAssortment { get; set; } /// <summary> /// Подразделение /// </summary> [DisplayName("Подразделение")] public string NameWh { get; set; } /// <summary> /// Остаток /// </summary> [DisplayName("Остаток")] public double Rest { get; set; } /// <summary> /// Продажа кол-во /// </summary> [DisplayName("Продажа кол-во")] public double SaleQuant { get; set; } /// <summary> /// Продажа сумма /// </summary> [DisplayName("Продажа сумма")] public decimal SaleSum { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using VJBatangas.LomiHouse.Business; using VJBatangas.LomiHouse.Common; using VJBatangas.LomiHouse.Entity; namespace VJBatangas.LomiHouse { public partial class frmWithdrawal : Form { public frmWithdrawal() { InitializeComponent(); } private void btnAdd_Click(object sender, EventArgs e) { frmWithdrawalDetail frm = new frmWithdrawalDetail(); frm.ShowDialog(); DialogResult result = frm.ShowDialog(this); if (result == DialogResult.OK) { Withdrawal s = new Withdrawal(); s.AvailableStock = frm.AvailableStock; s.ItemId = frm.ItemId; s.ItemName = frm.ItemName; s.SubTotal = frm.SubTotal; s.Quatity = frm.Quatity; dgvData.ColumnCount = 5; dgvData.Columns[0].Name = "Item ID"; dgvData.Columns[1].Name = "Item Name"; dgvData.Columns[2].Name = "Item Quantity"; dgvData.Columns[3].Name = "Item Price"; dgvData.Columns[4].Name = "Sub Total"; string[] row = new string[] { s.ItemId.ToString(), s.ItemName, s.Quatity.ToString(), "", s.SubTotal.ToString() }; dgvData.Rows.Add(row); //row = new string[] { "2", "Product 2", "2000" }; //dgvData.Rows.Add(row); //row = new string[] { "3", "Product 3", "3000" }; //dgvData.Rows.Add(row); //row = new string[] { "4", "Product 4", "4000" }; //dgvData.Rows.Add(row); //DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn(); //dgvData.Columns.Add(chk); //chk.HeaderText = "Check Data"; //chk.Name = "chk"; //dgvData.Rows[2].Cells[3].Value = true; DataGridViewLinkColumn Editlink = new DataGridViewLinkColumn(); Editlink.UseColumnTextForLinkValue = true; Editlink.HeaderText = "Edit"; Editlink.DataPropertyName = "lnkColumn"; Editlink.LinkBehavior = LinkBehavior.SystemDefault; Editlink.Text = "Edit"; dgvData.Columns.Add(Editlink); DataGridViewLinkColumn Deletelink = new DataGridViewLinkColumn(); Deletelink.UseColumnTextForLinkValue = true; Deletelink.HeaderText = "delete"; Deletelink.DataPropertyName = "lnkColumn"; Deletelink.LinkBehavior = LinkBehavior.SystemDefault; Deletelink.Text = "Delete"; dgvData.Columns.Add(Deletelink); } else { } //frm.Dispose(); } private void btnClose_Click(object sender, EventArgs e) { if (dgvData.RowCount > 0) { DialogResult diag = MessageBox.Show("You have pending items. Are you sure you want to discard the transaction?","Message",MessageBoxButtons.YesNo); if (diag == DialogResult.Yes) { this.Close(); } } else { this.Close(); } } private void frmWithdrawal_Load(object sender, EventArgs e) { this.ControlBox = false; LoadEmployeeNameList(); dgvData.AutoSize = true; } #region "Methods" private void LoadEmployeeByEmpId(int empid) { EmployeeMaster emp = new EmployeeMaster(); BSEmployeeMaster bsemp = new BSEmployeeMaster(); emp = bsemp.GetEmployeeByEmpId(empid); txtBranchName.Text = emp.BranchName; } private void LoadEmployeeNameList() { List<EmployeeMaster> emplist = new List<EmployeeMaster>(); BSEmployeeMaster bsemp = new BSEmployeeMaster(); emplist = bsemp.GetEmployeeNameList(); cbEmployee.DisplayMember = "FullName"; cbEmployee.ValueMember = "EmpId"; cbEmployee.DataSource = emplist; cbEmployee.SelectedValue = 0; } #endregion private void btnLoad_Click(object sender, EventArgs e) { if (cbEmployee.SelectedIndex != -1) { LoadEmployeeByEmpId(Convert.ToInt32(cbEmployee.SelectedValue.ToString())); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace CoherentSolutions.Extensions.Configuration.AnyWhere { public class AnyWhereConfigurationFileSearch : IAnyWhereConfigurationFileSearch { private readonly IAnyWhereConfigurationFileSystem fs; public AnyWhereConfigurationFileSearch( IAnyWhereConfigurationFileSystem fs) { this.fs = fs ?? throw new ArgumentNullException(nameof(fs)); } public IReadOnlyList<IAnyWhereConfigurationFileSearchResult> Find( IReadOnlyCollection<string> directories, string name, params string[] extensions) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException("Value cannot be null or whitespace.", nameof(name)); } if (directories.Count == 0) { return Array.Empty<IAnyWhereConfigurationFileSearchResult>(); } var resultSz = extensions.Length == 0 ? 1 : extensions.Length; IAnyWhereConfigurationFile[] result = null; List<IAnyWhereConfigurationFileSearchResult> output = null; foreach (var directory in directories) { if (result is null) { result = new IAnyWhereConfigurationFile[resultSz]; } var changed = this.FindInternal(result, directory, name, extensions); if (changed == 0) { continue; } if (output is null) { output = new List<IAnyWhereConfigurationFileSearchResult>(1); } output.Add( new AnyWhereConfigurationFileSearchResult( directory, result)); result = null; } return output; } public IReadOnlyList<IAnyWhereConfigurationFile> Find( string directory, string name, params string[] extensions) { if (string.IsNullOrWhiteSpace(directory)) { throw new ArgumentException("Value cannot be null or whitespace.", nameof(directory)); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException("Value cannot be null or whitespace.", nameof(name)); } var result = new IAnyWhereConfigurationFile[extensions.Length == 0 ? 1 : extensions.Length]; var changed = this.FindInternal(result, directory, name, extensions); return changed == 0 ? Array.Empty<IAnyWhereConfigurationFile>() : result; } private int FindInternal( IList<IAnyWhereConfigurationFile> result, string directory, string name, params string[] extensions) { if (extensions.Length == 0) { var path = Path.Combine(directory, name); if (this.fs.FileExists(path)) { result[0] = new AnyWhereConfigurationFile(this.fs, name, directory, path); return 1; } result[0] = null; return 0; } var count = 0; foreach (var (index, file) in extensions .Select((extension, index) => (index, path: string.Concat(name, extension)))) { var path = Path.Combine(directory, file); if (this.fs.FileExists(path)) { result[index] = new AnyWhereConfigurationFile(this.fs, name, directory, path); count++; } else { result[index] = null; } } return count; } } }
using mec.Common.Base; using mec.Model.Apps; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace mec.Framework { public partial class fmMain : Form { private AppForm apps; public AppForm Apps { get { if (this.apps == null) { this.apps = new AppForm(); } return this.apps; } } public string RuntimeAssemblyName { get; set; } public fmMain() { InitializeComponent(); } public fmMain(AppForm apps) { this.apps = apps; InitializeComponent(); } private void fmMain_Load(object sender, EventArgs e) { FormsManager.Configure(this, this.tsApps); this.initMenu(); this.openMainPage(); } private void initMenu() { this.msMenu.Items.Clear(); ToolStripMenuItem tsMenuItem = new ToolStripMenuItem(); tsMenuItem.Tag = "fmFunction"; tsMenuItem.Text = "功能選單(&F)"; this.msMenu.Items.Add(tsMenuItem); foreach (var app in this.Apps.AppFunctions) { ToolStripMenuItem tsSubMenuItem = new ToolStripMenuItem(); tsSubMenuItem.Text = app.Name; tsSubMenuItem.Tag = app.AssembyName; tsSubMenuItem.Click += new System.EventHandler(onFunctionClick); tsMenuItem.DropDownItems.Add(tsSubMenuItem); } tsMenuItem = new ToolStripMenuItem(); tsMenuItem.Tag = "fmSet"; tsMenuItem.Text = "設定(&S)"; tsMenuItem.Click += new System.EventHandler(onFunctionClick); this.msMenu.Items.Add(tsMenuItem); tsMenuItem = new ToolStripMenuItem(); tsMenuItem.Tag = "fmHelp"; tsMenuItem.Text = "說明(&H)"; this.msMenu.Items.Add(tsMenuItem); // 建置 HELP 選單 tsMenuItem = new ToolStripMenuItem(); tsMenuItem.Text = "關閉(&C)"; tsMenuItem.Click += new EventHandler(onCloseClick); tsMenuItem.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; tsMenuItem.Padding = new Padding(2, 0, 2, 0); msMenu.Items.Add(tsMenuItem); } private void openMainPage() { string formName = string.Format("{0}.Forms.fmMessage", this.GetType().Namespace); Type type = Type.GetType(formName); if (type != null) { FormsManager.OpenForm(type); } } private void onFunctionClick(object sender, EventArgs e) { ToolStripMenuItem tsmi = (ToolStripMenuItem)sender; Assembly AssemblyForm = Assembly.Load(this.Apps.RuntimeAssembyName); string formName = string.Format("{0}.{1}", this.Apps.RuntimeAssembyName, tsmi.Tag.ToString()); Type type = AssemblyForm.GetType(formName); //MethodInfo entry = AssemblyForm.EntryPoint; //Type asTitle = typeof(AssemblyTitleAttribute); //object[] attrs = AssemblyForm.GetCustomAttributes(asTitle, false); //string sMainType = ((AssemblyTitleAttribute)attrs[0]).Title; //Assembly AssemblyForm = Assembly.LoadFrom(mec.); //MethodInfo entry = AssemblyForm.EntryPoint; //Type asTitle = typeof(AssemblyTitleAttribute); //object[] attrs = AssemblyForm.GetCustomAttributes(asTitle, false); //string sMainType = ((AssemblyTitleAttribute)attrs[0]).Title; //Type type = AssemblyForm.GetType(sMainType); // 非常重要觀念GetType(nameSpace + mainForm key) //Form MdiChildForm = (Form)AssemblyForm.CreateInstance(type.FullName, true); //Type type = Type.GetType(formName); if (type != null) { bool open = FormsManager.OpenForm(type, "Text", tsmi.Text); } } private void onCloseClick(object sender, EventArgs e) { if (this.ActiveMdiChild == null) { return; } string sMessage = "您確定要關閉程式!!"; if (MessageBox.Show(sMessage, "問題", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2).Equals(DialogResult.Yes)) { FormsManager.CloseForm(this.ActiveMdiChild.GetType()); } } } }
using ScheduleService.CustomException; using ScheduleService.Model.Memento; using System; namespace ScheduleService.Model { public class Examination : IOriginator<ExaminationMemento> { private int Id { get; } private Appointment Appointment { get; } private ExaminationType ExaminationType { get; } private ExaminationStatus ExaminationStatus { get; set; } private Patient Patient { get; } private Doctor Doctor { get; } private Room Room { get; } public Examination(ExaminationMemento memento) { Id = memento.Id; Appointment = new Appointment(memento.Appointment); ExaminationStatus = memento.ExaminationStatus; ExaminationType = memento.ExaminationType; Patient = memento.Patient; Doctor = memento.Doctor; Room = memento.Room; } public Examination(Appointment appointment, Patient patient, Doctor doctor, Room room, int id = 0) { Id = id; Appointment = appointment; ExaminationType = ExaminationType.Examination; ExaminationStatus = ExaminationStatus.Created; Patient = patient; Doctor = doctor; Room = room; } public Examination(DateTime dateTime, Patient patient, Doctor doctor, Room room, int id = 0) { Id = id; Appointment = new Appointment(dateTime); ExaminationType = ExaminationType.Examination; ExaminationStatus = ExaminationStatus.Created; Patient = patient; Doctor = doctor; Room = room; } public bool IsAvailable() { return Patient.IsAvailable(Appointment) && Doctor.IsAvailable(Appointment) && Room.IsAvailable(Appointment); } public void Cancel(DateTime timeLimit) { if (ExaminationStatus == ExaminationStatus.Finished) throw new ValidationException("Finished examinations cannot be canceled."); if (ExaminationStatus == ExaminationStatus.Canceled) throw new ValidationException("Examination is already canceled."); if (IsBefore(timeLimit)) throw new ValidationException("The limit limit for canceling the examination has passed."); ExaminationStatus = ExaminationStatus.Canceled; } public bool IsBefore(DateTime timeLimit) { return Appointment.Value <= timeLimit; } public ExaminationMemento GetMemento() { return new ExaminationMemento() { Id = Id, Appointment = Appointment.Value, ExaminationStatus = ExaminationStatus, ExaminationType = ExaminationType, Doctor = Doctor, Patient = Patient, Room = Room }; } private void Validate() { if (ExaminationType == ExaminationType.Examination && Room.RoomType != RoomType.Examination) throw new ValidationException("Examinations have to be performed in examination rooms."); if (ExaminationType == ExaminationType.Surgery && Room.RoomType != RoomType.Surgery) throw new ValidationException("Surgeries have to be performed in operating rooms."); } } }
using System; namespace AppForMigrationDataFromKmiacDB { class Program { static void Main(string[] args) { Console.WriteLine("Hello 4World!"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.OleDb; namespace CS350_BackendAPI { class Database { static string dataFileLocation = @"E:\1. University Of Northern Colorado\6. Fall 2017\Software Engineering (CS 350-008)\CS350-BackendAPI\CS350-BackendAPI\SocialMedia.accdb"; static string oleConnectionString = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", dataFileLocation); //Method: Get Friends public static List<double> GetFriends(double UserID) { string getFriendsQuery = "SELECT * FROM Friends WHERE [User1] = @UserID;"; List<double> Friends = new List<double>(); using (OleDbConnection oleConn = new OleDbConnection(oleConnectionString)) { oleConn.Open(); using (OleDbCommand oleCmd = new OleDbCommand(getFriendsQuery, oleConn)) { oleCmd.Parameters.AddWithValue("@UserID", UserID); using (OleDbDataReader dr = oleCmd.ExecuteReader()) { while (dr.Read()) { Friends.Add(double.Parse(dr.GetValue(2).ToString())); } } } } return Friends; } //Method: Add Friendship public static bool AddFriendship(double User1ID, double User2ID) { string insertQuery = "INSERT INTO Friends ([User1],[User2]) VALUES (@User1,@User2);"; try { using (OleDbConnection oleConn = new OleDbConnection(oleConnectionString)) { oleConn.Open(); using (OleDbTransaction oleTrans = oleConn.BeginTransaction()) { try { using (OleDbCommand oleCmd = new OleDbCommand(insertQuery, oleConn, oleTrans)) { oleCmd.Parameters.AddWithValue("@User1", User1ID); oleCmd.Parameters.AddWithValue("@User2", User2ID); oleCmd.ExecuteNonQuery(); } using (OleDbCommand oleCmd = new OleDbCommand(insertQuery, oleConn, oleTrans)) { oleCmd.Parameters.AddWithValue("@User1", User2ID); oleCmd.Parameters.AddWithValue("@User2", User1ID); oleCmd.ExecuteNonQuery(); } oleTrans.Commit(); return true; } catch (Exception ex) { oleTrans.Rollback(); throw ex; } } } } catch { return false; } } //Method: Remove Friendship public static bool RemoveFriendship(double User1ID, double User2ID) { string insertQuery = "DELETE FROM Friends WHERE [User1] = @User1 And [User2] = @User2;"; try { using (OleDbConnection oleConn = new OleDbConnection(oleConnectionString)) { oleConn.Open(); using (OleDbTransaction oleTrans = oleConn.BeginTransaction()) { try { using (OleDbCommand oleCmd = new OleDbCommand(insertQuery, oleConn, oleTrans)) { oleCmd.Parameters.AddWithValue("@User1", User1ID); oleCmd.Parameters.AddWithValue("@User2", User2ID); oleCmd.ExecuteNonQuery(); } using (OleDbCommand oleCmd = new OleDbCommand(insertQuery, oleConn, oleTrans)) { oleCmd.Parameters.AddWithValue("@User1", User2ID); oleCmd.Parameters.AddWithValue("@User2", User1ID); oleCmd.ExecuteNonQuery(); } oleTrans.Commit(); return true; } catch (Exception ex) { oleTrans.Rollback(); throw ex; } } } } catch { return false; } } //Method: Get Posts public static List<Post> GetPosts(double UserID) { string selectQuery = "SELECT * FROM Posts WHERE [UserID] = @UserID;"; List<Post> Posts = new List<Post>(); using (OleDbConnection oleConn = new OleDbConnection(oleConnectionString)) { oleConn.Open(); using (OleDbCommand oleCmd = new OleDbCommand(selectQuery, oleConn)) { oleCmd.Parameters.AddWithValue("@UserID", UserID); using (OleDbDataReader dr = oleCmd.ExecuteReader()) { while (dr.Read()) { Post post = new Post(double.Parse(dr.GetValue(0).ToString()),double.Parse(dr.GetValue(1).ToString()), dr.GetValue(2).ToString(), dr.GetValue(3).ToString(), DateTime.Parse(dr.GetValue(4).ToString())); Posts.Add(post); } } } } return Posts; } //Method: Add Post public static Post AddPost(double userID, string Title, string Content) { string inserQuery = "INSERT INTO Posts ([UserID],[Title],[Content],[TimeStamp]) VALUES (@UserID, @Title, @Content, @Timestamp);"; string getIDQuery = "SELECT @@Identity;"; using (OleDbConnection oleConn = new OleDbConnection(oleConnectionString)) { oleConn.Open(); using (OleDbTransaction oleTrans = oleConn.BeginTransaction()) { try { DateTime now = DateTime.Now; using (OleDbCommand oleCmd = new OleDbCommand(inserQuery, oleConn, oleTrans)) { oleCmd.Parameters.AddWithValue("@UserID", userID); oleCmd.Parameters.AddWithValue("@Title", Title); oleCmd.Parameters.AddWithValue("@Content", Content); oleCmd.Parameters.AddWithValue("@TimeStamp", now); } double postID = 0; using (OleDbCommand oleCmd = new OleDbCommand(getIDQuery, oleConn, oleTrans)) { postID = (int)oleCmd.ExecuteScalar(); } Post post = new Post(postID, userID, Title, Content, now); oleTrans.Commit(); return post; } catch (Exception ex) { oleTrans.Rollback(); throw ex; } } } } //Method: Remove Post public static bool RemovePost(double postID) { string inserQuery = "DELETE FROM Posts WHERE [PostID] = @PostID;"; try { using (OleDbConnection oleConn = new OleDbConnection(oleConnectionString)) { oleConn.Open(); using (OleDbTransaction oleTrans = oleConn.BeginTransaction()) { try { using (OleDbCommand oleCmd = new OleDbCommand(inserQuery, oleConn, oleTrans)) { oleCmd.Parameters.AddWithValue("@PostID", postID); oleCmd.ExecuteNonQuery(); } oleTrans.Commit(); return true; } catch (Exception ex) { oleTrans.Rollback(); throw ex; } } } } catch { return false; } } //Method: Clear All Data public static bool ClearAll() { string deleteUsersQuery = "DELETE * FROM Users;"; string deleteFriendshipsQuery = "DELETE * FROM Friends;"; string deletePostsQuery = "DELETE * FROM Posts;"; try { using (OleDbConnection oleConn = new OleDbConnection(oleConnectionString)) { oleConn.Open(); using (OleDbTransaction oleTrans = oleConn.BeginTransaction()) { try { using (OleDbCommand oleCmd = new OleDbCommand(deleteUsersQuery, oleConn, oleTrans)) { oleCmd.ExecuteNonQuery(); } using (OleDbCommand oleCmd = new OleDbCommand(deleteFriendshipsQuery, oleConn, oleTrans)) { oleCmd.ExecuteNonQuery(); } using (OleDbCommand oleCmd = new OleDbCommand(deletePostsQuery, oleConn, oleTrans)) { oleCmd.ExecuteNonQuery(); } oleTrans.Commit(); return true; } catch(Exception ex) { oleTrans.Rollback(); throw ex; } } } } catch { return false; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Character : MonoBehaviour { public enum States { idle,moving,hitStun,shocking,attacking} public States state = States.idle; public bool dead = false; public bool hitStun = false; public AudioSource audioSource; public bool friend = false; public Transform target; public float maxDrainEnergy = 10; public float energyLeft = 10; public bool visible = true; public GameObject bullet; // Use this for initialization void Start () { audioSource = GetComponent<AudioSource>(); } // Update is called once per frame void Update () { } public void SetState(States newState) { state = newState; } public void EndKill() { } public void Fire() { //Debug.Log("Fire"); GameObject fireEffect = GameObject.Instantiate(EffectsManager.getInstance().shootEffect); fireEffect.transform.position= transform.position + 0.3f * Vector3.up+2.2f*transform.forward; fireEffect.transform.forward = transform.forward; GameObject thisBullet= GameObject.Instantiate(bullet); thisBullet.transform.position = transform.position + 1f * Vector3.up; thisBullet.transform.forward = transform.forward; thisBullet.GetComponent<DamageArea>().friend = friend; } public virtual void DealDamage(float val) { } }
using System; using System.Collections.Generic; using System.Text; namespace DesignPatterns.Singleton.Example1 { //https://csharpindepth.com/Articles/Singleton public sealed class SingletonLazy { private static readonly Lazy<SingletonLazy> lazy = new Lazy<SingletonLazy> (() => new SingletonLazy()); public static SingletonLazy Instance => lazy.Value; private SingletonLazy() { } } }
using DataAccess.Entities; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace DataAccess { public class ApplicationUser:IdentityUser<Guid> { public ICollection<TblPurchaseOrder> PurchaseOrders { get; set; } public ICollection<TblOrganisation> Organisations { get; set; } public string PersonName { get; set; } public string Organisation { get; set; } public string Address { get; set; } } }
using UnityEngine; using System.Collections.Generic; using System; using System.Threading; using System.Text; using UnityEngine.Events; #if (UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX || UNITY_IOS) using AOT; using System.Runtime.InteropServices; #endif namespace Ardunity { [AddComponentMenu("ARDUnity/CommSocket/HM10")] [HelpURL("https://sites.google.com/site/ardunitydoc/references/commsocket/hm10")] public class HM10 : CommSocket { public string serviceUUID = "FFE0"; public string charUUID = "FFE1"; public float searchTimeout = 5f; private bool _isBleOpen = false; private bool _bleOpenTry = false; private static bool _isSupport = true; private float _searchTimeout = 0f; private bool _threadOnOpen = false; private bool _threadOnOpenFailed = false; private bool _threadOnStartSearch = false; private bool _threadOnStopSearch = false; private bool _threadOnFoundDevice = false; private bool _threadOnErrorClosed = false; private bool _threadOnWriteCompleted = false; private Thread _openThread; private List<byte> _txBuffer = new List<byte>(); private List<byte> _rxBuffer = new List<byte>(); private bool _txWait = false; private bool _getCompleted = false; private string _serviceUUID; private string _charUUID; #if UNITY_ANDROID private AndroidJavaObject _android = null; #elif (UNITY_STANDALONE_OSX || UNITY_IOS) private static bool _bleInitialized = false; private static List<HM10> _commBleList = new List<HM10>(); private delegate void UnityCallbackDelegate(IntPtr arg1, IntPtr arg2); #if UNITY_IOS [DllImport("__Internal")] #else [DllImport("OsxPlugin")] #endif private static extern void bleInitialize([MarshalAs(UnmanagedType.FunctionPtr)]UnityCallbackDelegate unityCallback); #if UNITY_IOS [DllImport("__Internal")] #else [DllImport("OsxPlugin")] #endif private static extern void bleDeinitialize(); #if UNITY_IOS [DllImport("__Internal")] #else [DllImport("OsxPlugin")] #endif private static extern void bleStartScan(string service); #if UNITY_IOS [DllImport("__Internal")] #else [DllImport("OsxPlugin")] #endif private static extern void bleStopScan(); #if UNITY_IOS [DllImport("__Internal")] #else [DllImport("OsxPlugin")] #endif private static extern void bleConnect(string uuid); #if UNITY_IOS [DllImport("__Internal")] #else [DllImport("OsxPlugin")] #endif private static extern void bleDisconnect(string uuid); #if UNITY_IOS [DllImport("__Internal")] #else [DllImport("OsxPlugin")] #endif private static extern void bleDiscoverService(string uuid, string service); #if UNITY_IOS [DllImport("__Internal")] #else [DllImport("OsxPlugin")] #endif private static extern void bleDiscoverCharacteristic(string uuid, string service, string characteristic); #if UNITY_IOS [DllImport("__Internal")] #else [DllImport("OsxPlugin")] #endif private static extern void bleWrite(string uuid, string service, string characteristic, byte[] data, int length, bool withResponse); #if UNITY_IOS [DllImport("__Internal")] #else [DllImport("OsxPlugin")] #endif private static extern void bleRead(string uuid, string service, string characteristic); #if UNITY_IOS [DllImport("__Internal")] #else [DllImport("OsxPlugin")] #endif private static extern void bleSubscribe(string uuid, string service, string characteristic); #if UNITY_IOS [DllImport("__Internal")] #else [DllImport("OsxPlugin")] #endif private static extern void bleUnsubscribe(string uuid, string service, string characteristic); #endif protected override void Awake() { base.Awake(); #if UNITY_ANDROID _serviceUUID = string.Format("0000{0}-0000-1000-8000-00805f9b34fb", serviceUUID); _charUUID = string.Format("0000{0}-0000-1000-8000-00805f9b34fb", charUUID); try { AndroidJavaClass activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject activityContext = activityClass.GetStatic<AndroidJavaObject>("currentActivity"); AndroidJavaClass pluginClass = new AndroidJavaClass("com.ardunity.android.BluetoothLE"); _android = pluginClass.CallStatic<AndroidJavaObject>("GetInstance"); _isSupport = _android.Call<bool>("Initialize", activityContext, gameObject.name, "BleCallback"); if (_isSupport == false) _android = null; } catch(Exception) { _android = null; } if(_android == null) Debug.Log("Android BLE Failed!"); #elif (UNITY_STANDALONE_OSX|| UNITY_IOS) _serviceUUID = serviceUUID; _charUUID = charUUID; _commBleList.Add(this); if(_commBleList.Count == 1) bleInitialize(BleCallbackDelegate); #endif } // Update is called once per frame void Update () { if(_threadOnOpen) { OnOpen.Invoke(); _threadOnOpen = false; } if (_threadOnOpenFailed) { ErrorClose(); OnOpenFailed.Invoke(); _threadOnOpenFailed = false; } if (_threadOnErrorClosed) { ErrorClose(); OnErrorClosed.Invoke(); _threadOnErrorClosed = false; } if (_threadOnStartSearch) { OnStartSearch.Invoke(); _threadOnStartSearch = false; } if (_threadOnStopSearch) { OnStopSearch.Invoke(); _threadOnStopSearch = false; } if (_threadOnFoundDevice) { OnFoundDevice.Invoke(new CommDevice(foundDevices[foundDevices.Count - 1])); _threadOnFoundDevice = false; } if (_threadOnWriteCompleted) { OnWriteCompleted.Invoke(); _threadOnWriteCompleted = false; } if (_searchTimeout > 0f) { _searchTimeout -= Time.deltaTime; if (_searchTimeout <= 0f) StopSearch(); } } void LateUpdate() { if(IsOpen && !_txWait) txWrite(); } void OnDestroy() { #if UNITY_ANDROID #elif (UNITY_STANDALONE_OSX || UNITY_IOS) ErrorClose(); _commBleList.Remove(this); if(_commBleList.Count == 0) bleDeinitialize(); #endif } public bool isSupport { get { #if UNITY_ANDROID return _isSupport; #elif (UNITY_STANDALONE_OSX || UNITY_IOS) if(_bleInitialized) return _isSupport; else return false; #else return false; #endif } } public bool isSearching { get { if(_searchTimeout > 0f) return true; else return false; } } #region Override public override void Open() { StopSearch(); if (IsOpen) return; _openThread = new Thread(openThread); _openThread.Start(); } public override void Close() { if (!IsOpen) return; ErrorClose(); OnClose.Invoke(); } protected override void ErrorClose() { if (_openThread != null) { if (_openThread.IsAlive) _openThread.Abort(); } if(_isBleOpen) { #if UNITY_ANDROID if (_android != null) _android.Call("UnsubscribeCharacteristic", _serviceUUID, _charUUID); #elif (UNITY_STANDALONE_OSX || UNITY_IOS) if (_bleInitialized) bleUnsubscribe(device.address, _serviceUUID, _charUUID); #endif } _rxBuffer.Clear(); #if UNITY_ANDROID if (_android != null) _android.Call("Disconnect"); #elif (UNITY_STANDALONE_OSX || UNITY_IOS) if (_bleInitialized) bleDisconnect(device.address); #endif _isBleOpen = false; _bleOpenTry = false; } public override bool IsOpen { get { return _isBleOpen; } } public override void StartSearch() { _searchTimeout = searchTimeout; #if UNITY_ANDROID if (_android != null) _android.Call("StartScan", _serviceUUID); #elif (UNITY_STANDALONE_OSX || UNITY_IOS) if (_bleInitialized) bleStartScan(_serviceUUID); #endif } public override void StopSearch() { _searchTimeout = 0f; #if UNITY_ANDROID if (_android != null) _android.Call("StopScan"); #elif (UNITY_STANDALONE_OSX || UNITY_IOS) if (_bleInitialized) bleStopScan(); #endif } public override void Write(byte[] data, bool getCompleted = false) { if (data == null) return; if (data.Length == 0) return; _txBuffer.AddRange(data); _getCompleted = getCompleted; } private void txWrite() { if(_txBuffer.Count == 0) { _txWait = false; if(_getCompleted) _threadOnWriteCompleted = true; return; } _txWait = true; byte[] data20 = new byte[Mathf.Min(20, _txBuffer.Count)]; for(int i=0; i<data20.Length; i++) data20[i] = _txBuffer[i]; _txBuffer.RemoveRange(0, data20.Length); #if UNITY_ANDROID if (_android != null) _android.Call("Write", _serviceUUID, _charUUID, data20, true); #elif (UNITY_STANDALONE_OSX || UNITY_IOS) if (_bleInitialized) bleWrite(device.address, _serviceUUID, _charUUID, data20, data20.Length, false); #endif } public override byte[] Read() { if(_rxBuffer.Count > 0) { byte[] bytes = _rxBuffer.ToArray(); _rxBuffer.Clear(); return bytes; } else return null; } #endregion private void openThread() { #if UNITY_ANDROID AndroidJNI.AttachCurrentThread(); #endif _bleOpenTry = false; _txBuffer.Clear(); _txWait = false; #if UNITY_ANDROID if (_android != null) { _android.Call("Connect", device.address); _bleOpenTry = true; } #elif (UNITY_STANDALONE_OSX || UNITY_IOS) if (_bleInitialized) { bleConnect(device.address); _bleOpenTry = true; } #endif if(!_bleOpenTry) { _bleOpenTry = false; _threadOnOpenFailed = true; } #if UNITY_ANDROID AndroidJNI.DetachCurrentThread(); #endif _openThread.Abort(); return; } #if (UNITY_STANDALONE_OSX || UNITY_IOS) [MonoPInvokeCallback(typeof(UnityCallbackDelegate))] private static void BleCallbackDelegate(IntPtr arg1, IntPtr arg2) { string uuid = Marshal.PtrToStringAuto(arg1); string message = Marshal.PtrToStringAuto(arg2); if(_commBleList.Count > 0) { for(int i=0; i<_commBleList.Count; i++) { if(uuid == null) _commBleList[i].BleCallback(message); else { if(_commBleList[i].device.address.Equals(uuid)) _commBleList[i].BleCallback(message); } } } else Debug.Log(message); } #endif private void BleCallback(string message) { if (message == null) return; string[] tokens = message.Split(new char[] { '~' }); if(tokens.Length == 0) return; if(tokens[0].Equals("Initialized")) { Debug.Log("BLE Initialized"); #if (UNITY_STANDALONE_OSX || UNITY_IOS) _bleInitialized = true; #endif } else if(tokens[0].Equals("Deinitialized")) { Debug.Log("BLE Deinitialized"); #if (UNITY_STANDALONE_OSX || UNITY_IOS) _bleInitialized = false; #endif } else if(tokens[0].Equals("NotSupported")) { #if (UNITY_STANDALONE_OSX || UNITY_IOS) Debug.Log("BLE not supported"); _isSupport = false; #endif } else if(tokens[0].Equals("PoweredOff")) { #if (UNITY_STANDALONE_OSX || UNITY_IOS) Debug.Log("BLE Power Off"); #endif } else if(tokens[0].Equals("PoweredOn")) { #if (UNITY_STANDALONE_OSX || UNITY_IOS) Debug.Log("BLE Power On"); #endif } else if(tokens[0].Equals("Unauthorized")) { #if (UNITY_STANDALONE_OSX || UNITY_IOS) Debug.Log("BLE Unauthorized"); #endif } else if(tokens[0].Equals("StateUnknown")) { #if (UNITY_STANDALONE_OSX || UNITY_IOS) Debug.Log("BLE Unauthorized"); #endif } else if(tokens[0].Equals("StartScan")) { Debug.Log("HM10 Start Scanning"); foundDevices.Clear(); _threadOnStartSearch = true; } else if(tokens[0].Equals("StopScan")) { Debug.Log("HM10 Stop Scanning"); _threadOnStopSearch = true; } else if(tokens[0].Equals("ConnectFailed")) { Debug.Log("BLE GATT Connect Failed"); _threadOnOpenFailed = true; } else if(tokens[0].Equals("DiscoveredDevice")) { CommDevice foundDevice = new CommDevice(); foundDevice.name = tokens[1]; foundDevice.address = tokens[2]; for(int i=0; i<foundDevices.Count; i++) { if (foundDevices[i].Equals(foundDevice)) return; } foundDevices.Add(foundDevice); _threadOnFoundDevice = true; } else if(tokens[0].Equals("Disconnected")) { Debug.Log("BLE GATT Disconnected"); if(_isBleOpen) _threadOnErrorClosed = true; else if(_bleOpenTry) _threadOnOpenFailed = true; } else if(tokens[0].Equals("Connected")) { Debug.Log("BLE GATT Connected"); #if UNITY_ANDROID if (_android != null) _android.Call("DiscoverService", _serviceUUID); #elif (UNITY_STANDALONE_OSX || UNITY_IOS) if (_bleInitialized) bleDiscoverService(device.address, _serviceUUID); #endif } else if(tokens[0].Equals("DiscoveredService")) { Debug.Log("HM10 Discovered Service"); #if UNITY_ANDROID if (_android != null) _android.Call("DiscoverCharacteristic", _serviceUUID, _charUUID); #elif (UNITY_STANDALONE_OSX || UNITY_IOS) if (_bleInitialized) bleDiscoverCharacteristic(device.address, _serviceUUID, _charUUID); #endif } else if(tokens[0].Equals("ErrorDiscoveredService")) { Debug.Log("HM10 Discovered Service Error: " + tokens[1]); _threadOnOpenFailed = true; } else if(tokens[0].Equals("DiscoveredCharacteristic")) { #if UNITY_ANDROID Debug.Log("HM10 Discovered Characteristic"); if(_android != null) _android.Call("SubscribeCharacteristic2", _serviceUUID, _charUUID); #elif (UNITY_STANDALONE_OSX || UNITY_IOS) if(tokens.Length > 1 && !_isBleOpen) { string[] tokens2 = message.Split(new char[] { ':' }); bool foundCharUUID = false; for(int i=0; i<tokens2.Length; i++) { if(_charUUID.Equals(tokens2[i]) == true) { Debug.Log("HM10 Discovered Characteristic"); if(_bleInitialized) { bleSubscribe(device.address, _serviceUUID, _charUUID); } foundCharUUID = true; break; } } if(!foundCharUUID) { Debug.Log(string.Format("Can not find HM-10 Characteristic <{0}>", _charUUID)); _threadOnOpenFailed = true; } } #endif } else if(tokens[0].Equals("ErrorDiscoverCharacteristic")) { Debug.Log("HM10 Discover Characteristic Error: " + tokens[1]); _threadOnOpenFailed = true; } else if(tokens[0].Equals("ErrorWrite")) { Debug.Log("HM10 Write Error: " + tokens[1]); _threadOnErrorClosed = true; } else if(tokens[0].Equals("ErrorSubscribeCharacteristic")) { Debug.Log("HM10 Subscribe Characteristic Error: " + tokens[1]); _threadOnOpenFailed = true; } else if(tokens[0].Equals("SubscribedCharacteristic")) { #if UNITY_ANDROID Debug.Log("HM10 Subscribed Characteristic"); _isBleOpen = true; _bleOpenTry = false; _threadOnOpen = true; #elif (UNITY_STANDALONE_OSX || UNITY_IOS) if(tokens.Length > 1) { if(_charUUID.Equals(tokens[1]) == true) { Debug.Log("HM10 Subscribed Characteristic"); _isBleOpen = true; _bleOpenTry = false; _threadOnOpen = true; } } #endif } else if(tokens[0].Equals("UnSubscribedCharacteristic")) { #if UNITY_ANDROID Debug.Log("HM10 UnSubscribed Characteristic"); #elif (UNITY_STANDALONE_OSX || UNITY_IOS) if(tokens.Length > 1) { if(_charUUID.Equals(tokens[1]) == true) { Debug.Log("HM10 UnSubscribed Characteristic"); } } #endif } else if(tokens[0].Equals("Write")) { if(string.Compare(_charUUID, tokens[1], true) == 0) { txWrite(); } } else if(tokens[0].Equals("ErrorRead")) { Debug.Log("HM10 Read Error: " + tokens[1]); _threadOnErrorClosed = true; } else if(tokens[0].Equals("Read")) { byte[] base64Bytes = Convert.FromBase64String(tokens[2]); if(base64Bytes.Length > 0) { if(string.Compare(_charUUID, tokens[1], true) == 0) { _rxBuffer.AddRange(base64Bytes); } } } else { if(tokens.Length == 1) Debug.Log(tokens[0]); else if(tokens.Length == 2) Debug.Log(tokens[0] + ":" + tokens[1]); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Car_service.Modells; using Car_service.Repositories; using Microsoft.AspNetCore.Mvc; namespace Car_service.Controllers { [Route("api/work")] [ApiController] public class WorkController : ControllerBase { [HttpGet] public ActionResult<IEnumerable<Work>> GetAll() { var works = WorkRepository.GetWorks(); return Ok(works); } [HttpGet("{id}")] public ActionResult<Work> Get(long id) { var work = WorkRepository.GetWorks().FirstOrDefault(x => x.Id == id); if(work != null) { return Ok(work); } else { return NotFound(); } } [HttpPost] public ActionResult Post(Work work) { var works = WorkRepository.GetWorks(); work.Id = GetNewId(works); works.Add(work); WorkRepository.StoreWorks(works); return Ok(); } public ActionResult Put(Work work) { var works = WorkRepository.GetWorks(); var foundedWork = works.FirstOrDefault(innerWork => innerWork.Id == work.Id); if (foundedWork == null) { return NotFound(); } else { foundedWork.CarLicensePlate = work.CarLicensePlate; foundedWork.NameOfCustomer = work.NameOfCustomer; foundedWork.StateOfWork = work.StateOfWork; foundedWork.DetailOfIssues = work.DetailOfIssues; foundedWork.RecordingDate = work.RecordingDate; foundedWork.TypeOfCar = work.TypeOfCar; } WorkRepository.StoreWorks(works); return Ok(); } [HttpDelete("{id}")] public ActionResult Delete(long id) { var works = WorkRepository.GetWorks(); var workToRemove = works.FirstOrDefault(work => work.Id == id); if( workToRemove != null) { works.Remove(workToRemove); WorkRepository.StoreWorks(works); } else { return NotFound(); } return Ok(); } private long GetNewId(IList<Work> works) { long id = 0; foreach (var work in works) { if(id < work.Id) { id = work.Id; } } return id + 1; } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using FiiiChain.Framework; using FiiiChain.IModules; using System; using System.Collections.Generic; using System.Text; namespace FiiiChain.TempData { public static class DbAccessHelper { public static string Version = "0.1.1"; public static IHotDataAccess GetDataAccessInstance() { IHotDataAccess dataAccess = null; var type = RunTime.GetOSPlatform(); switch (type) { case OSPlatformType.Linux: case OSPlatformType.OSX: dataAccess = new LightDbAccess(); break; case OSPlatformType.WINDOWS: dataAccess = new LevelDbAccess(); break; default: LogHelper.Error("other system"); dataAccess = new LightDbAccess(); break; } return dataAccess; } } }
namespace CommandInterpreter { using System; using System.Linq; public class Startup { public static void Main(string[] args) { Execute(); } private static void Execute() { var arr = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .ToArray(); var args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); while (args[0] != "end") { switch (args[0]) { case "reverse": var start = int.Parse(args[2]); var count = int.Parse(args[4]); Reverse(arr, start, count); break; case "sort": start = int.Parse(args[2]); count = int.Parse(args[4]); Sort(arr, start, count); break; case "rollLeft": count = int.Parse(args[1]); RollLeft(arr, count); break; case "rollRight": count = int.Parse(args[1]); RollRight(arr, count); break; default: break; } args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); } Console.WriteLine($"[{string.Join(", ", arr)}]"); } private static void RollRight(string[] arr, int count) { if (count < 0) { Console.WriteLine("Invalid input parameters."); return; } count %= arr.Length; for (int j = 0; j < count; j++) { var last = arr[arr.Length - 1]; for (int i = arr.Length - 1; i > 0; i--) { arr[i] = arr[i - 1]; } arr[0] = last; } } private static void Reverse(string[] arr, int start, int count) { if (start < 0 || start > arr.Length || count < 0 || count > arr.Length || start + count < 0 || start + count > arr.Length) { Console.WriteLine("Invalid input parameters."); return; } var reversed = arr.Skip(start) .Take(count) .Reverse().ToArray(); for (int i = start, j = 0; i < start + count && i < arr.Length; i++, j++) { arr[i] = reversed[j]; } } private static void Sort(string[] arr, int start, int count) { if (start < 0 || start > arr.Length || count < 0 || count > arr.Length || start + count < 0 || start + count > arr.Length) { Console.WriteLine("Invalid input parameters."); return; } var sorted = arr.Skip(start) .Take(count) .OrderBy(x => x) .ToArray(); for (int i = start, j = 0; i < start + count && i < arr.Length; i++, j++) { arr[i] = sorted[j]; } } private static void RollLeft(string[] arr, int count) { if (count < 0) { Console.WriteLine("Invalid input parameters."); return; } count %= arr.Length; for (int j = 0; j < count; j++) { var first = arr[0]; for (int i = 0; i < arr.Length - 1; i++) { arr[i] = arr[i + 1]; } arr[arr.Length - 1] = first; } } } }
using mec.Model.Entities; using mec.Model.Orders; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; namespace mec.Model.Interfaces { [ServiceContract] public interface IOrder { [OperationContract] string GetString(); /// <summary> /// 取得工單流轉卡資訊 /// </summary> /// <param name="workOrder"></param> /// <returns></returns> [OperationContract] IEnumerable<FlowOrderViewModel> GetFlowOrders(FlowOrderParam param); /// <summary> /// 列印流轉卡 /// </summary> /// <param name="param"></param> /// <returns></returns> [OperationContract] IEnumerable<FlowOrderViewModel> GetFlowOrderForPrint(FlowOrderParam param); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing; namespace CS_2_HomeWork { class Program { public static void Start() { Form form = new Form(); Game.Width = 1000; Game.Height = 800; Game.Init(form); Game.Draw(); Application.Run(form); } static void Main(string[] args) { Start(); } } }
using System; using System.Runtime.InteropServices; using Vanara.InteropServices; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; namespace Vanara.PInvoke { /// <summary>Methods and data types found in Crypt32.dll.</summary> public static partial class Crypt32 { /// <summary>Private key pair type.</summary> [PInvokeData("wincrypt.h")] public enum PrivateKeyType { /// <summary>Key exchange</summary> AT_KEYEXCHANGE = 1, /// <summary>Digital signature</summary> AT_SIGNATURE = 2 } /// <summary> /// The CERT_CONTEXT structure contains both the encoded and decoded representations of a certificate. A certificate context returned /// by one of the functions defined in Wincrypt.h must be freed by calling the CertFreeCertificateContext function. The /// CertDuplicateCertificateContext function can be called to make a duplicate copy (which also must be freed by calling CertFreeCertificateContext). /// </summary> [PInvokeData("wincrypt.h")] [StructLayout(LayoutKind.Sequential)] public struct CERT_CONTEXT { /// <summary> /// Type of encoding used. It is always acceptable to specify both the certificate and message encoding types by combining them /// with a bitwise-OR operation. /// </summary> public uint dwCertEncodingType; /// <summary>A pointer to a buffer that contains the encoded certificate.</summary> public IntPtr pbCertEncoded; /// <summary>The size, in bytes, of the encoded certificate.</summary> public uint cbCertEncoded; /// <summary>The address of a CERT_INFO structure that contains the certificate information.</summary> public IntPtr pCertInfo; /// <summary>A handle to the certificate store that contains the certificate context.</summary> public IntPtr hCertStore; } /// <summary> /// The CERT_EXTENSION structure contains the extension information for a certificate, Certificate Revocation List (CRL) or /// Certificate Trust List (CTL). /// </summary> [PInvokeData("wincrypt.h")] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CERT_EXTENSION { /// <summary> /// Object identifier (OID) that specifies the structure of the extension data contained in the Value member. For specifics on /// extension OIDs and their related structures, see X.509 Certificate Extension Structures. /// </summary> public StrPtrAnsi pszObjId; /// <summary> /// If TRUE, any limitations specified by the extension in the Value member of this structure are imperative. If FALSE, /// limitations set by this extension can be ignored. /// </summary> [MarshalAs(UnmanagedType.Bool)] public bool fCritical; /// <summary> /// A CRYPT_OBJID_BLOB structure that contains the encoded extension data. The cbData member of Value indicates the length in /// bytes of the pbData member. The pbData member byte string is the encoded extension.e /// </summary> public CRYPTOAPI_BLOB Value; } /// <summary>The CERT_INFO structure contains the information of a certificate.</summary> [PInvokeData("wincrypt.h")] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CERT_INFO { /// <summary>The version number of a certificate.</summary> public uint dwVersion; /// <summary> /// A BLOB that contains the serial number of a certificate. The least significant byte is the zero byte of the pbData member of /// SerialNumber. The index for the last byte of pbData, is one less than the value of the cbData member of SerialNumber. The /// most significant byte is the last byte of pbData. Leading 0x00 or 0xFF bytes are removed. For more information, see CertCompareIntegerBlob. /// </summary> public CRYPTOAPI_BLOB SerialNumber; /// <summary> /// A CRYPT_ALGORITHM_IDENTIFIER structure that contains the signature algorithm type and encoded additional encryption parameters. /// </summary> public CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; /// <summary>The name, in encoded form, of the issuer of the certificate.</summary> public CRYPTOAPI_BLOB Issuer; /// <summary> /// Date and time before which the certificate is not valid. For dates between 1950 and 2049 inclusive, the date and time is /// encoded Coordinated Universal Time (Greenwich Mean Time) format in the form YYMMDDHHMMSS. This member uses a two-digit year /// and is precise to seconds. For dates before 1950 or after 2049, encoded generalized time is used. Encoded generalized time is /// in the form YYYYMMDDHHMMSSMMM, using a four-digit year, and is precise to milliseconds. Even though generalized time supports /// millisecond resolution, the NotBefore time is only precise to seconds. /// </summary> public FILETIME NotBefore; /// <summary> /// Date and time after which the certificate is not valid. For dates between 1950 and 2049 inclusive, the date and time is /// encoded Coordinated Universal Time format in the form YYMMDDHHMMSS. This member uses a two-digit year and is precise to /// seconds. For dates before 1950 or after 2049, encoded generalized time is used. Encoded generalized time is in the form /// YYYYMMDDHHMMSSMMM, using a four-digit year, and is precise to milliseconds. Even though generalized time supports millisecond /// resolution, the NotAfter time is only precise to seconds. /// </summary> public FILETIME NotAfter; /// <summary>The encoded name of the subject of the certificate.</summary> public CRYPTOAPI_BLOB Subject; /// <summary> /// A CERT_PUBLIC_KEY_INFO structure that contains the encoded public key and its algorithm. The PublicKey member of the /// CERT_PUBLIC_KEY_INFO structure contains the encoded public key as a CRYPT_BIT_BLOB, and the Algorithm member contains the /// encoded algorithm as a CRYPT_ALGORITHM_IDENTIFIER. /// </summary> public CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo; /// <summary>A BLOB that contains a unique identifier of the issuer.</summary> public CRYPTOAPI_BLOB IssuerUniqueId; /// <summary>A BLOB that contains a unique identifier of the subject.</summary> public CRYPTOAPI_BLOB SubjectUniqueId; /// <summary>The number of elements in the rgExtension array.</summary> public uint cExtension; /// <summary>An array of pointers to CERT_EXTENSION structures, each of which contains extension information about the certificate.</summary> public IntPtr rgExtension; } /// <summary>The CERT_PUBLIC_KEY_INFO structure contains a public key and its algorithm.</summary> [PInvokeData("wincrypt.h")] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CERT_PUBLIC_KEY_INFO { /// <summary>CRYPT_ALGORITHM_IDENTIFIER structure that contains the public key algorithm type and associated additional parameters.</summary> public CRYPT_ALGORITHM_IDENTIFIER Algorithm; /// <summary>BLOB containing an encoded public key.</summary> public CRYPTOAPI_BLOB PublicKey; } /// <summary> /// The CRYPT_ALGORITHM_IDENTIFIER structure specifies an algorithm used to encrypt a private key. The structure includes the object /// identifier (OID) of the algorithm and any needed parameters for that algorithm. The parameters contained in its CRYPT_OBJID_BLOB /// are encoded. /// </summary> [PInvokeData("wincrypt.h")] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CRYPT_ALGORITHM_IDENTIFIER { /// <summary>An OID of an algorithm.</summary> public StrPtrAnsi pszObjId; /// <summary> /// A BLOB that provides encoded algorithm-specific parameters. In many cases, there are no parameters. This is indicated by /// setting the cbData member of the Parameters BLOB to zero. /// </summary> public CRYPTOAPI_BLOB Parameters; } /// <summary> /// The BLOB structure contains an arbitrary array of bytes. The structure definition includes aliases appropriate to the various /// functions that use it. /// </summary> [PInvokeData("wincrypt.h")] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CRYPTOAPI_BLOB { /// <summary>A DWORD variable that contains the count, in bytes, of data.</summary> public uint cbData; /// <summary>A pointer to the data buffer.</summary> public IntPtr pbData; } /*CertAddCertificateContextToStore CertAddCertificateLinkToStore CertAddCRLContextToStore CertAddCRLLinkToStore CertAddCTLContextToStore CertAddCTLLinkToStore CertAddEncodedCertificateToStore CertAddEncodedCertificateToSystemStore CertAddEncodedCRLToStore CertAddEncodedCTLToStore CertAddEnhancedKeyUsageIdentifier CertAddRefServerOcspResponse CertAddRefServerOcspResponseContext CertAddSerializedElementToStore CertAddStoreToCollection CertAlgIdToOID CertCloseServerOcspResponse CertCloseStore CertCompareCertificate CertCompareCertificateName CertCompareIntegerBlob CertComparePublicKeyInfo CertControlStore CertCreateCertificateChainEngine CertCreateCertificateContext CertCreateContext CertCreateCRLContext CertCreateCTLContext CertCreateCTLEntryFromCertificateContextProperties CertCreateSelfSignCertificate CertDeleteCertificateFromStore CertDeleteCRLFromStore CertDeleteCTLFromStore CertDuplicateCertificateChain CertDuplicateCertificateContext CertDuplicateCRLContext CertDuplicateCTLContext CertDuplicateStore CertEnumCertificateContextProperties CertEnumCertificatesInStore CertEnumCRLContextProperties CertEnumCRLsInStore CertEnumCTLContextProperties CertEnumCTLsInStore CertEnumPhysicalStore CertEnumSubjectInSortedCTL CertEnumSystemStore CertEnumSystemStoreLocation CertFindAttribute CertFindCertificateInCRL CertFindCertificateInStore CertFindChainInStore CertFindCRLInStore CertFindCTLInStore CertFindExtension CertFindRDNAttr CertFindSubjectInCTL CertFindSubjectInSortedCTL CertFreeCertificateChain CertFreeCertificateChainEngine CertFreeCertificateChainList CertFreeCertificateContext CertFreeCRLContext CertFreeCTLContext CertFreeServerOcspResponseContext CertGetCertificateChain CertGetCertificateContextProperty CertGetCRLContextProperty CertGetCRLFromStore CertGetCTLContextProperty CertGetEnhancedKeyUsage CertGetIntendedKeyUsage CertGetIssuerCertificateFromStore CertGetNameString CertGetPublicKeyLength CertGetServerOcspResponseContext CertGetStoreProperty CertGetSubjectCertificateFromStore CertGetValidUsages CertIsRDNAttrsInCertificateName CertIsStrongHashToSign CertIsValidCRLForCertificate CertNameToStr CertOIDToAlgId CertOpenServerOcspResponse CertOpenStore CertOpenSystemStore CertRDNValueToStr CertRegisterPhysicalStore CertRegisterSystemStore CertRemoveEnhancedKeyUsageIdentifier CertRemoveStoreFromCollection CertResyncCertificateChainEngine CertRetrieveLogoOrBiometricInfo CertSaveStore CertSelectCertificateChains CertSerializeCertificateStoreElement CertSerializeCRLStoreElement CertSerializeCTLStoreElement CertSetCertificateContextPropertiesFromCTLEntry CertSetCertificateContextProperty CertSetCRLContextProperty CertSetCTLContextProperty CertSetEnhancedKeyUsage CertSetStoreProperty CertStrToName CertUnregisterPhysicalStore CertUnregisterSystemStore CertVerifyCertificateChainPolicy CertVerifyCRLRevocation CertVerifyCRLTimeValidity CertVerifyCTLUsage CertVerifyRevocation CertVerifySubjectCertificateContext CertVerifyTimeValidity CertVerifyValidityNesting CryptAcquireCertificatePrivateKey CryptBinaryToString CryptCreateKeyIdentifierFromCSP CryptDecodeMessage CryptDecodeObject CryptDecodeObjectEx CryptDecryptAndVerifyMessageSignature CryptDecryptMessage CryptEncodeObject CryptEncodeObjectEx CryptEncryptMessage CryptEnumKeyIdentifierProperties CryptEnumOIDFunction CryptEnumOIDInfo CryptExportPublicKeyInfo CryptExportPublicKeyInfoEx CryptExportPublicKeyInfoFromBCryptKeyHandle CryptFindCertificateKeyProvInfo CryptFindLocalizedName CryptFindOIDInfo CryptFormatObject CryptFreeOIDFunctionAddress CryptGetDefaultOIDDllList CryptGetDefaultOIDFunctionAddress CryptGetKeyIdentifierProperty CryptGetMessageCertificates CryptGetMessageSignerCount CryptGetOIDFunctionAddress CryptGetOIDFunctionValue CryptHashCertificate CryptHashCertificate2 CryptHashMessage CryptHashPublicKeyInfo CryptHashToBeSigned CryptImportPublicKeyInfo CryptImportPublicKeyInfoEx CryptImportPublicKeyInfoEx2 CryptInitOIDFunctionSet CryptInstallDefaultContext CryptInstallOIDFunctionAddress CryptMemAlloc CryptMemFree CryptMemRealloc CryptMsgCalculateEncodedLength CryptMsgClose CryptMsgControl CryptMsgCountersign CryptMsgCountersignEncoded CryptMsgDuplicate CryptMsgEncodeAndSignCTL CryptMsgGetAndVerifySigner CryptMsgGetParam CryptMsgOpenToDecode CryptMsgOpenToEncode CryptMsgSignCTL CryptMsgUpdate CryptMsgVerifyCountersignatureEncoded CryptMsgVerifyCountersignatureEncodedEx CryptQueryObject CryptRegisterDefaultOIDFunction CryptRegisterOIDFunction CryptRegisterOIDInfo CryptRetrieveTimeStamp CryptSetKeyIdentifierProperty CryptSetOIDFunctionValue CryptSignAndEncodeCertificate CryptSignAndEncryptMessage CryptSignCertificate CryptSignMessage CryptSignMessageWithKey CryptStringToBinary CryptUninstallDefaultContext CryptUnregisterDefaultOIDFunction CryptUnregisterOIDFunction CryptUnregisterOIDInfo CryptVerifyCertificateSignature CryptVerifyCertificateSignatureEx CryptVerifyDetachedMessageHash CryptVerifyDetachedMessageSignature CryptVerifyMessageHash CryptVerifyMessageSignature CryptVerifyMessageSignatureWithKey CryptVerifyTimeStampSignature PFXExportCertStore PFXExportCertStoreEx PFXImportCertStore PFXIsPFXBlob PFXVerifyPassword*/ } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using PalinLibrary; namespace PalendromeTest { [TestClass] public class PTest :PalinLibrary.PalenLib { [TestMethod] public void TestMethod1() { PalenLib PTest = new PalenLib(); Assert.AreEqual(PTest.palendromeCheck("aba"), true); } [TestMethod] public void TestMethod2() { PalenLib PTest = new PalenLib(); Assert.AreEqual(PTest.palendromeCheck("aba, ."), true); } [TestMethod] public void TestMethod3() { PalenLib PTest = new PalenLib(); Assert.AreEqual(PTest.palendromeCheck("abas"), false); } [TestMethod] public void TestMethod4() { PalenLib PTest = new PalenLib(); Assert.AreEqual(PTest.palendromeCheck("a"), true); } [TestMethod] public void TestMethod5() { PalenLib PTest = new PalenLib(); Assert.AreEqual(PTest.palendromeCheck("aa"), true); } [TestMethod] public void TestMethod6() { PalenLib PTest = new PalenLib(); Assert.AreEqual(PTest.palendromeCheck("11"), true); } [TestMethod] public void TestMethod7() { PalenLib PTest = new PalenLib(); Assert.AreEqual(PTest.palendromeCheck("1"), true); } [TestMethod] public void TestMethod8() { PalenLib PTest = new PalenLib(); Assert.AreEqual(PTest.palendromeCheck("nurses run"), true); } [TestMethod] public void TestMethod9() { PalenLib PTest = new PalenLib(); Assert.AreEqual(PTest.palendromeCheck("racecaR"), true); } [TestMethod] public void TestMethod10() { PalenLib PTest = new PalenLib(); Assert.AreEqual(PTest.palendromeCheck("1221"), true); } [TestMethod] public void TestMethod11() { PalenLib PTest = new PalenLib(); Assert.AreEqual(PTest.palendromeCheck("never odd, or even."), true); } [TestMethod] public void TestMethod12() { PalenLib PTest = new PalenLib(); Assert.AreEqual(PTest.palendromeCheck("one two one"), false); } [TestMethod] public void TestMethod13() { PalenLib PTest = new PalenLib(); Assert.AreEqual(PTest.palendromeCheck("123abccba123"), false); } } }
using System; namespace AxiEndPoint.EndPointClient.Transfer { [Serializable] public class CommandParameter { public string Name { get; set; } public object Value { get; set; } public int Direction { get; set; } } }
namespace Ricky.Infrastructure.Core.Generic { public enum OrderDirection { /// <summary> /// Represents an ascendant (A-Z) ordering. /// </summary> Ascendant = 0, /// <summary> /// Represents a descendant (Z-A) ordering. /// </summary> Descendant = 1 } }
/* * MIT License * Copyright (c) 2018 SPARKCREATIVE * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @author Noriyuki Hiromoto <hrmtnryk@sparkfx.jp> */ using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; using UnityEditor; namespace SPCR { [CanEditMultipleObjects] [CustomEditor(typeof(SPCRJointDynamicsController))] public class SPCRJointDynamicsControllerInspector : Editor { public enum UpdateJointConnectionType { Default, SortNearPointXYZ, SortNearPointXZ, SortNearPointXYZ_FixedBeginEnd, SortNearPointXZ_FixedBeginEnd, } public static bool Foldout(bool display, string title, Color color) { var backgroundColor = GUI.backgroundColor; GUI.backgroundColor = color; var style = new GUIStyle("ShurikenModuleTitle"); style.font = new GUIStyle(EditorStyles.label).font; style.border = new RectOffset(15, 7, 4, 4); style.fixedHeight = 22; style.contentOffset = new Vector2(20f, -2f); var rect = GUILayoutUtility.GetRect(16f, 22f, style); GUI.Box(rect, title, style); var e = Event.current; var toggleRect = new Rect(rect.x + 4f, rect.y + 2f, 13f, 13f); if (e.type == EventType.Repaint) { EditorStyles.foldout.Draw(toggleRect, false, false, display, false); } if (e.type == EventType.MouseDown && rect.Contains(e.mousePosition)) { display = !display; e.Use(); } GUI.backgroundColor = backgroundColor; return display; } public override void OnInspectorGUI() { serializedObject.Update(); var controller = target as SPCRJointDynamicsController; GUILayout.Space(8); controller.InspectorLang = (SPCRJointDynamicsController.eInspectorLang)EditorGUILayout.EnumPopup("言語(Language)", controller.InspectorLang); var Lang = (int)controller.InspectorLang; var TextShrink = new string[] { "伸びた時縮む力", "Shrink when stretched" }[Lang]; var TextStretch = new string[] { "縮む時伸びる力", "Stretch when shrinking" }[Lang]; var TextIndividual = new string[] { "個別設定", "Individual setting" }[Lang]; var TextConstraintForce = new string[] { "拘束力", "Constraint Force" }[Lang]; var TextCurve = new string[] { "カーブ", "Curve" }[Lang]; controller.Name = EditorGUILayout.TextField(new string[] { "名称", "Name" }[Lang], controller.Name); controller.Opened_BaseSettings = Foldout(controller.Opened_BaseSettings, new string[] { "基本設定", "Basic settings" }[Lang], new Color(1.0f, 0.7f, 1.0f)); if (controller.Opened_BaseSettings) { var _RootTransform = (Transform)EditorGUILayout.ObjectField(new GUIContent(new string[] { "親 Transform", "Parent Transform" }[Lang]), controller._RootTransform, typeof(Transform), true); if (controller._RootTransform != _RootTransform) { controller._RootTransform = _RootTransform; EditorUtility.SetDirty(controller); } if (GUILayout.Button(new GUIContent(new string[] { "ルートの点群自動検出", "Automatically detect the root points" }[Lang]), GUILayout.Height(22.0f))) { SearchRootPoints(controller); } if (EditorGUILayout.PropertyField(serializedObject.FindProperty("_RootPointTbl"), new GUIContent(new string[] { "ルートの点群", "Root points" }[Lang]), true)) { EditorUtility.SetDirty(controller); } GUILayout.Space(5); if (EditorGUILayout.PropertyField(serializedObject.FindProperty("_ColliderTbl"), new GUIContent(new string[] { "コライダー", "Colliders" }[Lang]), true)) { EditorUtility.SetDirty(controller); } if (EditorGUILayout.PropertyField(serializedObject.FindProperty("_PointGrabberTbl"), new GUIContent(new string[] { "グラバー", "Grabbers" }[Lang]), true)) { EditorUtility.SetDirty(controller); } } controller.Opened_PhysicsSettings = Foldout(controller.Opened_PhysicsSettings, new string[] { "物理設定", "Physics settings" }[Lang], new Color(1.0f, 1.0f, 0.7f)); if (controller.Opened_PhysicsSettings) { var _UpdateTiming = (SPCRJointDynamicsController.UpdateTiming)EditorGUILayout.EnumPopup(new string[] { "更新タイミング", "Update timing" }[Lang], controller._UpdateTiming); if (controller._UpdateTiming != _UpdateTiming) { controller._UpdateTiming = _UpdateTiming; EditorUtility.SetDirty(controller); } if (controller._UpdateTiming == SPCRJointDynamicsController.UpdateTiming.LateUpdate) UpdateToggle(new string[] { "LateUpdate安定化", "LateUpdate stabilization" }[Lang], controller, ref controller._IsLateUpdateStabilization); if (controller._IsLateUpdateStabilization) { UpdateIntSlider(new string[] { "安定化フレームレート", "FrameRate for Stabilization" }[Lang], controller, ref controller._StabilizationFrameRate, 10, 240); } UpdateIntSlider(new string[] { "演算安定化回数", "Number of Relaxation" }[Lang], controller, ref controller._Relaxation, 1, 16); UpdateIntSlider(new string[] { "演算分割数", "Number of calculation steps" }[Lang], controller, ref controller._SubSteps, 1, 16); GUILayout.Space(8); UpdateToggle(new string[] { "物理リセットを拒否", "Reject physics reset" }[Lang], controller, ref controller._IsCancelResetPhysics); GUILayout.Space(8); UpdateToggle(new string[] { "質点とコライダーの衝突判定をする", "Point and collider collide" }[Lang], controller, ref controller._IsEnableColliderCollision); GUILayout.Space(8); UpdateToggle(new string[] { "質点と床の衝突判定をする", "Point and floor collide" }[Lang], controller, ref controller._IsEnableFloorCollision); if (controller._IsEnableFloorCollision) { UpdateFloat(new string[] { "床の高さ", "Floor height" }[Lang], controller, ref controller._FloorHeight); } GUILayout.Space(8); UpdateIntSlider(new string[] { "詳細な衝突判定の最大分割数", "Max divisions for collision detection" }[Lang], controller, ref controller._DetailHitDivideMax, 0, 16); GUILayout.Space(8); UpdateToggle(new string[] { "表面衝突", "Surface collision" }[Lang], controller, ref controller._IsEnableSurfaceCollision); if (controller._IsEnableSurfaceCollision) { UpdateIntSlider(new string[] { "表面衝突分割数", "Surface collision division" }[Lang], controller, ref controller._SurfaceCollisionDivision, 1, 16); } GUILayout.Space(8); UpdateFloat(new string[] { "ルートの最大移動距離", "Maximum move distance of root" }[Lang], controller, ref controller._RootSlideLimit); UpdateFloat(new string[] { "ルートの最大回転角", "Maximum rotate angle of root" }[Lang], controller, ref controller._RootRotateLimit); GUILayout.Space(8); UpdateVector3(new string[] { "重力", "" }[Lang], controller, ref controller._Gravity); UpdateVector3(new string[] { "風力", "" }[Lang], controller, ref controller._WindForce); GUILayout.Space(8); UpdateCurve(new string[] { "質量", "Mass" }[Lang], controller, ref controller._MassScaleCurve); UpdateCurve(new string[] { "重力", "Gravity scale" }[Lang], controller, ref controller._GravityScaleCurve); UpdateCurve(new string[] { "風力", "Wind force scale" }[Lang], controller, ref controller._WindForceScaleCurve); UpdateCurve(new string[] { "空気抵抗", "Resistance" }[Lang], controller, ref controller._ResistanceCurve); UpdateCurve(new string[] { "硬さ", "Hardness" }[Lang], controller, ref controller._HardnessCurve); UpdateCurve(new string[] { "摩擦", "Friction" }[Lang], controller, ref controller._FrictionCurve); GUILayout.Space(8); UpdateToggle(new string[] { "アニメーションを参照する", "Refer to animation" }[Lang], controller, ref controller._IsReferToAnimation); } controller.Opened_ConstraintSettings = Foldout(controller.Opened_ConstraintSettings, new string[] { "拘束設定", "Constraint settings" }[Lang], new Color(0.7f, 1.0f, 1.0f)); if (controller.Opened_ConstraintSettings) { EditorGUILayout.BeginVertical(GUI.skin.box); UpdateToggle(new string[] { "水平拘束のループ", "Horizontal Point Loop" }[Lang], controller, ref controller._IsLoopRootPoints); EditorGUILayout.EndVertical(); GUILayout.Space(5); EditorGUILayout.BeginVertical(GUI.skin.box); Titlebar(new string[] { "水平方向スライダージョイント", "Horizontal Slider Joint" }[Lang], new Color(96, 96, 96)); UpdateCurve(new string[] { "伸び", "Expand Limit" }[Lang], controller, ref controller._SliderJointLengthCurve); UpdateCurve(new string[] { "バネ", "Spring" }[Lang], controller, ref controller._SliderJointSpringCurve); EditorGUILayout.EndVertical(); GUILayout.Space(5); EditorGUILayout.BeginVertical(GUI.skin.box); Titlebar(new string[] { "拘束力の一括設定", "Common Parameter" }[Lang], new Color(96, 96, 96)); EditorGUILayout.BeginVertical(GUI.skin.box); UpdateSlider(TextShrink, controller, ref controller._AllShrink, 0.0f, 1.0f); UpdateCurve(TextCurve, controller, ref controller._AllShrinkScaleCurve); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); UpdateSlider(TextStretch, controller, ref controller._AllStretch, 0.0f, 1.0f); UpdateCurve(TextCurve, controller, ref controller._AllStretchScaleCurve); EditorGUILayout.EndVertical(); EditorGUILayout.EndVertical(); GUILayout.Space(5); EditorGUILayout.BeginVertical(GUI.skin.box); Titlebar(new string[] { "垂直構造", "Structural (Vertical)" }[Lang], new Color(96, 96, 96)); if (controller._IsComputeStructuralVertical) { EditorGUILayout.BeginVertical(GUI.skin.box); TitlebarSub(TextShrink, new Color(192, 192, 192)); UpdateToggle(TextIndividual, controller, ref controller._IsAllStructuralShrinkVertical, true); if (!controller._IsAllStructuralShrinkVertical) { EditorGUILayout.BeginVertical(GUI.skin.box); UpdateSlider(TextConstraintForce, controller, ref controller._StructuralShrinkVertical, 0.0f, 1.0f); UpdateCurve(TextCurve, controller, ref controller._StructuralShrinkVerticalScaleCurve); EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); TitlebarSub(TextStretch, new Color(192, 192, 192)); UpdateToggle(TextIndividual, controller, ref controller._IsAllStructuralStretchVertical, true); if (!controller._IsAllStructuralStretchVertical) { EditorGUILayout.BeginVertical(GUI.skin.box); UpdateCurve(TextConstraintForce, controller, ref controller._StructuralStretchVerticalScaleCurve); UpdateSlider(TextCurve, controller, ref controller._StructuralStretchVertical, 0.0f, 1.0f); EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); Titlebar(new string[] { "水平構造", "Structural (Horizontal)" }[Lang], new Color(96, 96, 96)); if (controller._IsComputeStructuralHorizontal) { EditorGUILayout.BeginVertical(GUI.skin.box); TitlebarSub(TextShrink, new Color(192, 192, 192)); UpdateToggle(TextIndividual, controller, ref controller._IsAllStructuralShrinkHorizontal, true); if (!controller._IsAllStructuralShrinkHorizontal) { EditorGUILayout.BeginVertical(GUI.skin.box); UpdateSlider(TextConstraintForce, controller, ref controller._StructuralShrinkHorizontal, 0.0f, 1.0f); UpdateCurve(TextCurve, controller, ref controller._StructuralShrinkHorizontalScaleCurve); EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); TitlebarSub(TextStretch, new Color(192, 192, 192)); UpdateToggle(TextIndividual, controller, ref controller._IsAllStructuralStretchHorizontal, true); if (!controller._IsAllStructuralStretchHorizontal) { EditorGUILayout.BeginVertical(GUI.skin.box); UpdateSlider(TextConstraintForce, controller, ref controller._StructuralStretchHorizontal, 0.0f, 1.0f); UpdateCurve(TextCurve, controller, ref controller._StructuralStretchHorizontalScaleCurve); EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); Titlebar(new string[] { "せん断", "Shear" }[Lang], new Color(96, 96, 96)); if (controller._IsComputeShear) { EditorGUILayout.BeginVertical(GUI.skin.box); TitlebarSub(TextShrink, new Color(192, 192, 192)); UpdateToggle(TextIndividual, controller, ref controller._IsAllShearShrink, true); if (!controller._IsAllShearShrink) { EditorGUILayout.BeginVertical(GUI.skin.box); UpdateSlider(TextConstraintForce, controller, ref controller._ShearShrink, 0.0f, 1.0f); UpdateCurve(TextCurve, controller, ref controller._ShearShrinkScaleCurve); EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); TitlebarSub(TextStretch, new Color(192, 192, 192)); UpdateToggle(TextIndividual, controller, ref controller._IsAllShearStretch, true); if (!controller._IsAllShearStretch) { EditorGUILayout.BeginVertical(GUI.skin.box); UpdateSlider(TextConstraintForce, controller, ref controller._ShearStretch, 0.0f, 1.0f); UpdateCurve(TextCurve, controller, ref controller._ShearStretchScaleCurve); EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); Titlebar(new string[] { "垂直曲げ", "Bending (Vertical)" }[Lang], new Color(96, 96, 96)); if (controller._IsComputeBendingVertical) { EditorGUILayout.BeginVertical(GUI.skin.box); TitlebarSub(TextShrink, new Color(255, 255, 255)); UpdateToggle(TextIndividual, controller, ref controller._IsAllBendingShrinkVertical, true); if (!controller._IsAllBendingShrinkVertical) { EditorGUILayout.BeginVertical(GUI.skin.box); UpdateSlider(TextConstraintForce, controller, ref controller._BendingShrinkVertical, 0.0f, 1.0f); UpdateCurve(TextCurve, controller, ref controller._BendingShrinkVerticalScaleCurve); EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); TitlebarSub(TextStretch, new Color(192, 192, 192)); UpdateToggle(TextIndividual, controller, ref controller._IsAllBendingStretchVertical, true); if (!controller._IsAllBendingStretchVertical) { EditorGUILayout.BeginVertical(GUI.skin.box); UpdateSlider(TextConstraintForce, controller, ref controller._BendingStretchVertical, 0.0f, 1.0f); UpdateCurve(TextCurve, controller, ref controller._BendingStretchVerticalScaleCurve); EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); Titlebar(new string[] { "水平曲げ", "Bending (Horizontal)" }[Lang], new Color(96, 96, 96)); if (controller._IsComputeBendingHorizontal) { EditorGUILayout.BeginVertical(GUI.skin.box); TitlebarSub(TextShrink, new Color(192, 192, 192)); UpdateToggle(TextIndividual, controller, ref controller._IsAllBendingShrinkHorizontal, true); if (!controller._IsAllBendingShrinkHorizontal) { EditorGUILayout.BeginVertical(GUI.skin.box); UpdateSlider(TextConstraintForce, controller, ref controller._BendingShrinkHorizontal, 0.0f, 1.0f); UpdateCurve(TextCurve, controller, ref controller._BendingShrinkHorizontalScaleCurve); EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); TitlebarSub(TextStretch, new Color(192, 192, 192)); UpdateToggle(TextIndividual, controller, ref controller._IsAllBendingStretchHorizontal, true); if (!controller._IsAllBendingStretchHorizontal) { EditorGUILayout.BeginVertical(GUI.skin.box); UpdateSlider(TextConstraintForce, controller, ref controller._BendingStretchHorizontal, 0.0f, 1.0f); UpdateCurve(TextCurve, controller, ref controller._BendingStretchHorizontalScaleCurve); EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); } controller.Opened_AngleLockSettings = Foldout(controller.Opened_AngleLockSettings, new string[] { "角度制限設定", "Angle lock settings" }[Lang], new Color(0.7f, 0.7f, 1.0f)); if (controller.Opened_AngleLockSettings) { controller._UseLimitAngles = EditorGUILayout.Toggle(new string[] { "角度制限", "Angle limit" }[Lang], controller._UseLimitAngles); if (controller._UseLimitAngles) { controller._LimitAngle = EditorGUILayout.IntSlider(new string[] { "制限角度", "Limit angle" }[Lang], controller._LimitAngle, 0, 180); controller._LimitPowerCurve = EditorGUILayout.CurveField(new string[] { "制限力", "Limit power curve" }[Lang], controller._LimitPowerCurve); controller._LimitFromRoot = EditorGUILayout.Toggle(new string[] { "ルートから角度制限", "Limit from root" }[Lang], controller._LimitFromRoot); } } controller.Opened_OptionSettings = Foldout(controller.Opened_OptionSettings, new string[] { "オプション", "Option" }[Lang], new Color(0.7f, 1.0f, 0.7f)); if (controller.Opened_OptionSettings) { if (GUILayout.Button(new string[] { "物理初期化", "Physics reset" }[Lang])) { controller.ResetPhysics(0.3f); } GUILayout.Space(8); EditorGUILayout.PropertyField(serializedObject.FindProperty("_IsPaused"), new GUIContent(new string[] { "一時停止", "Pause" }[Lang]), true); Titlebar(new string[] { "デバッグ表示", "Show debug information" }[Lang], new Color(0.7f, 1.0f, 1.0f)); UpdateToggle(new string[] { "垂直構造", "Structural (Vertical)" }[Lang], controller, ref controller._IsDebugDraw_StructuralVertical); UpdateToggle(new string[] { "水平構造", "Structural (Horizontal)" }[Lang], controller, ref controller._IsDebugDraw_StructuralHorizontal); UpdateToggle(new string[] { "せん断", "Shear" }[Lang], controller, ref controller._IsDebugDraw_Shear); UpdateToggle(new string[] { "垂直曲げ", "Bending (Vertical);" }[Lang], controller, ref controller._IsDebugDraw_BendingVertical); UpdateToggle(new string[] { "水平曲げ", "Bending (Horizontal);" }[Lang], controller, ref controller._IsDebugDraw_BendingHorizontal); UpdateToggle(new string[] { "ポリゴン面", "Surface Face" }[Lang], controller, ref controller._IsDebugDraw_SurfaceFace); if (controller._IsDebugDraw_SurfaceFace) { UpdateSlider(new string[] { "ポリゴン法線の長さ", "Surface normal length" }[Lang], controller, ref controller._Debug_SurfaceNormalLength, 0, 1); } UpdateToggle(new string[] { "実行中のコリジョン情報", "Runtime collider bounds" }[Lang], controller, ref controller._IsDebugDraw_RuntimeColliderBounds); } controller.Opened_PreSettings = Foldout(controller.Opened_PreSettings, new string[] { "拘束情報事前計算", "Constraint information pre-calculation" }[Lang], new Color(1.0f, 0.7f, 0.7f)); if (controller.Opened_PreSettings) { EditorGUILayout.BeginVertical(GUI.skin.box); Titlebar(new string[] { "拘束条件", "Constraint rules" }[Lang], new Color(96, 96, 96)); EditorGUILayout.BeginVertical(GUI.skin.box); EditorGUILayout.BeginHorizontal(); UpdateToggle(new string[] { "垂直構造", "Structural (Vertical)" }[Lang], controller, ref controller._IsComputeStructuralVertical); GUILayout.Space(5); if (controller._IsComputeStructuralVertical) { UpdateToggle(new string[] { "コリジョン", "Collision" }[Lang], controller, ref controller._IsCollideStructuralVertical); } EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); EditorGUILayout.BeginHorizontal(); UpdateToggle(new string[] { "水平構造", "Structural (Horizontal)" }[Lang], controller, ref controller._IsComputeStructuralHorizontal); if (controller._IsComputeStructuralHorizontal) { UpdateToggle(new string[] { "コリジョン", "Collision" }[Lang], controller, ref controller._IsCollideStructuralHorizontal); } EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); EditorGUILayout.BeginHorizontal(); UpdateToggle(new string[] { "せん断", "Shear" }[Lang], controller, ref controller._IsComputeShear); if (controller._IsComputeShear) { UpdateToggle(new string[] { "コリジョン", "Collision" }[Lang], controller, ref controller._IsCollideShear); } EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); EditorGUILayout.BeginHorizontal(); UpdateToggle(new string[] { "垂直曲げ", "Bending (Vertical)" }[Lang], controller, ref controller._IsComputeBendingVertical); if (controller._IsComputeBendingVertical) { UpdateToggle(new string[] { "コリジョン", "Collision" }[Lang], controller, ref controller._IsCollideBendingVertical); } EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUI.skin.box); EditorGUILayout.BeginHorizontal(); UpdateToggle(new string[] { "水平曲げ", "Bending (Horizontal)" }[Lang], controller, ref controller._IsComputeBendingHorizontal); if (controller._IsComputeBendingHorizontal) { UpdateToggle(new string[] { "コリジョン", "Collision" }[Lang], controller, ref controller._IsCollideBendingHorizontal); } EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); EditorGUILayout.EndVertical(); Titlebar(new string[] { "拘束情報を計算", "Calculate constraint information" }[Lang], new Color(96, 96, 96)); if (GUILayout.Button(new string[] { "拘束情報を事前計算", "From Root points" }[Lang])) { controller.UpdateJointConnection(); EditorUtility.SetDirty(controller); } if (GUILayout.Button(new string[] { "拘束情報を事前計算(近ポイント自動検索XYZ)", "Near point automatic search XYZ" }[Lang])) { SortConstraintsHorizontalRoot(controller, UpdateJointConnectionType.SortNearPointXYZ); controller.UpdateJointConnection(); EditorUtility.SetDirty(controller); } if (GUILayout.Button(new string[] { "拘束情報を事前計算(近ポイント自動検索XZ)", "Near point automatic search XZ" }[Lang])) { SortConstraintsHorizontalRoot(controller, UpdateJointConnectionType.SortNearPointXZ); controller.UpdateJointConnection(); EditorUtility.SetDirty(controller); } if (GUILayout.Button(new string[] { "拘束情報を事前計算(近ポイント自動検索XYZ:先端終端固定)", "Near point automatic search XYZ (Fixed tip)" }[Lang])) { SortConstraintsHorizontalRoot(controller, UpdateJointConnectionType.SortNearPointXYZ_FixedBeginEnd); controller.UpdateJointConnection(); EditorUtility.SetDirty(controller); } if (GUILayout.Button(new string[] { "拘束情報を事前計算(近ポイント自動検索XZ:先端終端固定)", "Near point automatic search XZ (Fixed tip)" }[Lang])) { SortConstraintsHorizontalRoot(controller, UpdateJointConnectionType.SortNearPointXZ_FixedBeginEnd); controller.UpdateJointConnection(); EditorUtility.SetDirty(controller); } if (GUILayout.Button(new string[] { "拘束間の長さを再計算", "Constraint length recalculation" }[Lang])) { controller.UpdateJointDistance(); EditorUtility.SetDirty(controller); } { var bgColor = GUI.backgroundColor; var contentColor = GUI.contentColor; GUI.contentColor = Color.yellow; GUI.backgroundColor = new Color(1.0f, 0.5f, 0.5f); if (GUILayout.Button(new string[] { "拘束の設定を破棄", "Discard constraint settings" }[Lang])) { controller.DeleteJointConnection(); EditorUtility.SetDirty(controller); } GUI.backgroundColor = bgColor; GUI.contentColor = contentColor; } Titlebar(new string[] { "設定保存", "Save settings" }[Lang], new Color(1.0f, 0.7f, 0.7f)); if (GUILayout.Button(new string[] { "設定を保存する", "Save settings" }[Lang])) { SPCRJointSettingLocalSave.Save(controller); } if (GUILayout.Button(new string[] { "設定をロードする", "Load settings" }[Lang])) { SPCRJointSettingLocalSave.Load(controller); } GUILayout.Space(5); Titlebar(new string[] { "細分化", "Subdivision" }[Lang], new Color(0.7f, 1.0f, 0.7f)); if (PrefabUtility.IsPartOfAnyPrefab(controller.gameObject)) { EditorGUILayout.HelpBox(new string[] { "UnpackされていないPrefabは細分化できません", "Unpacked Prefabs cannot be subdivided" }[Lang], MessageType.Warning); } else { if (GUILayout.Button(new string[] { "垂直の拘束を挿入", "Insert vertical constraint" }[Lang])) { SubdivideVerticalChain(controller, 1); EditorUtility.SetDirty(controller); } if (GUILayout.Button(new string[] { "水平の拘束を挿入", "Insert horizontal constraint" }[Lang])) { SubdivideHorizontalChain(controller, 1); EditorUtility.SetDirty(controller); } if (controller._SubDivInsertedPoints.Count > 0) { if (GUILayout.Button(new string[] { "細分化を元に戻す", "Undo subdivision" }[Lang])) { RemoveInsertedPoints(controller); EditorUtility.SetDirty(controller); } { var bgColor = GUI.backgroundColor; var contentColor = GUI.contentColor; GUI.contentColor = Color.yellow; GUI.backgroundColor = new Color(0.6f, 0.0f, 0.0f); if (GUILayout.Button(new string[] { "細分化の確定", "Confirmation of subdivision" }[Lang])) { PurgeSubdivideOriginalInfo(controller); EditorUtility.SetDirty(controller); } GUI.backgroundColor = bgColor; GUI.contentColor = contentColor; } { var message = string.Format( new string[] { "分割後には自動設定を行ってください\nオリジナルの点:{0}個\n追加された点:{1}個", "Please set automatically after splitting\nOriginal points: {0}\nAdded points: {1}" }[Lang], controller._SubDivOriginalPoints.Count, controller._SubDivInsertedPoints.Count); EditorGUILayout.HelpBox(message, MessageType.Warning); } } } } if (GUI.changed) { EditorUtility.SetDirty(controller); } serializedObject.ApplyModifiedProperties(); } void UpdateToggle(string Label, SPCRJointDynamicsController Source, ref bool Value, bool Reverse = false) { if (Reverse) Value = !EditorGUILayout.Toggle(Label, !Value); else Value = EditorGUILayout.Toggle(Label, Value); } void UpdateIntSlider(string Label, SPCRJointDynamicsController Source, ref int Value, int Min, int Max) { Value = EditorGUILayout.IntSlider(Label, Value, Min, Max); } void UpdateSlider(string Label, SPCRJointDynamicsController Source, ref float Value, float Min, float Max) { Value = EditorGUILayout.Slider(Label, Value, Min, Max); } void UpdateFloat(string Label, SPCRJointDynamicsController Source, ref float Value) { Value = EditorGUILayout.FloatField(Label, Value); } void UpdateVector3(string Label, SPCRJointDynamicsController Source, ref Vector3 Value) { Value = EditorGUILayout.Vector3Field(Label, Value); } void UpdateCurve(string Label, SPCRJointDynamicsController Source, ref AnimationCurve Value) { Value = EditorGUILayout.CurveField(Label, Value); } void Titlebar(string text, Color color) { var backgroundColor = GUI.backgroundColor; GUI.backgroundColor = Color.gray;// color; EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); GUILayout.Label(text); EditorGUILayout.EndHorizontal(); GUI.backgroundColor = backgroundColor; GUILayout.Space(3); } void TitlebarSub(string text, Color color) { var backgroundColor = GUI.backgroundColor; GUI.backgroundColor = color; EditorGUILayout.BeginHorizontal(EditorStyles.helpBox); GUILayout.Label(text); EditorGUILayout.EndHorizontal(); GUI.backgroundColor = backgroundColor; GUILayout.Space(3); } void SearchRootPoints(SPCRJointDynamicsController controller) { if (controller._RootTransform != null) { var PointList = new List<SPCRJointDynamicsPoint>(); for (int i = 0; i < controller._RootTransform.transform.childCount; ++i) { var child = controller._RootTransform.transform.GetChild(i); var point = child.GetComponent<SPCRJointDynamicsPoint>(); if (point != null) { PointList.Add(point); } } controller._RootPointTbl = PointList.ToArray(); } } SPCRJointDynamicsPoint GetNearestPoint(Vector3 Base, ref List<SPCRJointDynamicsPoint> Source, bool IsIgnoreY) { float NearestDistance = float.MaxValue; int NearestIndex = -1; for (int i = 0; i < Source.Count; ++i) { var Direction = Source[i].transform.position - Base; if (IsIgnoreY) Direction.y = 0.0f; var Distance = Direction.sqrMagnitude; if (NearestDistance > Distance) { NearestDistance = Distance; NearestIndex = i; } } var Point = Source[NearestIndex]; Source.RemoveAt(NearestIndex); return Point; } void SortConstraintsHorizontalRoot(SPCRJointDynamicsController controller, UpdateJointConnectionType Type) { switch (Type) { case UpdateJointConnectionType.Default: { } break; case UpdateJointConnectionType.SortNearPointXYZ: { var SourcePoints = new List<SPCRJointDynamicsPoint>(); var EdgeA = controller._RootPointTbl[0]; for (int i = 1; i < controller._RootPointTbl.Length; ++i) { SourcePoints.Add(controller._RootPointTbl[i]); } var SortedPoints = new List<SPCRJointDynamicsPoint>(); SortedPoints.Add(EdgeA); while (SourcePoints.Count > 0) { SortedPoints.Add(GetNearestPoint( SortedPoints[SortedPoints.Count - 1].transform.position, ref SourcePoints, false)); } controller._RootPointTbl = SortedPoints.ToArray(); } break; case UpdateJointConnectionType.SortNearPointXZ: { var SourcePoints = new List<SPCRJointDynamicsPoint>(); var EdgeA = controller._RootPointTbl[0]; for (int i = 1; i < controller._RootPointTbl.Length; ++i) { SourcePoints.Add(controller._RootPointTbl[i]); } var SortedPoints = new List<SPCRJointDynamicsPoint>(); SortedPoints.Add(EdgeA); while (SourcePoints.Count > 0) { SortedPoints.Add(GetNearestPoint( SortedPoints[SortedPoints.Count - 1].transform.position, ref SourcePoints, true)); } controller._RootPointTbl = SortedPoints.ToArray(); } break; case UpdateJointConnectionType.SortNearPointXYZ_FixedBeginEnd: { var SourcePoints = new List<SPCRJointDynamicsPoint>(); var EdgeA = controller._RootPointTbl[0]; var EdgeB = controller._RootPointTbl[controller._RootPointTbl.Length - 1]; for (int i = 1; i < controller._RootPointTbl.Length - 1; ++i) { SourcePoints.Add(controller._RootPointTbl[i]); } var SortedPoints = new List<SPCRJointDynamicsPoint>(); SortedPoints.Add(EdgeA); while (SourcePoints.Count > 0) { SortedPoints.Add(GetNearestPoint( SortedPoints[SortedPoints.Count - 1].transform.position, ref SourcePoints, false)); } SortedPoints.Add(EdgeB); controller._RootPointTbl = SortedPoints.ToArray(); } break; case UpdateJointConnectionType.SortNearPointXZ_FixedBeginEnd: { var SourcePoints = new List<SPCRJointDynamicsPoint>(); var EdgeA = controller._RootPointTbl[0]; var EdgeB = controller._RootPointTbl[controller._RootPointTbl.Length - 1]; for (int i = 1; i < controller._RootPointTbl.Length - 1; ++i) { SourcePoints.Add(controller._RootPointTbl[i]); } var SortedPoints = new List<SPCRJointDynamicsPoint>(); SortedPoints.Add(EdgeA); while (SourcePoints.Count > 0) { SortedPoints.Add(GetNearestPoint( SortedPoints[SortedPoints.Count - 1].transform.position, ref SourcePoints, true)); } SortedPoints.Add(EdgeB); controller._RootPointTbl = SortedPoints.ToArray(); } break; } } void SubdivideVerticalChain(SPCRJointDynamicsController controller, int NumInsert) { var rnd = new System.Random(); var RootList = new List<SPCRJointDynamicsPoint>(controller._RootPointTbl); var OriginalPoints = controller._SubDivOriginalPoints; var InsertedPoints = controller._SubDivInsertedPoints; var IsFirstSubdivide = (OriginalPoints.Count == 0); foreach (var rootPoint in RootList) { if (IsFirstSubdivide) OriginalPoints.Add(rootPoint); var parentPoint = rootPoint; while (parentPoint.transform.childCount > 0) { var parentTransform = parentPoint.transform; var points = parentTransform.GetComponentsInChildren<SPCRJointDynamicsPoint>(); if (points.Length < 2) { break; } var childPoint = points[1]; if (parentPoint == childPoint) { Debug.LogWarning("Infinite Loop!:" + parentPoint.name); break; } if (IsFirstSubdivide) OriginalPoints.Add(childPoint); var childTransform = childPoint.transform; SPCRJointDynamicsPoint newPoint = null; for (int i = 1; i <= NumInsert; i++) { float weight = i / (NumInsert + 1.0f); newPoint = CreateInterpolatedPoint(parentPoint, childPoint, weight, "VSubdiv_" + rnd.Next()); InsertedPoints.Add(newPoint); newPoint.transform.SetParent(parentTransform); parentTransform = newPoint.transform; } childTransform.SetParent(newPoint.transform); parentPoint = childPoint; } } } void SubdivideHorizontalChain(SPCRJointDynamicsController controller, int NumInsert) { var rnd = new System.Random(); var RootList = new List<SPCRJointDynamicsPoint>(controller._RootPointTbl); var OriginalPoints = controller._SubDivOriginalPoints; var InsertedPoints = controller._SubDivInsertedPoints; var IsFirstSubdivide = (OriginalPoints.Count == 0); int Count = RootList.Count; int Start = controller._IsLoopRootPoints ? Count : (Count - 1); for (int iroot = Start; iroot > 0; iroot--) { var root0 = RootList[iroot % Count]; var root1 = RootList[iroot - 1]; for (int iin = 1; iin <= NumInsert; iin++) { var point0 = root0; var point1 = root1; var parentTransform = root0.transform.parent; float weight = iin / (NumInsert + 1.0f); SPCRJointDynamicsPoint newRoot = null; while (point0 != null && point1 != null) { if (IsFirstSubdivide && iin == 1) { if (!controller._IsLoopRootPoints && iroot == Start) { OriginalPoints.Add(point0); } OriginalPoints.Add(point1); } var newPoint = CreateInterpolatedPoint(point0, point1, weight, "HSubdiv_" + rnd.Next()); InsertedPoints.Add(newPoint); var newTransform = newPoint.transform; newTransform.SetParent(parentTransform); parentTransform = newTransform; SPCRJointDynamicsPoint[] points; points = point0.transform.GetComponentsInChildren<SPCRJointDynamicsPoint>(); point0 = (points.Length > 1) ? points[1] : null; points = point1.transform.GetComponentsInChildren<SPCRJointDynamicsPoint>(); point1 = (points.Length > 1) ? points[1] : null; if (newRoot == null) { newRoot = newPoint; RootList.Insert(iroot, newRoot); } } } } controller._RootPointTbl = RootList.ToArray(); } SPCRJointDynamicsPoint CreateInterpolatedPoint(SPCRJointDynamicsPoint point0, SPCRJointDynamicsPoint point1, float weight0, string newName = "SubDivPoint") { var Transform0 = point0.transform; var Transform1 = point1.transform; var pos = Vector3.Lerp(Transform0.position, Transform1.position, weight0); var rot = Quaternion.Slerp(Transform0.rotation, Transform1.rotation, weight0); var obj = new GameObject(newName); var newPoint = obj.AddComponent<SPCRJointDynamicsPoint>(); var objTransform = obj.transform; objTransform.position = pos; objTransform.rotation = rot; return newPoint; } void RemoveInsertedPoints(SPCRJointDynamicsController controller) { var OriginalPoints = controller._SubDivOriginalPoints; var InsertedPoints = controller._SubDivInsertedPoints; if (OriginalPoints.Count == 0) { return; } controller.DeleteJointConnection(); var originalPoints = new Dictionary<int, SPCRJointDynamicsPoint>(OriginalPoints.Count); foreach (var op in OriginalPoints) { int key = op.GetInstanceID(); if (!originalPoints.ContainsKey(key)) { originalPoints.Add(key, op); } } var rootList = new List<SPCRJointDynamicsPoint>(); foreach (var root in controller._RootPointTbl) { if (!originalPoints.ContainsKey(root.GetInstanceID())) { continue; } rootList.Add(root); var parentPoint = root; var chainPoint = root; while (chainPoint != null) { var children = chainPoint.GetComponentsInChildren<SPCRJointDynamicsPoint>(); if (children.Length < 2) { break; } var childPoint = children[1]; if (originalPoints.ContainsKey(childPoint.GetInstanceID())) { childPoint.transform.SetParent(parentPoint.transform); parentPoint = childPoint; } chainPoint = childPoint; } } foreach (var point in InsertedPoints) { point._RefChildPoint = null; point.transform.SetParent(null); } foreach (var point in InsertedPoints) { DestroyImmediate(point.gameObject); } controller._RootPointTbl = rootList.ToArray(); controller._SubDivOriginalPoints.Clear(); controller._SubDivInsertedPoints.Clear(); } void PurgeSubdivideOriginalInfo(SPCRJointDynamicsController controller) { controller._SubDivOriginalPoints.Clear(); controller._SubDivInsertedPoints.Clear(); } void CreationSubdivisionJoint(SPCRJointDynamicsController Controller, int HDivCount, int VDivCount) { var VCurve = new List<CurveData>(); var HCurve = new List<CurveData>(); var RootTbl = Controller._RootPointTbl; #if UNITY_2018_3_OR_NEWER PrefabUtility.UnpackPrefabInstance(Controller.gameObject, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction); #else//UNITY_2018_3_OR_NEWER PrefabUtility.DisconnectPrefabInstance(Controller.gameObject); #endif//UNITY_2018_3_OR_NEWER for (int i = 0; i < RootTbl.Length; ++i) { float Length = 0.0f; var Curve = new CurveData(); var Point = RootTbl[i]; while (Point != null) { Curve.Keys.Add(new CurveKey() { Length = Length, Value = Point.transform.position, }); var NextPoint = Controller.GetChildJointDynamicsPoint(Point); if (NextPoint != null) { Length += (NextPoint.transform.position - Point.transform.position).magnitude; } Point = NextPoint; } Curve.CreateSpileData(Length, false); VCurve.Add(Curve); } for (int v = 0; v <= VDivCount; ++v) { float Rate = (float)v / (float)VDivCount; var Curve = new CurveData(); var OldPoint = VCurve[0].ComputeLinear(Rate); float Length = 0.0f; for (int i = 0; i < VCurve.Count; ++i) { var NewPoint = VCurve[i].ComputeLinear(Rate); Length += (NewPoint - OldPoint).magnitude; Curve.Keys.Add(new CurveKey() { Length = Length, Value = NewPoint, }); OldPoint = NewPoint; } Curve.CreateSpileData(Length, true); HCurve.Add(Curve); } var RootPointList = new List<SPCRJointDynamicsPoint>(); for (int h = 0; h < HDivCount; ++h) { float Rate = (float)h / (float)HDivCount; var parent = Controller._RootTransform; for (int i = 0; i < HCurve.Count; ++i) { var Position = HCurve[i].ComputeSpline(Rate); var go = new GameObject(h.ToString("D3") + "_" + i.ToString("D3")); var pt = go.AddComponent<SPCRJointDynamicsPoint>(); go.transform.SetParent(parent); go.transform.position = Position; if (i == 0) { RootPointList.Add(pt); } parent = go.transform; } } for (int i = 0; i < RootTbl.Length; ++i) { SetTransformScaleZero(RootTbl[i].transform); } Controller._RootPointTbl = RootPointList.ToArray(); Controller.UpdateJointConnection(); GenerateMeshFromBoneConstraints(Controller); } void SetTransformScaleZero(Transform t) { t.localScale = Vector3.zero; for (int i = 0; i < t.childCount; ++i) { SetTransformScaleZero(t.GetChild(i)); } } void GenerateMeshFromBoneConstraints(SPCRJointDynamicsController Controller) { var vertices = new List<Vector3>(); var boneWeights = new List<BoneWeight>(); var bindposes = new List<Matrix4x4>(); var AllBones = new List<Transform>(); var HorizontalBones = new List<List<Transform>>(); for (int i = 0; i <= Controller._RootPointTbl.Length; ++i) { var verticalBones = new List<Transform>(); var child = Controller._RootPointTbl[i % Controller._RootPointTbl.Length]; while (child != null) { vertices.Add(child.transform.position); boneWeights.Add(new BoneWeight() { boneIndex0 = AllBones.Count, weight0 = 1.0f, }); bindposes.Add(child.transform.worldToLocalMatrix); AllBones.Add(child.transform); verticalBones.Add(child.transform); child = Controller.GetChildJointDynamicsPoint(child); } HorizontalBones.Add(verticalBones); } var uvs = new List<Vector2>(); for (int h = 0; h < HorizontalBones.Count; ++h) { for (int v = 0; v < HorizontalBones[h].Count; ++v) { uvs.Add(new Vector2( (float)h / (float)(HorizontalBones.Count - 1), (float)v / (float)(HorizontalBones[h].Count - 1))); } } int index = 0; var triangles = new List<int>(); var HorizontalCount = HorizontalBones.Count; for (int h = 0; h < HorizontalCount - 1; ++h) { var Vertical0Count = HorizontalBones[h].Count; var Vertical1Count = HorizontalBones[h + 1].Count; if (Vertical0Count == Vertical1Count) { for (int v = 0; v < Vertical0Count - 1; ++v) { var top0 = index; var top1 = index + Vertical0Count; var x0y0 = top0 + v; var x1y0 = top0 + v + 1; var x0y1 = top1 + v; var x1y1 = top1 + v + 1; triangles.Add(x0y0); triangles.Add(x1y0); triangles.Add(x1y1); triangles.Add(x1y1); triangles.Add(x0y1); triangles.Add(x0y0); } } index += Vertical0Count; } var mesh = new Mesh(); mesh.indexFormat = vertices.Count > 65535 ? IndexFormat.UInt32 : IndexFormat.UInt16; mesh.vertices = vertices.ToArray(); mesh.uv = uvs.ToArray(); mesh.boneWeights = boneWeights.ToArray(); mesh.bindposes = bindposes.ToArray(); mesh.triangles = triangles.ToArray(); RecalculateNormals(mesh); var renderers = Controller.gameObject.GetComponentsInChildren<SkinnedMeshRenderer>(); if (renderers.Length != 0) { var Path = AssetDatabase.GetAssetPath(renderers[renderers.Length - 1].sharedMesh); var DirName = System.IO.Path.GetDirectoryName(Path); AssetDatabase.CreateAsset(mesh, DirName + "/" + Controller.gameObject.name + "_" + Controller.Name + ".asset"); AssetDatabase.Refresh(); } var skinMesh = Controller.gameObject.GetComponent<SkinnedMeshRenderer>(); if (skinMesh == null) skinMesh = Controller.gameObject.AddComponent<SkinnedMeshRenderer>(); skinMesh.bones = AllBones.ToArray(); skinMesh.sharedMesh = mesh; skinMesh.rootBone = Controller._RootTransform; var meshFilter = Controller.gameObject.GetComponent<MeshFilter>(); if (meshFilter == null) meshFilter = Controller.gameObject.AddComponent<MeshFilter>(); meshFilter.mesh = mesh; } void RecalculateNormals(Mesh mesh) { var Normals = new Dictionary<Vector3, Vector3>(); var triangles = mesh.triangles; var vertices = mesh.vertices; var normals = new Vector3[vertices.Length]; for (var i = 0; i < triangles.Length; i += 3) { var i1 = triangles[i]; var i2 = triangles[i + 1]; var i3 = triangles[i + 2]; var p1 = vertices[i2] - vertices[i1]; var p2 = vertices[i3] - vertices[i1]; var normal = Vector3.Cross(p1, p2).normalized; Normals[vertices[i1]] = normal; Normals[vertices[i2]] = normal; Normals[vertices[i3]] = normal; } for (int i = 0; i < vertices.Length; ++i) { normals[i] = Normals[vertices[i]].normalized; } mesh.normals = normals; } struct CurveKey { public float Length; public Vector3 Value; } class CurveData { public List<CurveKey> Keys = new List<CurveKey>(); public float TotalLength = 0.0f; public void CreateSpileData(float Length, bool IsLoop) { TotalLength = Length; if (!IsLoop) return; var Key_p1 = new CurveKey() { Length = -(Keys[Keys.Count - 1].Value - Keys[0].Value).magnitude, Value = Keys[Keys.Count - 1].Value, }; var Key_p2 = new CurveKey() { Length = Key_p1.Length - (Keys[Keys.Count - 2].Value - Keys[Keys.Count - 1].Value).magnitude, Value = Keys[Keys.Count - 2].Value, }; var Key_n1 = new CurveKey() { Length = TotalLength + (Keys[Keys.Count - 1].Value - Keys[0].Value).magnitude, Value = Keys[0].Value, }; TotalLength = Key_n1.Length; var Key_n2 = new CurveKey() { Length = TotalLength + (Keys[0].Value - Keys[1].Value).magnitude, Value = Keys[1].Value, }; Keys.Insert(0, Key_p1); Keys.Insert(0, Key_p2); Keys.Add(Key_n1); Keys.Add(Key_n2); } void Hermite(float t, out float H1, out float H2, out float H3, out float H4) { float t2 = t * t; float t3 = t * t2; H1 = +2.0f * t3 - 3.0f * t2 + 1.0f; H2 = -2.0f * t3 + 3.0f * t2; H3 = t3 - 2.0f * t2 + t; H4 = t3 - t2; } Vector3 GetOut(int No) { var Key1 = Keys[No]; var Key2 = Keys[No + 1]; var a = 1.0f; var b = 1.0f; var d = Key2.Value - Key1.Value; var Key0 = Keys[No - 1]; var t = (Key2.Length - Key1.Length) / (Key2.Length - Key0.Length); return t * (b * (Key1.Value - Key0.Value) + (a * d)); } Vector3 GetIn(int No) { var Key0 = Keys[No]; var Key1 = Keys[No + 1]; var a = 1.0f; var b = 1.0f; var d = Key1.Value - Key0.Value; var Key2 = Keys[No + 2]; var t = (Key1.Length - Key0.Length) / (Key2.Length - Key0.Length); return t * (a * (Key2.Value - Key1.Value) + (b * d)); } public Vector3 ComputeLinear(float Length) { Length *= TotalLength; int No = 0; while (!((Keys[No].Length <= Length) && (Length <= Keys[No + 1].Length))) No++; var Key1 = Keys[No]; var Key2 = Keys[(No + 1) % Keys.Count]; var ValueRate = (Length - Key1.Length) / (Key2.Length - Key1.Length); return Vector3.Lerp(Key1.Value, Key2.Value, ValueRate); } public Vector3 ComputeSpline(float Length) { Length *= TotalLength; int No = 0; while (!((Keys[No].Length <= Length) && (Length <= Keys[No + 1].Length))) No++; var Key1 = Keys[No]; var Key2 = Keys[(No + 1) % Keys.Count]; var ValueRate = (Length - Key1.Length) / (Key2.Length - Key1.Length); var Out = GetOut(No); var In = GetIn(No); float H1, H2, H3, H4; Hermite(ValueRate, out H1, out H2, out H3, out H4); return (H1 * Key1.Value) + (H2 * Key2.Value) + (H3 * Out) + (H4 * In); } } } [InitializeOnLoad] public class SPCRJointDynamicsSettingsWindow : EditorWindow { static SPCRJointDynamicsSettingsWindow _Window; static SPCRJointDynamicsSettingsWindow() { EditorApplication.update += Update; } static void Update() { if (!EditorApplication.isPlayingOrWillChangePlaymode) { if (!PlayerSettings.allowUnsafeCode) { _Window = GetWindow<SPCRJointDynamicsSettingsWindow>(true); _Window.minSize = new Vector2(450, 200); } } } void OnGUI() { EditorGUILayout.HelpBox( "Recommended project settings for SPCRJointDynamics:\n" + "PlayerSettings.allowUnsafeCode = true\n", MessageType.Info); if (GUILayout.Button("fix Settings")) { if (!PlayerSettings.allowUnsafeCode) { PlayerSettings.allowUnsafeCode = true; } Close(); } } } }
using Caliburn.Micro; using Caliburn.Micro.Xamarin.Forms; using RRExpress.AppCommon.Attributes; using RRExpress.Seller.Entity; using System.Collections.Generic; using System.Windows.Input; using Xamarin.Forms; namespace RRExpress.Store.ViewModels { [Regist(InstanceMode.Singleton)] public class MyViewModel : StoreBaseVM { public override char Icon { get { return (char)0xf007; } } public override string Title { get { return "我的"; } } public ICommand ShowOrdersCmd { get; } //public Dictionary<OrderStatus, int?> OrderSummary { // get; //} = new Dictionary<OrderStatus, int?>() { // { OrderStatus.NonPayment, 1 }, // { OrderStatus.WaitReceive, 2 }, // { OrderStatus.WaitComment, 10 }, // { OrderStatus.Tuihuan, null } //}; public IEnumerable<Tmp> OrderSummary { get; } public MyViewModel() { this.OrderSummary = new List<Tmp>() { new Tmp() { Status = OrderStatus.All, Count = null, Icon = (char)0xf03a }, new Tmp() { Status = OrderStatus.NonPayment, Count = null, Icon = (char)0xf09d }, new Tmp() { Status = OrderStatus.WaitReceive, Count = null, Icon = (char)0xf0d1 }, new Tmp() { Status = OrderStatus.WaitComment, Count = null, Icon = (char)0xf27b }, new Tmp() { Status = OrderStatus.Tuihuan, Count = null, Icon = (char)0xf119 }, }; this.ShowOrdersCmd = new Command((o) => { var tmp = (Tmp)o; IoC.Get<INavigationService>() .For<OrderListViewModel>() .WithParam(vm => vm.Status, tmp.Status) .Navigate(); }); } public class Tmp { public OrderStatus Status { get; set; } public char Icon { get; set; } public int? Count { get; set; } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace <%= domainTestsProjectName %>.Services { [TestClass] public class ExempleServiceTests { [TestMethod] public void ExempleTest() { Assert.IsTrue(0 == 0); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class QuestionObject { public Effect right; public Effect left; public string question; public string rightChoice; public string leftChoice; public string rightResult; public string leftResult; public QuestionObject(Effect right, Effect left, string question, string rightChoice, string leftChoice, string rightResult, string leftResult) { this.right = right; this.left = left; this.question = question; this.rightChoice = rightChoice; this.leftChoice = leftChoice; this.rightResult = rightResult; this.leftResult = leftResult; } }
using UnityEngine; public class HideController : MonoBehaviour { private bool didHideDefaultController; void LateUpdate () { HideDefaultControllerIfNeeded(); } void HideDefaultControllerIfNeeded() { if (!didHideDefaultController) { Renderer[] renderers = transform.GetComponentsInChildren<Renderer>(); for (int i = 0; i < renderers.Length; i++) { if (renderers[i].material.name == "Standard (Instance)") { renderers[i].enabled = false; didHideDefaultController = true; } } } } }
using UnityEngine; using System.Collections; public class BeatsEngine : MonoBehaviour { public static BeatsEngine Instance; public float bpm = 60f; public bool bpmIncreases = true; private int beats; public GameObject sun; private SunScript sunScript; private TerrainGeneration terrainGeneration; private ColorDefinitions colorDefinitions; public int beatsPerSubthrob = 1; public int sunLeadBeats = 1; public int beatsPerGate = 4; private bool generateGates = false; private AudioSource audioSource; void Start () { StartCoroutine(generateBeats()); sunScript.randomizeColor(); } public void registerTintable(ColorObject tintable) { sunScript.registerTintable(tintable); } public void unregisterTintable(ColorObject tintable) { sunScript.unregisterTintable(tintable); } void OnGUI(){ GUI.Label(new Rect(0, 0, Screen.width,Screen.height), bpm.ToString()); } public void gateDestroyed() { if(bpmIncreases) bpm++; MakeSound(Playlist.Instance.gatePassed); } IEnumerator generateBeats() { for( float timer = 0; timer <= 60f / bpm; timer += Time.deltaTime) yield return 0; beats++; if(generateGates && ((beats + sunLeadBeats) % beatsPerGate == 0)) sunScript.randomizeColor(); if(generateGates && (beats % beatsPerGate == 0)) { terrainGeneration.generateGate(); } if(beats % beatsPerSubthrob == 0) { MakeSound(Playlist.Instance.sunThrob); sunScript.throb(); } foreach(BeatAspect aspect in Playlist.Instance.beatAspects) { if((beats >= aspect.beatStart) && (beats % aspect.beatsPer == 0)) MakeSound(aspect.clip); } StartCoroutine(generateBeats()); } public void engage() { generateGates = true; } // Update is called once per frame void Update () { } private void MakeSound(AudioClip originalClip) { audioSource.PlayOneShot(originalClip); } void Awake() { // Register the singleton if (Instance != null) { Debug.LogError("Multiple instances of BeatsEngine!"); } Instance = this; audioSource = GetComponent<AudioSource>(); sunScript = sun.GetComponent<SunScript>(); terrainGeneration = GetComponent<TerrainGeneration>(); } }
namespace P08MilitaryElite.Interfaces.Factories { public interface IPrivateFactory : IAbstractFactory<IPrivate> { } }
using System; using System.Collections.Generic; using System.Text; namespace SelectionCommittee.BLL.DataTransferObject { public class StatementDTO { public string EnrolleeId { get; set; } public int SpecialtyId { get; set; } public int Priority { get; set; } } }
using System; namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual { /// <summary> /// Representa el objeto request de Bien /// </summary> /// <remarks> /// Creación : GMD 20150515 <br /> /// Modificación : <br /> /// </remarks> public class BienRequest { /// <summary> /// Codigo del Bien /// </summary> public Guid? CodigoBien { get; set; } /// <summary> /// Codigo del Tipo de Bien /// </summary> public string CodigoTipoBien { get; set; } /// <summary> /// Código de Identificación /// </summary> public string CodigoIdentificacion { get; set; } /// <summary> /// Numero de Serie /// </summary> public string NumeroSerie { get; set; } /// <summary> /// Descripcion /// </summary> public string Descripcion { get; set; } /// <summary> /// Marca /// </summary> public string Marca { get; set; } /// <summary> /// Modelo /// </summary> public string Modelo { get; set; } /// <summary> /// Fecha de Adquisicion /// </summary> public DateTime? FechaAdquisicion { get; set; } /// <summary> /// Fecha de Adquisición en cadena de texto /// </summary> public string FechaAdquisicionString { get; set; } /// <summary> /// Filtro fecha de inicio /// </summary> public string FechaInicio { get; set; } /// <summary> /// Filtro fecha fin /// </summary> public string FechaFin { get; set; } /// <summary> /// Tiempo de Vida /// </summary> public decimal TiempoVida { get; set; } /// <summary> /// Tiempo de Vida en cadena de texto /// </summary> public string TiempoVidaString { get; set; } /// <summary> /// Valor Residual /// </summary> public decimal ValorResidual { get; set; } /// <summary> /// Valor Residual en cadena de texto /// </summary> public string ValorResidualString { get; set; } /// <summary> /// Codigo de Tipo de Tarifa /// </summary> public string CodigoTipoTarifa { get; set; } /// <summary> /// Codigo Periodo de Alquiler /// </summary> public string CodigoPeriodoAlquiler { get; set; } /// <summary> /// Valor de Alquiler /// </summary> public decimal ValorAlquiler { get; set; } /// <summary> /// Valor de Alquiler en cadena de texto /// </summary> public string ValorAlquilerString { get; set; } /// <summary> /// Codigo de Moneda /// </summary> public string CodigoMoneda { get; set; } /// <summary> /// Mes de Inicio de Alquiler /// </summary> public Byte? MesInicioAlquiler { get; set; } /// <summary> /// Año de Inicio de Alquiler /// </summary> public Int16? AnioInicioAlquiler { get; set; } } }
using System; namespace ResilienceClasses { public class clsLoanTable { public clsLoanTable() { } } }
namespace Zinnia.Tracking.Collision.Active { using UnityEngine; using UnityEngine.Events; using System; using System.Collections.Generic; using Malimbe.MemberClearanceMethod; using Malimbe.XmlDocumentationAttribute; using Malimbe.PropertySerializationAttribute; using Malimbe.BehaviourStateRequirementMethod; using Zinnia.Rule; using Zinnia.Extension; /// <summary> /// Holds a collection of the current collisions raised by a <see cref="CollisionNotifier"/>. /// </summary> public class ActiveCollisionsContainer : MonoBehaviour { /// <summary> /// Holds data about a <see cref="CollisionTracker"/> event. /// </summary> [Serializable] public class EventData { /// <summary> /// The current active collisions. /// </summary> [Serialized] [field: DocumentedByXml] public List<CollisionNotifier.EventData> ActiveCollisions { get; set; } = new List<CollisionNotifier.EventData>(); public EventData Set(EventData source) { return Set(source.ActiveCollisions); } public EventData Set(List<CollisionNotifier.EventData> activeCollisions) { ActiveCollisions.Clear(); ActiveCollisions.AddRange(activeCollisions); return this; } public void Clear() { ActiveCollisions.Clear(); } } /// <summary> /// Defines the event with the <see cref="EventData"/>. /// </summary> [Serializable] public class ActiveCollisionUnityEvent : UnityEvent<EventData> { } #region Validity Settings /// <summary> /// Determines whether the collision is valid and to add it to the active collision collection. /// </summary> [Serialized, Cleared] [field: Header("Validity Settings"), DocumentedByXml] public RuleContainer CollisionValidity { get; set; } #endregion #region Collection Events /// <summary> /// Emitted when the collision count has changed. /// </summary> [Header("Collection Events"), DocumentedByXml] public ActiveCollisionUnityEvent CountChanged = new ActiveCollisionUnityEvent(); /// <summary> /// Emitted when the collision contents have changed. /// </summary> [DocumentedByXml] public ActiveCollisionUnityEvent ContentsChanged = new ActiveCollisionUnityEvent(); #endregion #region Collision Events /// <summary> /// Emitted when the first collision occurs. /// </summary> [Header("Collision Events"), DocumentedByXml] public CollisionNotifier.UnityEvent FirstStarted = new CollisionNotifier.UnityEvent(); /// <summary> /// Emitted when a collision is added. /// </summary> [DocumentedByXml] public CollisionNotifier.UnityEvent Added = new CollisionNotifier.UnityEvent(); /// <summary> /// Emitted when a collision is removed. /// </summary> [DocumentedByXml] public CollisionNotifier.UnityEvent Removed = new CollisionNotifier.UnityEvent(); /// <summary> /// Emitted when there are no more collisions occuring. /// </summary> [DocumentedByXml] public UnityEvent AllStopped = new UnityEvent(); #endregion /// <summary> /// The current active collisions. /// </summary> public List<CollisionNotifier.EventData> Elements { get; protected set; } = new List<CollisionNotifier.EventData>(); /// <summary> /// The event data emitted on active collision events. /// </summary> protected readonly EventData eventData = new EventData(); /// <summary> /// Adds the given collision as an active collision. /// </summary> /// <param name="collisionData">The collision data.</param> [RequiresBehaviourState] public virtual void Add(CollisionNotifier.EventData collisionData) { if (!IsValidCollision(collisionData)) { return; } Elements.Add(CloneEventData(collisionData)); Added?.Invoke(collisionData); if (Elements.Count == 1) { FirstStarted?.Invoke(collisionData); } CountChanged?.Invoke(eventData.Set(Elements)); ProcessContentsChanged(); } /// <summary> /// Removes the given collision from being an active collision. /// </summary> /// <param name="collisionData">The collision data.</param> [RequiresBehaviourState] public virtual void Remove(CollisionNotifier.EventData collisionData) { if (Elements.Remove(collisionData)) { Removed?.Invoke(collisionData); EmitEmptyEvents(); } } /// <summary> /// Processes any changes to the contents of existing collisions. /// </summary> [RequiresBehaviourState] public virtual void ProcessContentsChanged() { ContentsChanged?.Invoke(eventData.Set(Elements)); } protected virtual void OnDisable() { if (Elements.Count == 0) { return; } foreach (CollisionNotifier.EventData element in Elements) { Removed?.Invoke(element); } Elements.Clear(); EmitEmptyEvents(); } /// <summary> /// Emits the appropriate events when the collection is emptied. /// </summary> protected virtual void EmitEmptyEvents() { if (Elements.Count == 0) { AllStopped?.Invoke(); } CountChanged?.Invoke(eventData.Set(Elements)); ProcessContentsChanged(); } /// <summary> /// Clones the given event data. /// </summary> /// <param name="input">The data to clone.</param> /// <returns>The cloned data.</returns> protected virtual CollisionNotifier.EventData CloneEventData(CollisionNotifier.EventData input) { return new CollisionNotifier.EventData().Set(input); } /// <summary> /// Determines if the current collision is valid. /// </summary> /// <param name="collisionData">The collision to check.</param> /// <returns>The validity result of the collision.</returns> protected virtual bool IsValidCollision(CollisionNotifier.EventData collisionData) { Transform containingTransform = collisionData.ColliderData.GetContainingTransform(); return containingTransform != null && CollisionValidity.Accepts(containingTransform.gameObject); } } }
using UnityEngine; public struct ColorHSV { float m_h; // 0..360 public float H { get => m_h; set => m_h = value % 360; } float m_s; // 0..100 public float S { get => m_s; set { if (value < 0) m_s = 0; else if (value > 100) m_s = 100; else m_s = value; } } float m_v; // 0..100 public float V { get => m_v; set { if (value < 0) m_v = 0; else if (value > 100) m_v = 100; else m_v = value; } } float m_a; // 0..100 public float A { get => m_a; set { if (value < 0) m_a = 0; else if (value > 100) m_a = 100; else m_a = value; } } public ColorHSV(float h, float s, float v) : this() { H = h; S = s; V = v; A = 100.0f; } public ColorHSV(float h, float s, float v, float a) : this() { H = h; S = s; V = v; A = a; } public ColorHSV(Color color) : this() { Color32 col32 = color; SetColorHSV(col32); } public ColorHSV(Color32 color) : this() { SetColorHSV(color); } private void SetColorHSV(Color32 color) { float div = 100.0f / 255.0f; m_a = color.a * div; m_h = 0.0f; float minRGB = Mathf.Min(Mathf.Min(color.r, color.g), color.b); float maxRGB = Mathf.Max(Mathf.Max(color.r, color.g), color.b); float delta = maxRGB - minRGB; m_v = maxRGB; if (maxRGB != 0.0f) { m_s = 255.0f * delta / maxRGB; } else { m_s = 0.0f; } if (m_s != 0.0f) { if (color.r == maxRGB) { m_h = (color.g - color.b) / delta; } else if (color.g == maxRGB) { m_h = 2.0f + (color.b - color.r) / delta; } else if (color.b == maxRGB) { m_h = 4.0f + (color.r - color.g) / delta; } } else { m_h = -1.0f; } m_h *= 60.0f; if (m_h < 0.0f) { m_h += 360.0f; } m_s *= div; m_v *= div; } public Color ToColor() { Color color = ToColor32(); return color; } public Color32 ToColor32() { float saturation = m_s * .01f; float value = m_v * 2.55f; int hi = (int)(Mathf.Floor(m_h / 60.0f)) % 6; float f = m_h / 60.0f - Mathf.Floor(m_h / 60.0f); byte v1 = (byte)Mathf.Round(value); byte p = (byte)Mathf.Round(value * (1.0f - saturation)); byte q = (byte)Mathf.Round(value * (1.0f - f * saturation)); byte t = (byte)Mathf.Round(value * (1.0f - (1.0f - f) * saturation)); byte a1 = (byte)Mathf.Round(m_a * 2.55f); switch (hi) { case 0: return new Color32(v1, t, p, a1); case 1: return new Color32(q, v1, p, a1); case 2: return new Color32(p, v1, t, a1); case 3: return new Color32(p, q, v1, a1); case 4: return new Color32(t, p, v1, a1); default: return new Color32(v1, p, q, a1); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; namespace MODEL.ViewPage { /// <summary> /// 登陆用户 模型 /// </summary> public class LoginUser { [Required(ErrorMessage="请输入用户名")] public string UserName { get; set; } [Required(ErrorMessage = "请输入密码")] public string Password { get; set; } public bool IsAlways { get; set; } } }
using ApiGetBooks.Controllers; using ApiGetBooks.Entities; using ApiGetBooks.Repositories; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; namespace ApiGetBooks.Test { public class SearchBooksRepositoryTest { protected readonly ISearchBooksRepository _SearchBooksrepository; public SearchBooksRepositoryTest(ISearchBooksRepository SearchBooksrepository) { _SearchBooksrepository = SearchBooksrepository; } string classTestingHere = "SearchBooksRepository"; List<EntitysTest> ListaDeTestes = new List<EntitysTest>(); private string methodTestingHere; private object result; private enum Result { Ok, Falhou } public List<EntitysTest> TestarTudoClasseSearchBooksRepository() { GetAllTest(); return ListaDeTestes; } public void GetAllTest() { try { methodTestingHere = MethodBase.GetCurrentMethod().Name.Replace("Test", ""); List<Books> jsonFile = ManageJson.LoadAllJson(); List<Books> countGetAllTest = _SearchBooksrepository.GetAll(null); result = jsonFile.Count == countGetAllTest.Count ? Result.Ok : Result.Falhou; ListaDeTestes.Add(new EntitysTest() { Classe = classTestingHere, Metodo = methodTestingHere, Resultado = result.ToString() }); //Próximo metodo GetIdTest(); } catch (System.Exception) { throw; } } public void GetIdTest() { methodTestingHere = MethodBase.GetCurrentMethod().Name.Replace("Test",""); var Test1 = _SearchBooksrepository.GetId(1); result = Test1.Count == 1 ? result = Result.Ok : result = Result.Falhou; ListaDeTestes.Add(new EntitysTest() { Classe = classTestingHere, Metodo = methodTestingHere, Resultado = result.ToString() }); //Próximo metodo GetNameTest(); } public void GetNameTest() { methodTestingHere = MethodBase.GetCurrentMethod().Name.Replace("Test", ""); var Test1 = _SearchBooksrepository.GetName("t","ascending"); result = Test1.Count == 5 ? result = Result.Ok : result = Result.Falhou; var Test2 = _SearchBooksrepository.GetName("x", "ascending"); result = Test2.Count == 0 ? result = Result.Ok : result = Result.Falhou; ListaDeTestes.Add(new EntitysTest() { Classe = classTestingHere, Metodo = methodTestingHere, Resultado = result.ToString() }); //Próximo metodo GetPriceTest(); } public void GetPriceTest() { methodTestingHere = MethodBase.GetCurrentMethod().Name.Replace("Test", ""); var Test1 = _SearchBooksrepository.GetPrice(10.1); result = Test1.Count == 1 ? result = Result.Ok : result = Result.Falhou; ListaDeTestes.Add(new EntitysTest() { Classe = classTestingHere, Metodo = methodTestingHere, Resultado = result.ToString() }); //Próximo metodo GetOriginallyPublishedTest(); } public void GetOriginallyPublishedTest() { methodTestingHere = MethodBase.GetCurrentMethod().Name.Replace("Test", ""); var Test1 = _SearchBooksrepository.GetOriginallyPublished("n", "ascending"); result = Test1.Count == 3 ? result = Result.Ok : result = Result.Falhou; var Test2 = _SearchBooksrepository.GetOriginallyPublished("x", "ascending"); result = Test2.Count == 0 ? result = Result.Ok : result = Result.Falhou; ListaDeTestes.Add(new EntitysTest() { Classe = classTestingHere, Metodo = methodTestingHere, Resultado = result.ToString() }); //Próximo metodo GetAuthorTest(); } public void GetAuthorTest() { methodTestingHere = MethodBase.GetCurrentMethod().Name.Replace("Test", ""); var Test1 = _SearchBooksrepository.GetAuthor("n", "ascending"); result = Test1.Count == 5 ? result = Result.Ok : result = Result.Falhou; var Test2 = _SearchBooksrepository.GetAuthor("x", "ascending"); result = Test2.Count == 0 ? result = Result.Ok : result = Result.Falhou; ListaDeTestes.Add(new EntitysTest() { Classe = classTestingHere, Metodo = methodTestingHere, Resultado = result.ToString() }); //Próximo metodo GetPageCountTest(); } public void GetPageCountTest() { methodTestingHere = MethodBase.GetCurrentMethod().Name.Replace("Test", ""); var Test1 = _SearchBooksrepository.GetPageCount(183, "ascending"); result = Test1.Count == 1 ? result = Result.Ok : result = Result.Falhou; var Test2 = _SearchBooksrepository.GetPageCount(636, "ascending"); result = Test2.Count == 1 ? result = Result.Ok : result = Result.Falhou; ListaDeTestes.Add(new EntitysTest() { Classe = classTestingHere, Metodo = methodTestingHere, Resultado = result.ToString() }); //Próximo metodo GetIllustratorTest(); } public void GetIllustratorTest() { methodTestingHere = MethodBase.GetCurrentMethod().Name.Replace("Test", ""); var Test1 = _SearchBooksrepository.GetIllustrator("n", "ascending"); result = Test1.Count == 3 ? result = Result.Ok : result = Result.Falhou; var Test2 = _SearchBooksrepository.GetIllustrator("x", "ascending"); result = Test2.Count == 0 ? result = Result.Ok : result = Result.Falhou; ListaDeTestes.Add(new EntitysTest() { Classe = classTestingHere, Metodo = methodTestingHere, Resultado = result.ToString() }); //Próximo metodo GetGenresTest(); } public void GetGenresTest() { methodTestingHere = MethodBase.GetCurrentMethod().Name.Replace("Test", ""); var Test1 = _SearchBooksrepository.GetGenres("n", "ascending"); result = Test1.Count == 5 ? result = Result.Ok : result = Result.Falhou; var Test2 = _SearchBooksrepository.GetGenres("y", "ascending"); result = Test2.Count == 3 ? result = Result.Ok : result = Result.Falhou; ListaDeTestes.Add(new EntitysTest() { Classe = classTestingHere, Metodo = methodTestingHere, Resultado = result.ToString() }); //Próximo metodo GetValueShippingTest(); } public void GetValueShippingTest() { methodTestingHere = MethodBase.GetCurrentMethod().Name.Replace("Test", ""); var Test1 = _SearchBooksrepository.GetValueShipping(1); result = Test1 == 2 ? result = Result.Ok : result = Result.Falhou; var Test2 = _SearchBooksrepository.GetValueShipping(3); result = Test2 == 1.462 ? result = Result.Ok : result = Result.Falhou; ListaDeTestes.Add(new EntitysTest() { Classe = classTestingHere, Metodo = methodTestingHere, Resultado = result.ToString() }); //Próximo metodo } } }
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace BuildingGame { class BuildManager { Map map; CellSelection cs; BuildingType toBuild; public enum BuildingType { Strasse, Wohnhaus, Holzfäller }; public BuildManager(Map map) { this.map = map; } internal void Update(GameTime gameTime) { if (cs != null) { if (Input.MouseClicked) { if (toBuild == BuildingType.Holzfäller) { Holzfäller b = new Holzfäller(); b.PlaceOnMap(map, cs.GetCells()); cs = null; } } } if (Keyboard.GetState().IsKeyDown(Keys.D1)) { cs = new CellSelection(map, 2, 2); toBuild = BuildingType.Holzfäller; } if (cs != null) cs.Update(gameTime); } public void Draw(SpriteBatch spriteBatch, GameTime gameTime) { spriteBatch.Begin(); if (cs != null) cs.Draw(spriteBatch, gameTime); spriteBatch.End(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Collections; using System.Runtime.InteropServices; using System.Diagnostics; using Microsoft.Win32; // Used for the registery using System.IO; // Used for getting all the current drives using Newtonsoft.Json; namespace pub { public partial class Form1 : Form { /* WinAPI imports*/ [DllImport("kernel32.dll")] static extern bool GetVolumeInformation( string lpRootPathName, StringBuilder lpVolumeNameBuffer, Int32 nVolumeNameSize, out Int32 lpVolumeSerialNumber, out Int32 lpMaximumComponentLength, out Int32 lpFileSystemFlags, StringBuilder lpFileSystemNameBuffer, Int32 nFileSystemNameSize ); /* Required WNDPROC */ const int WM_DEVICECHANGE = 0x219; const int DBT_DEVICEARRIVAL = 0x8000; const int DBT_DEVICEREMOVECOMPLETE = 0x8004; // const int DBT_DEVTYP_VOLUME = 0x2; // Flags used for identifying what kind of volume the inserted device is. const int DBTF_MEDIA = 0x1; // This is a CD or a USB flash drive. const int DBTF_NET = 0x2; // This is a networked drive. FileBackup backupProcesses; SettingsManager settingsManager; public string targetSettingsFolder = null; public string targetSettingsPath = null; public Form1() { InitializeComponent(); backupProcesses = new FileBackup(); settingsManager = new SettingsManager(); // Populate the connected devices. // Assign the path for the settings path targetSettingsPath = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData ), "pub\\settings.json"); targetSettingsFolder = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData ), "pub"); if (File.Exists(targetSettingsPath) == false || Directory.Exists(targetSettingsFolder) == false) // If the settings file doesn't currently exist then create it { Directory.CreateDirectory(targetSettingsFolder); // Create the folder in appdata File.Create(targetSettingsPath).Close(); // Create the json file // Set the default file backup path to appdata pub settingsManager.setBackupPath(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "pub\\backups")); } else // If there is already a file for it then just read the file and populate the settings object { settingsManager.readSettings(); // Just apply the settings to the visual elements // Path textbox textBoxFolderPath.Text = settingsManager.getSettingsObject().backupPath; // Force the textbox to show the end of the file path textBoxFolderPath.SelectionStart = textBoxFolderPath.Text.Length; textBoxFolderPath.SelectionLength = 0; } // Adding already connected drives to the program foreach (DriveInfo drive in DriveInfo.GetDrives()) // Loop through each drive connected to the PC { if (drive.DriveType == DriveType.Removable) // Check if it is a USB { volumeInformation volumeInfo = new volumeInformation(); volumeInfo.driveLetter = drive.RootDirectory.ToString(); if (GetVolumeInformation(drive.RootDirectory.ToString(), volumeInfo.volumeName, volumeInfo.volumeName.Capacity, out volumeInfo.serialNumber, out volumeInfo.maxComponentLen, out volumeInfo.fileSysetmFlags, volumeInfo.fileSystemName, volumeInfo.fileSystemName.Capacity)) listBoxDevicesConnected.Items.Add( volumeInfo ); // Add the volume information for the new drive to the end of the listbox } } // Fetch and popluate the whitelisted devices. if( settingsManager.getSettingsObject().whitelistedDrives != null ) // Make sure there is a list in the first place foreach ( var device in settingsManager.getSettingsObject().whitelistedDrives ) // Loop through all the subkeys listBoxWhitelistedDevices.Items.Add( device ); // Add each one to the end of the whitelisted devices } public string convertToDriveLetter(int mask) { int i; // Uninitialized at the moment as it gets set at the start of the for loop. for ( i = 0; i < 26; i++ ) // Loop for all the possible drive letters which is 26 { if ( (mask & 0x1) == 1 ) // Check if the mask is currently 1 which means that the letter is at this offset. break; // Exit the loop. else mask = mask >> 1; // Shift the mask over one to check on the next loop. } // A is the base offset of the char since the first capital letter of the ascii table then each letter after that is one up each time. return ( (char)( Convert.ToChar( 'A' + i ) ) ).ToString(); } protected override void WndProc(ref Message m) { int wparam = m.WParam != null ? m.WParam.ToInt32() : 0; if ( m.Msg == WM_DEVICECHANGE && wparam != 0 ) // Check that the received message is for device event { if ( wparam == DBT_DEVICEARRIVAL) // If the messages is due to a device being inserted { if( m.LParam != null ) // Make sure the LParam isn't null { DEV_BROADCAST_VOLUME hdr = new DEV_BROADCAST_VOLUME(); // New class to store the data of LParam Marshal.PtrToStructure( m.LParam, hdr ); // Cast the LParam data to the needed structutre if (hdr.dbch_devicetype == DBT_DEVTYP_VOLUME) // The type is a USB { // Now that we have idenified that it is a volume type we need to get the specifc // information about the drive. string driveLetter = convertToDriveLetter(hdr.dbcv_unitmask) + ":"; // ":" is needed for the GetVolumeInformationA function. volumeInformation volumeInfo = new volumeInformation(); if (GetVolumeInformation(driveLetter, volumeInfo.volumeName, volumeInfo.volumeName.Capacity, out volumeInfo.serialNumber, out volumeInfo.maxComponentLen, out volumeInfo.fileSysetmFlags, volumeInfo.fileSystemName, volumeInfo.fileSystemName.Capacity)) { volumeInfo.driveLetter = driveLetter + "\\"; listBoxEvents.Items.Add("[ " + DateTime.Now.ToShortTimeString() + " ] Starting the backup of USB drive, " + volumeInfo.driveLetter + volumeInfo.volumeName + "."); if ( listBoxDevicesConnected.Items.Contains( volumeInfo ) == false ) // Make sure that the device isn't already in the listbox listBoxDevicesConnected.Items.Add( volumeInfo ); // Add the newest device to the end of the device list. volumeInformation currentWhitelistedObject = settingsManager.findVolumeInformation( volumeInfo.serialNumber ); // Find the corresponding volumeinformation IEnumerable< DriveInfo > driveInfo = DriveInfo.GetDrives().Where(x => x.DriveType == DriveType.Removable); // Get all drives which have the type of removable aka USB if (driveInfo != null) { volumeInfo.unusedSpace = driveInfo.Where( x => x.VolumeLabel == volumeInfo.volumeName.ToString()).First().AvailableFreeSpace; // Set the current devices unused space settingsManager.setWhitelistedDevice( volumeInfo ); // Save this value to the JSON file } if (currentWhitelistedObject != null ) // Drive was found inside the whitelisted list { switch (currentWhitelistedObject.fileResolverMethod) { case SettingLevels.high: backupProcesses.backupHigh(settingsManager.getSettingsObject().backupPath, currentWhitelistedObject.archiveMethod, volumeInfo); break; case SettingLevels.medium: backupProcesses.backupMedium(settingsManager.getSettingsObject().backupPath, currentWhitelistedObject.archiveMethod, volumeInfo); break; case SettingLevels.low: backupProcesses.backupLow(settingsManager.getSettingsObject().backupPath, currentWhitelistedObject.archiveMethod, volumeInfo); break; default: MessageBox.Show("Error occured when getting the resolver setting."); break; } } } } } } else if (wparam == DBT_DEVICEREMOVECOMPLETE) // This is the message for when a device has been removed { if (m.LParam != null) // Make sure the LParam isn't null { DEV_BROADCAST_VOLUME hdr = new DEV_BROADCAST_VOLUME(); // New class to store the data of LParam Marshal.PtrToStructure(m.LParam, hdr); // Cast the LParam data to the needed structutre if (hdr.dbch_devicetype == DBT_DEVTYP_VOLUME) // The type is a USB { string driveLetter = convertToDriveLetter(hdr.dbcv_unitmask) + ":\\"; // ":\\" is needed as to match the style inside the structure. foreach (var item in listBoxDevicesConnected.Items) // Loop through all of the items within the listbox { volumeInformation info = (volumeInformation)item; // Cast the item to the type volumeInformation if (info.driveLetter == driveLetter) // Check if both the drive letters are the same { listBoxDevicesConnected.Items.Remove(item); // Remove the current item from the list break; // Exit the loop as it is no longer needed. } } // Add a little messsage to the events listbox listBoxEvents.Items.Add("[ " + DateTime.Now.ToShortTimeString() + " ] The drive, " + driveLetter + ", has been removed."); } } } } base.WndProc(ref m); // Call the original } private void buttonBackupLocation_Click(object sender, EventArgs e) { FolderBrowserDialog fileDialog = new FolderBrowserDialog(); // Create a new file dialog DialogResult result = fileDialog.ShowDialog(); // Open it and get the result from it if ( result == DialogResult.OK ) // If it has been selected and confirmed { // Set the path in the settings to the new path settingsManager.setBackupPath( fileDialog.SelectedPath ); textBoxFolderPath.Text = fileDialog.SelectedPath; // Force the textbox to show the end of the file path textBoxFolderPath.SelectionStart = textBoxFolderPath.Text.Length; textBoxFolderPath.SelectionLength = 0; } } private void buttonWhitelist_Click(object sender, EventArgs e) { if (listBoxDevicesConnected.SelectedItem != null) { // Save the device to the settings.json and add it to the list settingsManager.addWhitelistDevice( (volumeInformation)listBoxDevicesConnected.SelectedItem ); // Add it visually to the whitelisted device listbox listBoxWhitelistedDevices.Items.Add( listBoxDevicesConnected.SelectedItem ); } else // Tell the user that they haven't selected a device MessageBox.Show("No device has been selected. Select a device then try again."); } private void buttonRemoveDevice_Click(object sender, EventArgs e) { if (MessageBox.Show("Are you sure you want to remove this device?", "Device Removal", MessageBoxButtons.OKCancel) == DialogResult.OK) { // Remove it from the settings.json file and the device list // Check if the fuction returns 1 as it means that one device has been removed if (settingsManager.removeWhitelistedDevice((volumeInformation)listBoxWhitelistedDevices.SelectedItem) == 1) { volumeInformation volInfo = (volumeInformation)listBoxWhitelistedDevices.SelectedItem; listBoxWhitelistedDevices.Items.RemoveAt(listBoxWhitelistedDevices.SelectedIndex); // Remove it visually // Add a little messsage to the events listbox listBoxEvents.Items.Add("[ " + DateTime.Now.ToShortTimeString() + " ] The drive, " + volInfo.driveLetter + ", has been removed."); } } } private void comboBoxFileResolver_SelectedIndexChanged(object sender, EventArgs e) { // Make sure the selected item isn't null if(listBoxWhitelistedDevices.SelectedItem != null) // Update the FileResolver value for the current selected device settingsManager.setFileResolver((volumeInformation)listBoxWhitelistedDevices.SelectedItem, (SettingLevels)comboBoxFileResolver.SelectedIndex); } private void comboBoxArchiveMethod_SelectedIndexChanged(object sender, EventArgs e) { // Make sure the selected item isn't null if (listBoxWhitelistedDevices.SelectedItem != null) // Update the ArchiveMethod value for the current selected device settingsManager.setArchiveMethod((volumeInformation)listBoxWhitelistedDevices.SelectedItem, (SettingLevels)comboBoxArchiveMethod.SelectedIndex); } private void listBoxWhitelistedDevices_SelectedIndexChanged(object sender, EventArgs e) { // Update the combobox's value for the corresponding selected device comboBoxArchiveMethod.SelectedIndex = (int)settingsManager.getArchiveMethod( (volumeInformation)listBoxWhitelistedDevices.SelectedItem ); comboBoxFileResolver.SelectedIndex = (int)settingsManager.getFileResolver((volumeInformation)listBoxWhitelistedDevices.SelectedItem); } } }
 namespace Juicy.Core.UnitTest.Resources { class SomeClass { } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection.Emit; using System.Runtime.InteropServices; using System.Security.Policy; using System.Text; using System.Threading; using System.Threading.Tasks; using DataStrcture.Graph; using DataStrcture.LinkedList; using DataStrcture.Queue; using DataStrcture.Recursion; using DataStrcture.Stack; namespace Algorithom { class MainCaller { static void Main(string[] args) { // TODO 整理到notion筆記 // TODO 整理readme.md // TODO Merge Sort還未實作 UndirectedAdjacenyList graph = new UndirectedAdjacenyList(); // bfs graph //https://media.geeksforgeeks.org/wp-content/cdn-uploads/bfs1.png // dfs graph.AddEdge(1, 2); graph.AddEdge(1, 3); graph.AddEdge(2, 4); graph.AddEdge(2, 5); graph.AddEdge(2, 1); graph.AddEdge(3, 1); graph.AddEdge(3, 5); graph.AddEdge(3, 7); graph.AddEdge(3, 6); graph.AddEdge(4, 2); graph.AddEdge(4, 8); graph.AddEdge(5, 3); graph.AddEdge(5, 2); graph.AddEdge(6, 3); graph.AddEdge(7, 3); graph.AddEdge(8, 4); //var path = graph.Bfs(1, 8); //foreach (var vertice in path) //{ // Console.WriteLine(vertice); //} var p = graph.Dfs(1, 8); foreach (var vertice in p) { Console.WriteLine(vertice); } Console.Read(); } /// <summary> /// 觀察執行毫秒數,將會傳出毫秒數跟已經排序好的集合 /// </summary> /// <param name="func">要進行觀察的Func</param> public static (long Ms, List<T> SortedList) StopWatcher<T>(Func<List<T>> func) { Stopwatch sw = Stopwatch.StartNew(); var result = func.Invoke(); sw.Stop(); return (sw.ElapsedMilliseconds, result); } /// <summary> /// 取得指定大小的random list /// </summary> /// <param name="capacity">指定的陣列大小</param> /// <returns></returns> public static List<int> GetRandomList(int capacity) { if (capacity == 0) { throw new ArgumentException("陣列大小不可為0"); } List<int> result = new List<int>(); Random random = new Random(Guid.NewGuid().GetHashCode()); for (int i = 0; i < capacity; i++) { result.Add(random.Next(0, 1000)); } return result; } } }
public class Solution { public IList<string> FindRepeatedDnaSequences(string s) { var res = new List<string>(); if (s.Length <= 10) return res; var m = new Dictionary<int, int>(); int mask = 0x7ffffff; int curr = 0; for (int i=0; i<9; i++) { curr = (curr<<3) | (s[i]&7); } for (int i=9; i<s.Length; i++) { curr = ((curr&mask)<<3) | (s[i]&7); if (m.ContainsKey(curr)) { if (m[curr] == 1) { res.Add(s.Substring(i-9, 10)); m[curr]++; } } else { m[curr] = 1; } } return res; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; namespace KartSystem { public class LinkDocument:Entity { [DBIgnoreReadParam] [DBIgnoreAutoGenerateParam] public override string FriendlyName { get { return "Связь между документами"; } } public long IdBaseDoc { get; set; } public long IdChildDoc { get; set; } } }
using System; using System.Collections.Generic; using System.IO; namespace wsb { [System.Serializable] public class VendingMachine { // unikatowy kod maszyny public string Code { get; set; } // adres miejsca gidze jest postawiona public string Adress { get; set; } public VendingMachineType Type { get; set; } // ilosc miejsc na produkty, np jak ma 10 to moze byc 5 batonikow i 5 roznych napoi public int NumberOfSlots { get; set; } public List<int> SlotsToRefill = new List<int>(); // ile miesci sie produktow w jednym slocie public int SlotDepthness { get; set; } public bool IsWorking { get; set; } = true; public List<Product> Slots { get; set; } public List<Transaction> transactionList; public VendingMachine() { this.SlotDepthness = 20; this.NumberOfSlots = 60; InitializeSlots(); } public VendingMachine(int numberOfSlots) { this.SlotDepthness = 20; this.NumberOfSlots = numberOfSlots; InitializeSlots(); } private void InitializeSlots() { this.Slots = new List<Product>(); transactionList = new List<Transaction>(); System.Threading.Thread.Sleep(500); } public void FillProduct(int productCode) { Slots[productCode].Count = SlotDepthness; } public void RefillMissingProducts() { foreach ( int slot in SlotsToRefill ) { FillProduct(slot); Console.WriteLine("Uzupełniono slot nr: " + slot); } SlotsToRefill.Clear(); } public void BuyProduct(int productCode) { if ( IsWorking ) { if ( Slots[productCode].Count != 0 ) { Console.WriteLine("Zakupiono " + Slots[productCode].Name + " za " + Slots[productCode].Price + " zł" + " Zostało " + (Slots[productCode].Count-1) + "/" + SlotDepthness + " Automat na ulicy: " + Adress); Slots[productCode].Count--; transactionList.Add(new Transaction(productCode, DateTime.Now)); } CheckSlot(productCode); } // kod błedu: maszyna nie działa else SendErrorCode(-1); } void CheckSlot(int productCode) { if ( Slots[productCode].Count <= SlotDepthness / 10 && Slots[productCode].Count > 0 ) { // kod błedu: mniej niz 10% produktu SendErrorCode(5); if ( !SlotsToRefill.Contains(productCode) ) SlotsToRefill.Add(productCode); } else if ( Slots[productCode].Count == 0 ) // kod błedu: produtku nie ma SendErrorCode(10); if (SlotsToRefill.Count >= NumberOfSlots/3) { // wyslij do serwera prośbe o uzupełnienie RefillMissingProducts(); } IsWorking = RandomBreakChance(); } bool RandomBreakChance() { Random rnd = new Random(); if ( rnd.Next(1, 1000) == 2 ) return false; return true; } public void SendErrorCode(int errCode) { //TODO: Wysłanie do serwera ostrzeżenia //Oproznienie cache transakcji, przy okazji Console.WriteLine("Wysłano Kod Błędu => " + errCode + " " + Adress + " " + Code); EmptyTransactionChache(); } public void EmptyTransactionChache() { //wysylanie listy transakcji do serwera oraz usuwanie cache transactionList.Clear(); } public void SendStatus() { } } }
using UnityEngine; using System.Collections; public class ClownMovement : MonoBehaviour { public GameObject Clown; public bool setActive = false; // Clown is inactive to begin public bool onScreen = false; // Clown is off screen to begin public Transform Check; private float Speed; public bool Token = false; // Use this for initialization void Start () { float randomChance = Random.Range(0f, 100.0f); // Random number generated to help determine if Clown is initially spawned if (randomChance < 3) { // 3% chance that the Clown initially spawns setActive = true; // Set Clown active } if (setActive) { // if the Clown is active, spawn it on screen using generateClown generateClown (); onScreen = true; } else { // if the Clown is not active, place off screen transform.position = new Vector2 (0, -550); } } // Update is called once per frame void Update () { float randomChance = Random.Range(0f, 100.0f); // Random number generated every update to determine if Clown is spawned if ((randomChance < .5) && !setActive) { // Less than .5% chance the Clown is spawned setActive = true; } if (setActive && onScreen) { // if the Clown is on the screen and active if (Speed > 0) { // if the spawned Clown is moving right if (transform.position.x > 40) { // if the Clown's x position is out of the right limit, move off screen and make inactive transform.position = new Vector2 (0, -550); setActive = false; onScreen = false; } else { // otherwise move Clown right transform.position = new Vector2 (transform.position.x + Speed, transform.position.y); } } else { // if the spawned Clown is moving left if (transform.position.x < -40) { // if the spawbed Clown's x position is out of the right limit, move off screen and make inactive transform.position = new Vector2 (0, -550); setActive = false; onScreen = false; } else { // otherwise move Clown left transform.position = new Vector2 (transform.position.x + Speed, transform.position.y); } } } else if (setActive && !onScreen) { // if the Clown is active but not on screen, spawn Clown on screen generateClown (); onScreen = true; } else { // otherwise if Clown is inactive, stay/become inactive transform.position = new Vector2 (0, -550); setActive = false; onScreen = false; } } void generateClown () { float randomNumberX = Random.Range(0f, 100.0f); // random value used to determine if Clown enters from left or right float randomNumberY = Random.Range(0f, 14.0f); // random value that determines y pos of Clown print (randomNumberX); print (randomNumberY); if (randomNumberX > 50) { // 50% chance the Clown moves left transform.position = new Vector2 (40, randomNumberY); Speed = -0.07f; // speed of Clown } else { // 50% chance the Clown moves right transform.position = new Vector2 (-40, randomNumberY); Speed = 0.07f; // speed of Clown } } void OnTriggerEnter2D(Collider2D other) // if Clown intersects Monkey, it is set inactive { if(other.gameObject.layer == LayerMask.NameToLayer("Death")) { setActive = false; Token = true; // token is set true, and will be 'collected' in PlayerTransition } } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Rollbar; using Rollbar.DTOs; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading; using Exception = System.Exception; namespace Utilities { public class Logging : Telemetry { private static readonly Regex JsonRegex = new Regex(@"^{.*}$", RegexOptions.Singleline); public static readonly string LogFile = Constants.DATA_DIR + @"\eddi.log"; public static bool Verbose { get; set; } public static void Error(string message, object data = null, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "") { handleLogging(ErrorLevel.Error, message, data, memberName, filePath); } public static void Warn(string message, object data = null, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "") { handleLogging(ErrorLevel.Warning, message, data, memberName, filePath); } public static void Info(string message, object data = null, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "") { handleLogging(ErrorLevel.Info, message, data, memberName, filePath); } public static void Debug(string message, object data = null, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "") { handleLogging(ErrorLevel.Debug, message, data, memberName, filePath); } private static void handleLogging(ErrorLevel errorlevel, string message, object data, string memberName, string filePath) { try { System.Threading.Tasks.Task.Run(() => { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; string timestamp = DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture); var shortPath = Redaction.RedactEnvironmentVariables(Path.GetFileNameWithoutExtension(filePath)); var method = Redaction.RedactEnvironmentVariables(memberName); message = $"{shortPath}:{method} {Redaction.RedactEnvironmentVariables(message)}"; var preppedData = FilterAndRedactData(data); switch (errorlevel) { case ErrorLevel.Debug: { if (Verbose) { log(timestamp, errorlevel, message, preppedData); } if (TelemetryEnabled) { RecordTelemetryInfo(errorlevel, message, preppedData); } break; } case ErrorLevel.Info: case ErrorLevel.Warning: { log(timestamp, errorlevel, message, preppedData); if (TelemetryEnabled) { RecordTelemetryInfo(errorlevel, message, preppedData); } break; } case ErrorLevel.Error: case ErrorLevel.Critical: { log(timestamp, errorlevel, message, preppedData); if (TelemetryEnabled) { ReportTelemetryEvent(timestamp, errorlevel, message, preppedData); } break; } } }).ConfigureAwait(false); } catch { // Nothing to do here } } private static readonly object logLock = new object(); private static void log(string timestamp, ErrorLevel errorlevel, string message, object data = null) { var str = $"{timestamp} [{errorlevel}] {message}" + (data != null ? $": {Redaction.RedactEnvironmentVariables(JsonConvert.SerializeObject(data))}" : null); lock (logLock) { try { using (StreamWriter file = new StreamWriter(LogFile, true)) { file.WriteLine(str); } } catch (Exception) { // Failed; can't do anything about it as we're in the logging code anyway } } if (errorlevel == ErrorLevel.Error || errorlevel == ErrorLevel.Critical) { Console.WriteLine(str); } } private static void RecordTelemetryInfo(ErrorLevel errorLevel, string message, IDictionary<string, object> preppedData = null) { if (Enum.TryParse(errorLevel.ToString(), out TelemetryLevel telemetryLevel)) { try { var telemetryBody = preppedData is null ? new LogTelemetry(message) : new LogTelemetry(message, preppedData); var telemetry = new Rollbar.DTOs.Telemetry(TelemetrySource.Client, telemetryLevel, telemetryBody); LockManager.GetLock(nameof(Telemetry), () => { RollbarInfrastructure.Instance.TelemetryCollector?.Capture(telemetry); }); } catch (RollbarException rex) { Warn(rex.Message, rex); } catch (HttpRequestException httpEx) { Warn(httpEx.Message, httpEx); } catch (Exception ex) { if (ex.Source != "Rollbar") { Warn(ex.Message, ex); } } } } private static void ReportTelemetryEvent(string timestamp, ErrorLevel errorLevel, string message, Dictionary<string, object> preppedData = null) { try { LockManager.GetLock(nameof(Telemetry), () => { RollbarLocator.RollbarInstance.Log(errorLevel, message, preppedData); }); string personID = RollbarLocator.RollbarInstance.Config.RollbarPayloadAdditionOptions.Person?.Id; if (!string.IsNullOrEmpty(personID)) { log(timestamp, errorLevel, $"Reporting error to Rollbar telemetry service, anonymous ID {personID}: {message}"); } } catch (RollbarException rex) { Warn(rex.Message, rex); } catch (HttpRequestException httpEx) { Warn(httpEx.Message, httpEx); } catch (Exception ex) { Warn(ex.Message, ex); } } private static Dictionary<string, object> FilterAndRedactData(object data) { if (data is null) { return null; } try { if (data is string str && !JsonRegex.IsMatch(str)) { return Wrap("message", Redaction.RedactEnvironmentVariables(str)); } else { // Serialize the data to a string string serialized = JsonConvert.SerializeObject(data); serialized = FilterPropertiesFromJsonString(serialized); serialized = Redaction.RedactEnvironmentVariables(serialized); if (data is Exception) { return JsonConvert.DeserializeObject<Dictionary<string, object>>(serialized); } else { var jToken = JToken.Parse(serialized); if (jToken is JArray jArray) { return Wrap("data", jArray); } if (jToken is JObject jObject) { return jObject.ToObject<Dictionary<string, object>>(); } } } } catch (Exception) { // Something went wrong. Return null and don't send data to Rollbar } return null; } private static Dictionary<string, object> Wrap(string key, object data) { var wrappedData = new Dictionary<string, object>() { {key, data} }; return wrappedData; } private static string FilterPropertiesFromJsonString(string json) { if (string.IsNullOrEmpty(json)) { return null; } try { var jToken = JToken.Parse(json); if (jToken is JObject data) { // Strip module data that is not useful to report for more consistent matching // Strip commodity data that is not useful to report for more consistent matching // Strip sensitive or personal data like "apiKey" or "frontierID" string[] filterProperties = { "priority", "health", "buyprice", "stock", "stockbracket", "sellprice", "demand", "demandbracket", "StatusFlags", "apiKey", "frontierID", "FID", "ActiveFine", "CockpitBreach", "BoostUsed", "FuelLevel", "FuelUsed", "JumpDist", "Wanted", "Latitude", "Longitude", "MyReputation", "SquadronFaction", "HappiestSystem", "HomeSystem", "access_token", "refresh_token", "uploaderID", "commanderName" }; foreach (string property in filterProperties) { data.Descendants() .OfType<JProperty>() .Where(attr => attr.Name.StartsWith(property, StringComparison.OrdinalIgnoreCase)) .ToList() .ForEach(attr => attr.Remove()); } json = data.ToString(); } } catch (Exception) { // Not parseable json. } return json; } public static void incrementLogs() { // Ensure dir exists DirectoryInfo directoryInfo = new DirectoryInfo(Constants.DATA_DIR); if (!directoryInfo.Exists) { Directory.CreateDirectory(Constants.DATA_DIR); } // Obtain files, sorting by last write time to ensure that older files are incremented prior to newer files foreach (FileInfo file in directoryInfo.GetFiles().OrderBy(f => f.LastWriteTimeUtc).ToList()) { string filePath = file.FullName; if (filePath.EndsWith(".log")) { try { bool parsed = int.TryParse(filePath.Replace(Constants.DATA_DIR + @"\eddi", "").Replace(".log", ""), out int i); ++i; // Increment our index number if (i >= 10) { File.Delete(filePath); } else { // This might be our primary log file, so we lock it prior to doing anything with it lock (logLock) { File.Move(filePath, Constants.DATA_DIR + @"\eddi" + i + ".log"); } } } catch (Exception) { // Someone may have had a log file open when this code executed? Nothing to do, we'll try again on the next run } } } } } public class Telemetry { // Exception handling (configuration instructions are at https://github.com/rollbar/Rollbar.NET) // The Rollbar API test console is available at https://docs.rollbar.com/reference. const string rollbarWriteToken = "c94faac5c4d8447fb05654e0488305db"; public static bool TelemetryEnabled { get => RollbarLocator.RollbarInstance.Config.RollbarDeveloperOptions.Transmit; // ReSharper disable once ValueParameterNotUsed set => RollbarLocator.RollbarInstance.Config.RollbarDeveloperOptions.Transmit = #if DEBUG false; #else value; #endif } public static void Start(string uniqueId, bool fromVA = false) { try { TelemetryEnabled = true; var config = new RollbarInfrastructureConfig( rollbarWriteToken, Constants.EDDI_VERSION.ToString() ); // Configure telemetry var telemetryOptions = new RollbarTelemetryOptions( true, 250 ); config.RollbarTelemetryOptions.Reconfigure( telemetryOptions ); // Configure Infrastructure Options var infrastructureOptions = new RollbarInfrastructureOptions { MaxReportsPerMinute = 1, PayloadPostTimeout = TimeSpan.FromSeconds( 10 ), CaptureUncaughtExceptions = false }; config.RollbarInfrastructureOptions.Reconfigure( infrastructureOptions ); // Configure Logger Options var loggerOptions = new RollbarLoggerConfig( rollbarWriteToken, Constants.EDDI_VERSION.ToString() ); var loggerDataSecurityOptions = new RollbarDataSecurityOptions( PersonDataCollectionPolicies.None, IpAddressCollectionPolicy.DoNotCollect, new[] { "Commander", "apiKey", "commanderName", "access_token", "refresh_token", "uploaderID" } ); var assyMetadataAttributes = Assembly.GetExecutingAssembly()?.GetCustomAttributes<AssemblyMetadataAttribute>().ToList(); var loggerPayloadOptions = new RollbarPayloadAdditionOptions() { Person = new Person( uniqueId + ( fromVA ? " VA" : "" ) ), Server = new Server { Root = "https://github.com/EDCD/EDDI", Branch = assyMetadataAttributes.SingleOrDefault( a => a.Key == "SourceBranch")?.Value }, CodeVersion = assyMetadataAttributes.SingleOrDefault( a => a.Key == "SourceRevisionId" )?.Value }; loggerOptions.RollbarDataSecurityOptions.Reconfigure( loggerDataSecurityOptions ); loggerOptions.RollbarPayloadAdditionOptions.Reconfigure( loggerPayloadOptions ); config.RollbarLoggerConfig.Reconfigure( loggerOptions ); // Initialize our configured client RollbarInfrastructure.Instance.Init( config ); RollbarLocator.RollbarInstance.Configure( config.RollbarLoggerConfig ); RollbarLocator.RollbarInstance.InternalEvent += OnRollbarInternalEvent; Thread.Sleep( 100 ); // Give some space for Rollbar to initialize before we begin sending data } catch ( Exception e ) { TelemetryEnabled = false; Logging.Warn( "Telemetry process has failed", e ); } } /// <summary> /// Called when rollbar internal event is detected. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="RollbarEventArgs"/> instance containing the event data.</param> private static void OnRollbarInternalEvent ( object sender, RollbarEventArgs e ) { if ( e is RollbarApiErrorEventArgs apiErrorEvent ) { Logging.Warn(apiErrorEvent.ErrorDescription, apiErrorEvent); return; } if ( e is CommunicationEventArgs ) { //TODO: handle/report Rollbar API communication event as needed... return; } if ( e is CommunicationErrorEventArgs commErrorEvent ) { Logging.Warn( commErrorEvent.Error.Message, commErrorEvent ); return; } if ( e is InternalErrorEventArgs internalErrorEvent ) { Logging.Warn( internalErrorEvent.Details, internalErrorEvent ); return; } } } }
public interface IGenericRepository<TEntity> where TEntity : class { IList<TEntity> GetAll(); TEntity GetById(string rowid); void Create(TEntity entity); void Update(string rowid, TEntity entity); void Delete(string rowid); }
namespace Models.Towers { public class PistolModel : IWeapon { public int Radius { get { return 2; } } public int Damage { get { return 1; } } public float RechargeTime { get { return 0.5f; } } public float BulletSpeed { get { return 5f; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace HCBot.Runner.Schedule { public class FlatFileTrainingScheduleProvider : ITrainingScheduleProvider { readonly string filePath; public FlatFileTrainingScheduleProvider(string path) { filePath = path; } public TrainingSchedule Load() { var schedule = new TrainingSchedule(); var scheduleCsv = File.ReadAllLines(Path.Combine(filePath, "Schedule.csv")); schedule.Trainigs.AddRange( scheduleCsv.Select(l => new Training { TrainingDayOfWeek = TrainingSchedule.GetDayOfWeek(l.Split(',')[0]), Location = new TrainingLocation { Name = l.Split(',')[1] }, TrainingType = TrainingSchedule.GetTrainingType(l.Split(',')[2]), TimeFrom = TrainingSchedule.GetFrom(l.Split(',')[3]), TimeTo = TrainingSchedule.GetTo(l.Split(',')[3]) }).ToList()); return schedule; } } }
namespace Pobs.Domain { public enum ReactionType { Upvote = 1, ThisMadeMeThink = 2, ThisChangedMyView = 3, NotRelevant = 4, YouBeTrolling = 5, } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HomeWork7_2 { class Program { static void TestCh(double a) { if (a > 0) { Console.WriteLine("{0} положительное число",a); } else { Console.WriteLine("{0} отрицательное число", a); } } static void TestCh1(double a) { double ostatok = 0; int summ_count = 0; for(int i = 1; i <= 9; i++) { ostatok = a % i; if (ostatok == 0) { summ_count = summ_count + 1; } } if (a> 9) { summ_count++; } if (summ_count == 2) { Console.WriteLine("{0} простое число",a); } else { Console.WriteLine("{0} составное число", a); } } static void Main(string[] args) { Console.WriteLine("Введите число отличное от 0"); double digital = Convert.ToDouble(Console.ReadLine()); TestCh(digital);//отрицательное или положительное число TestCh1(digital);//простое или составное число Console.ReadKey(); } } }
using ServiceQuotes.Application.DTOs.ServiceRequest; namespace ServiceQuotes.Application.DTOs.Quote { public class GetQuoteWithServiceDetailsResponse : GetQuoteResponse { public GetServiceWithCustomerAndAddressResponse ServiceRequest { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using CSVHandler; using System.Windows; using System.Collections.ObjectModel; namespace Tax_Time.DataModel { public class DataFactory { List<KeyValuePair<String, CSVHandler.Transaction>> listOfTrans; public System.Data.DataTable dt; public ObservableCollection<String> overallQuery; object[,] arr; public DataFactory() { listOfTrans = new List<KeyValuePair<string, CSVHandler.Transaction>>(); dt = new System.Data.DataTable(); overallQuery = new ObservableCollection<String>(); } //Takes the file path from the UI to a selected CSV file, stripps it and passes each line to the datafactory to create Transaction objects. public void dataLibraryFromFile(String fileName) { bool validFile = false; while (validFile == false) try { using (StreamReader sr = new StreamReader(fileName)) { String headerLine = sr.ReadLine(); String line = sr.ReadLine(); while (!(sr.EndOfStream)) { //Send each line to factory method and return each object to an arraylist container. try { Transaction eachLine = TransactionFactory.createTransaction(line); listOfTrans.Insert(0, new KeyValuePair<String, Transaction>(eachLine.getTransType(), eachLine)); line = sr.ReadLine(); } catch (Exception exc) { string factoryMethodFail = "Please make sure that you are using the 'Basic' CSV export option\n\n" + exc.Message; MessageBox.Show(factoryMethodFail, "Trouble reading that file"); break; } validFile = true; } } } catch (System.IO.FileNotFoundException fnfe) { string fileReadError = "Incorrect file path or file has been changed.\n\n" + fnfe.Message; MessageBox.Show(fileReadError, "Could not locate that file"); validFile = false; break; } catch (Exception ex) { string factoryMethodFail = "There was a problem accessing that file. Please try again.\n\n" + ex.Message; MessageBox.Show(factoryMethodFail, "Trouble reading the file"); validFile = false; break; } } //Takes the selected query term from the UI and fills an arraylist with terms from the overall collection stripped from the CSV file. //Builds a datatable at the same time that is then used to create a 2D array for Excel automation public void searchResults(String pSearchTerm) { overallQuery.Clear(); //clear the arraylist from any previous filter calls, so that only one query term is returned. dt.Reset(); //Reset the datatable so that only one search term is output to Excel. dt.Columns.Add("Date"); dt.Columns.Add("Vendor"); dt.Columns.Add("Value"); if (pSearchTerm.Equals("Direct Debit") || pSearchTerm.Equals("Direct Credit") || pSearchTerm.Equals("Automatic Payment") || pSearchTerm.Equals("Online Payment") || pSearchTerm.Equals("Salary") || pSearchTerm.Equals("Point of Sale")) { for (int i = 0; i < listOfTrans.Count; i++) { if (listOfTrans[i].Key.Equals(pSearchTerm)) { String s = listOfTrans[i].Value.toString(); overallQuery.Add(s); System.Data.DataRow _eachRow = dt.NewRow(); _eachRow["Date"] = listOfTrans[i].Value.getTransDate(); _eachRow["Vendor"] = listOfTrans[i].Value.getVendor(); _eachRow["Value"] = listOfTrans[i].Value.getTransValue(); dt.Rows.Add(_eachRow); } } } else if (pSearchTerm.Equals("Meridian Energy") || pSearchTerm.Equals("Financial Synergy") || pSearchTerm.Equals("Vero") || pSearchTerm.Equals("Auckland Council") || pSearchTerm.Equals("Southland District Council") || pSearchTerm.Equals("Watercare Services") || pSearchTerm.Equals("AON") || pSearchTerm.Equals("Busy Bodies") || pSearchTerm.Equals("NZTA Crown")){ for (int i = 0; i < listOfTrans.Count; i++) { String test = listOfTrans[i].Value.getVendor(); if (test.Contains(pSearchTerm.ToUpper())) { String s = listOfTrans[i].Value.toString(); overallQuery.Add(s); System.Data.DataRow _eachRow = dt.NewRow(); _eachRow["Date"] = listOfTrans[i].Value.getTransDate(); _eachRow["Vendor"] = listOfTrans[i].Value.getVendor(); _eachRow["Value"] = listOfTrans[i].Value.getTransValue(); dt.Rows.Add(_eachRow); } } } else{ //keyword search for (int i = 0; i < listOfTrans.Count; i++) { String test = listOfTrans[i].Value.toString().ToLower(); if (test.Contains(pSearchTerm.ToLower())) { String s = listOfTrans[i].Value.toString(); overallQuery.Add(s); System.Data.DataRow _eachRow = dt.NewRow(); _eachRow["Date"] = listOfTrans[i].Value.getTransDate(); _eachRow["Vendor"] = listOfTrans[i].Value.getVendor(); _eachRow["Value"] = listOfTrans[i].Value.getTransValue(); dt.Rows.Add(_eachRow); } } } } //Simple method to return the subset collection filtered from the overall collection based on the searchterm. public ObservableCollection<String> getSearchResults(){ return overallQuery; } //Simple method that returns the datatable object of items filtered from the overall collection based on the searchterm. public System.Data.DataTable getDataTable(){ return dt; } //Accessor method that returns the data table constructed after each transaction type query as a 2D array. This is in turn sent to the VM when Excel automation //for results is required. public object[,] getDataTableAsArray() { object[,] arr = new object[dt.Rows.Count, dt.Columns.Count]; for (int r = 0; r < dt.Rows.Count; r++) { System.Data.DataRow dr = dt.Rows[r]; for (int c = 0; c < dt.Columns.Count; c++) { arr[r, c] = dr[c]; } } return arr; } }//end searchResults }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System.IO; namespace Colours { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D tex_player, tex_enemy_tiny, tex_enemy_small, tex_enemy_medium, tex_enemy_large, tex_enemy_huge, tex_enemy_xbox, tex_wep_none, tex_hair_centre, tex_hair_ver, tex_hair_hor, tex_col_wht, tex_col_red, tex_col_grn, tex_col_blu, tex_col_cyn, tex_col_mgn, tex_col_ylo, tex_col_blk, tex_col_gry, tex_trans_wht, tex_trans_red, tex_trans_grn, tex_trans_blu, tex_trans_cyn, tex_trans_mgn, tex_trans_ylo, tex_trans_blk, tex_trans_gry, tex_wep_a, tex_wep_a_f, tex_wep_a_i, tex_wep_a_e, tex_wep_a_x, tex_wep_a_f1, tex_wep_b, tex_wep_b_f, tex_wep_b_i, tex_wep_b_e, tex_wep_b_x, tex_wep_b_x_i, tex_wep_b_x_i1, tex_wep_b_x_i2, tex_wep_c, tex_wep_c_f, tex_wep_c_i, tex_wep_c_e, tex_wep_c_x, tex_wep_d, tex_wep_d_f, tex_wep_d_i, tex_wep_d_e, tex_wep_d_x, tex_hair_a, tex_hair_a1, tex_hair_b, tex_hair_c, tex_hair_d, tex_splash, tex_menubuttons, tex_pause, tex_pause_over, tex_howto, tex_scorebg, tex_gameover; SoundEffect snd_atatat, snd_spawn, snd_death, snd_explode, snd_bgm, snd_hit; SoundEffectInstance snd_explode_instance, snd_bgm_instance; bool music = true; bool sfx = true; SpriteFont font; List<Enemy> enemyList = new List<Enemy>();//Enemy list List<Bullet> bulletList = new List<Bullet>();//Projectile List Player[] hiscores = new Player[5] { new Player (896, "Hitagi"), new Player(1024, "Suruga"), new Player(512, "Hanekawa"), new Player (880, "Araragi"), new Player(120, "Sengoku" )}; // used to store high scores String currentFile = "Hiscores.txt"; Color grm = new Color(127, 127, 127, 255); UI ui1; Player player1; string newname = ""; Weapon[] weapons = new Weapon[5]; Texture2D[] enemytex = new Texture2D[6]; MouseState mouseStatePrev, mouseState; KeyboardState keyStatePrev, keyState; Keys[] oldKeys = new Keys[0]; const int screenwidth = 640; const int screenheight = 896; Vector2 midpoint; Vector2 mousePos; Vector2 mousePosPrev; Vector2 mouseLeftPrev; Vector2 mouseRightPrev; bool select; const float SPAWNTIMERPREMAX = 5; float spawntimerpremax = 5; float spawntimer; bool spawn = true; const byte SPLASH = 0, MENU = 1, GAME = 2, PAUSE = 3, GAMEOVER = 4; byte gameMode = SPLASH; int lasthit = -1; int pausetimer; bool drawScores; bool drawHow; bool takename; bool debug = false; bool debugmsg = true; int saved; int loaded; bool excepio; bool excepfnf; FileNotFoundException excepfnfproblem; Rectangle menu1, menu2, menu3, menu4, noticeRect; Rectangle rectRed, rectGreen, rectBlue, rectCyan, rectMagenta, rectYellow, rectClear, rectBlack, rectWhite; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.IsFullScreen = false; graphics.PreferredBackBufferHeight = screenheight; graphics.PreferredBackBufferWidth = screenwidth; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { this.IsMouseVisible = false; // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); font = Content.Load<SpriteFont>("squarefont"); tex_player = Content.Load<Texture2D>("PlayerEdgeFill"); tex_wep_none = Content.Load<Texture2D>("Wep_None"); tex_enemy_tiny = Content.Load<Texture2D>("Enemy_Tiny"); tex_enemy_small = Content.Load<Texture2D>("Enemy_Small"); tex_enemy_medium = Content.Load<Texture2D>("Enemy_Medium"); tex_enemy_large = Content.Load<Texture2D>("Enemy_Large"); tex_enemy_huge = Content.Load<Texture2D>("Enemy_Huge"); tex_enemy_xbox = Content.Load<Texture2D>("Enemy_Xbox"); tex_wep_a = Content.Load<Texture2D>("Wep_Atatat"); tex_wep_a_f = Content.Load<Texture2D>("Wep_Atatat_Fire"); tex_wep_a_i = Content.Load<Texture2D>("Wep_Atatat_Impact"); //tex_wep_a_e = Content.Load<Texture2D>("Wep_Atatat_Effect"); tex_wep_a_x = Content.Load<Texture2D>("Wep_Atatat_X"); tex_wep_a_f1 = Content.Load<Texture2D>("Wep_Atatat_Fire1"); tex_wep_b = Content.Load<Texture2D>("Wep_Boom"); tex_wep_b_f = Content.Load<Texture2D>("Wep_Boom_Fire"); //tex_wep_b_i = Content.Load<Texture2D>("Wep_Boom_Impact"); //tex_wep_b_e = Content.Load<Texture2D>("Wep_Boom_Effect"); tex_wep_b_x = Content.Load<Texture2D>("Wep_Boom_X"); tex_wep_b_x_i = Content.Load<Texture2D>("Wep_Boom_X_I"); tex_wep_b_x_i1 = Content.Load<Texture2D>("Wep_Boom_X_I1"); tex_wep_b_x_i2 = Content.Load<Texture2D>("Wep_Boom_X_I2"); tex_wep_c = Content.Load<Texture2D>("Wep_Coil"); tex_wep_c_f = Content.Load<Texture2D>("Wep_Coil_Fire"); //tex_wep_c_i = Content.Load<Texture2D>("Wep_Coil_Impact"); //tex_wep_c_e = Content.Load<Texture2D>("Wep_Coil_Effect"); tex_wep_c_x = Content.Load<Texture2D>("Wep_Coil_X"); tex_wep_d = Content.Load<Texture2D>("Wep_Depleted"); tex_wep_d_f = Content.Load<Texture2D>("Wep_Depleted_Fire"); tex_wep_d_i = Content.Load<Texture2D>("Wep_Depleted_Impact"); tex_wep_d_e = Content.Load<Texture2D>("Wep_Depleted_Effect"); tex_wep_d_x = Content.Load<Texture2D>("Wep_Depleted_X"); tex_hair_centre = Content.Load<Texture2D>("X_Centre"); tex_hair_hor = Content.Load<Texture2D>("X_Hor"); tex_hair_ver = Content.Load<Texture2D>("X_Ver"); tex_col_wht = Content.Load<Texture2D>("Col_White"); tex_col_red = Content.Load<Texture2D>("Col_Red"); tex_col_grn = Content.Load<Texture2D>("Col_Green"); tex_col_blu = Content.Load<Texture2D>("Col_Blue"); tex_col_cyn = Content.Load<Texture2D>("Col_Cyan"); tex_col_ylo = Content.Load<Texture2D>("Col_Yellow"); tex_col_mgn = Content.Load<Texture2D>("Col_Magenta"); tex_col_blk = Content.Load<Texture2D>("Col_Black"); tex_col_gry = Content.Load<Texture2D>("Col_Grey"); tex_trans_wht = Content.Load<Texture2D>("Trans_White"); tex_trans_red = Content.Load<Texture2D>("Trans_Red"); tex_trans_grn = Content.Load<Texture2D>("Trans_Green"); tex_trans_blu = Content.Load<Texture2D>("Trans_Blue"); tex_trans_cyn = Content.Load<Texture2D>("Trans_Cyan"); tex_trans_ylo = Content.Load<Texture2D>("Trans_Yellow"); tex_trans_mgn = Content.Load<Texture2D>("Trans_Magenta"); tex_trans_blk = Content.Load<Texture2D>("Trans_Black"); tex_trans_gry = Content.Load<Texture2D>("Trans_Grey"); Texture2D[] uicontent = new Texture2D[] { tex_hair_centre, tex_hair_hor, tex_hair_ver, tex_col_wht, tex_col_red, tex_col_grn, tex_col_blu, tex_col_cyn, tex_col_mgn, tex_col_ylo, tex_col_blk, tex_col_gry }; tex_splash = Content.Load<Texture2D>("Splash"); tex_menubuttons = Content.Load<Texture2D>("MenuButtons"); tex_pause = Content.Load<Texture2D>("PauseScreen"); tex_pause_over = Content.Load<Texture2D>("PauseOverlay"); tex_howto = Content.Load<Texture2D>("Howto"); tex_scorebg = Content.Load<Texture2D>("ScoreBG"); tex_gameover = Content.Load<Texture2D>("GameOver"); snd_atatat = Content.Load<SoundEffect>("Atatat"); snd_bgm = Content.Load<SoundEffect>("BGM"); snd_death = Content.Load<SoundEffect>("Death"); snd_explode = Content.Load<SoundEffect>("Explode"); snd_spawn = Content.Load<SoundEffect>("Spawn"); snd_hit = Content.Load<SoundEffect>("Hit"); snd_bgm_instance = snd_bgm.CreateInstance(); snd_bgm_instance.IsLooped = true; snd_explode_instance = snd_explode.CreateInstance(); snd_bgm_instance.Volume = 0.05f; snd_explode_instance.Volume = 0.1f; midpoint = new Vector2(screenwidth / 2, screenheight / 2); menu1 = new Rectangle(256, 532, 128, 32); menu2 = new Rectangle(256, 596, 128, 32); menu3 = new Rectangle(256, 660, 128, 32); menu4 = new Rectangle(256, 725, 128, 32); noticeRect = new Rectangle(20, 63, 600, 320); rectRed= new Rectangle(210, 0, 220, 400); rectGreen= new Rectangle(0, 448, 210, 448); rectBlue= new Rectangle(430, 448, 210, 448); rectCyan= new Rectangle(210, 496, 220, 400); rectMagenta= new Rectangle(430, 0, 210, 448); rectYellow= new Rectangle(0, 0, 210, 448); rectClear = new Rectangle(210, 400, 220, 96); rectBlack= new Rectangle(210, 400, 220, 48); rectWhite= new Rectangle(210, 448, 220, 48); ui1 = new UI(spriteBatch, font, uicontent); weapons[0] = new WeaponZ(ui1, tex_wep_none); weapons[1] = new WeaponA(ui1, tex_wep_a, tex_wep_a_x); weapons[2] = new WeaponB(ui1, tex_wep_b, tex_wep_b_x, new Texture2D[3]{tex_wep_b_x_i, tex_wep_b_x_i1, tex_wep_b_x_i2}); weapons[3] = new WeaponC(ui1, tex_wep_c, tex_wep_c_x);//use effect constructor weapons[4] = new WeaponD(ui1, tex_wep_d, tex_wep_d_x); player1 = new Player(tex_player, weapons, ui1); enemytex[0] = tex_enemy_tiny; enemytex[1] = tex_enemy_small; enemytex[2] = tex_enemy_medium; enemytex[3] = tex_enemy_large; enemytex[4] = tex_enemy_huge; enemytex[5] = tex_enemy_xbox; weapons[0].ChangeLevel(3, 0); weapons[1].ChangeLevel(3, 0); weapons[2].ChangeLevel(3, 0); weapons[3].ChangeLevel(3, 0); weapons[4].ChangeLevel(3, 0); player1.ChangeWeapon(3, 1); player1.ChangeColour(1); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { CheckInput(2); SoundControl(); switch (gameMode) { case SPLASH: break; case MENU: TakeName(); break; case GAME: CoolWeapons(); SpawnEnemies(); Collisions(); MoveItems(); Cleanup(); break; case PAUSE: break; case GAMEOVER: break; } base.Update(gameTime); } private void ResetGame() { debug = false; enemyList.Clear(); bulletList.Clear(); lasthit = -1; spawntimerpremax = SPAWNTIMERPREMAX; player1.Reset(); spawn = true; } private void SoundControl() { { if (music) { snd_bgm_instance.Play(); } else if (!music) { snd_bgm_instance.Pause(); } } } /// <summary> /// Checks for input. /// </summary> /// <param name="mode">0 = Mouse, 1 = Keyboard, 2 = Both</param> private void CheckInput(byte mode) { mouseStatePrev = mouseState; mouseState = Mouse.GetState(); mousePosPrev = mousePos; mousePos.X = mouseState.X; mousePos.Y = mouseState.Y; keyStatePrev = keyState; keyState = Keyboard.GetState(); if (keyState.IsKeyDown(Keys.Escape) && keyStatePrev.IsKeyUp(Keys.Escape)) { this.Exit(); } if (mode == 0 || mode == 2) { if (gameMode == SPLASH) { if (mouseState.LeftButton == ButtonState.Pressed && mouseStatePrev.LeftButton == ButtonState.Released) { gameMode = MENU; } } if (gameMode == MENU) { if (mouseState.LeftButton == ButtonState.Released && mouseStatePrev.LeftButton == ButtonState.Pressed) { MenuClick(new Rectangle((int)mousePos.X - 4, (int)mousePos.Y - 4, 8, 8)); } } if (gameMode == GAME) { if (mousePos.X > -50 && mousePos.X < 690) { if (!select) { player1.Move((int)mousePos.X, 1); } } if (mouseState.LeftButton == ButtonState.Pressed && mouseStatePrev.LeftButton == ButtonState.Released) { mouseLeftPrev.X = mouseState.X; mouseLeftPrev.Y = mouseState.Y; if (player1.Fire()) { Fire(); } } if (mouseState.LeftButton == ButtonState.Pressed && mouseStatePrev.LeftButton == ButtonState.Pressed) { if (player1.Refire()) { Fire(); } if (player1.Colour == 7 || player1.Colour == 0) { player1.CurrentWeapon.InstaCool(); } } if (mouseState.RightButton == ButtonState.Pressed && mouseStatePrev.RightButton == ButtonState.Released) { mouseRightPrev = mousePos; Mouse.SetPosition((int)midpoint.X, (int)midpoint.Y); select = true; } if (mouseState.RightButton == ButtonState.Released && mouseStatePrev.RightButton == ButtonState.Pressed) { if (new Rectangle((int)mousePos.X - 4, (int)mousePos.Y - 4, 8, 8).Intersects(rectRed)) { player1.ChangeColour(1); } else if (new Rectangle((int)mousePos.X - 4, (int)mousePos.Y - 4, 8, 8).Intersects(rectGreen)) { player1.ChangeColour(2); } else if (new Rectangle((int)mousePos.X - 4, (int)mousePos.Y - 4, 8, 8).Intersects(rectBlue)) { player1.ChangeColour(3); } else if (new Rectangle((int)mousePos.X - 4, (int)mousePos.Y - 4, 8, 8).Intersects(rectCyan)) { player1.ChangeColour(4); } else if (new Rectangle((int)mousePos.X - 4, (int)mousePos.Y - 4, 8, 8).Intersects(rectMagenta)) { player1.ChangeColour(5); } else if (new Rectangle((int)mousePos.X - 4, (int)mousePos.Y - 4, 8, 8).Intersects(rectYellow)) { player1.ChangeColour(6); } else if (!debug) { if (new Rectangle((int)mousePos.X - 4, (int)mousePos.Y - 4, 8, 8).Intersects(rectClear)) { } } else if (debug) { if (new Rectangle((int)mousePos.X - 4, (int)mousePos.Y - 4, 8, 8).Intersects(rectBlack)) { player1.ChangeColour(7); } else if (new Rectangle((int)mousePos.X - 4, (int)mousePos.Y - 4, 8, 8).Intersects(rectWhite)) { player1.ChangeColour(0); } } Mouse.SetPosition((int)mouseRightPrev.X, (int)mouseRightPrev.Y); select = false; } } if (gameMode == PAUSE) { if (mouseState.LeftButton == ButtonState.Pressed && mouseStatePrev.LeftButton == ButtonState.Released) { gameMode = GAME; } } if (gameMode == GAMEOVER) { if (mouseState.LeftButton == ButtonState.Pressed && mouseStatePrev.LeftButton == ButtonState.Released) { gameMode = MENU; drawScores = false; } } if (mode == 1 || mode == 2) { if (gameMode == SPLASH) { if (keyState.IsKeyDown(Keys.Space) && keyStatePrev.IsKeyUp(Keys.Space)) { gameMode = MENU; } if (keyState.IsKeyDown(Keys.M) && keyStatePrev.IsKeyUp(Keys.M)) { music = !music; } if (keyState.IsKeyDown(Keys.N) && keyStatePrev.IsKeyUp(Keys.N)) { sfx = !sfx; } } if (gameMode == MENU) { if (!takename) { if (keyState.IsKeyDown(Keys.M) && keyStatePrev.IsKeyUp(Keys.M)) { music = !music; } if (keyState.IsKeyDown(Keys.N) && keyStatePrev.IsKeyUp(Keys.N)) { sfx = !sfx; } if (keyState.IsKeyDown(Keys.S) && keyStatePrev.IsKeyUp(Keys.S)) { SaveScores(); } if (keyState.IsKeyDown(Keys.L) && keyStatePrev.IsKeyUp(Keys.L)) { LoadScores(currentFile); } if (keyState.IsKeyDown(Keys.K) && keyStatePrev.IsKeyUp(Keys.K)) { LoadScores("Hiscoresload.txt"); } if (keyState.IsKeyDown(Keys.J) && keyStatePrev.IsKeyUp(Keys.J)) { LoadScores("Hiscoressort.txt"); } } } if (gameMode == GAME) { if (keyState.IsKeyDown(Keys.M) && keyStatePrev.IsKeyUp(Keys.M)) { music = !music; } if (keyState.IsKeyDown(Keys.N) && keyStatePrev.IsKeyUp(Keys.N)) { sfx = !sfx; } if (keyState.IsKeyDown(Keys.D1) && keyStatePrev.IsKeyUp(Keys.D1)) { player1.ChangeWeapon(3, 1); } if (keyState.IsKeyDown(Keys.D2) && keyStatePrev.IsKeyUp(Keys.D2) && debug) { player1.ChangeWeapon(3, 2); } if (keyState.IsKeyDown(Keys.D3) && keyStatePrev.IsKeyUp(Keys.D3) && debug) { player1.ChangeWeapon(3, 3); } if (keyState.IsKeyDown(Keys.D4) && keyStatePrev.IsKeyUp(Keys.D4) && debug) { player1.ChangeWeapon(3, 4); } if (keyState.IsKeyDown(Keys.D0) && keyStatePrev.IsKeyUp(Keys.D0)) { player1.ChangeWeapon(3, 0); } if (keyState.IsKeyDown(Keys.F) && keyStatePrev.IsKeyUp(Keys.F) && debug) { player1.CycleColour(); } if (keyState.IsKeyDown(Keys.E) && keyStatePrev.IsKeyUp(Keys.E) && debug) { //Cycles Weapon Levels player1.ChangeWepLevel(2, 0); } if (keyState.IsKeyDown(Keys.V) && keyStatePrev.IsKeyUp(Keys.V) && debug) { spawn = !spawn; } if (keyState.IsKeyDown(Keys.R) && keyStatePrev.IsKeyUp(Keys.R) && debug) { //Resets weapon levels for (int i = 0; i < 4; i++) { if (weapons[i].Level == -1) { weapons[i].ChangeLevel(3, 0); } } } if (keyState.IsKeyDown(Keys.T) && keyStatePrev.IsKeyUp(Keys.T) && debug) { if (sfx) { SoundEffectInstance spawn_instance = snd_spawn.CreateInstance(); spawn_instance.Volume = 0.1f; spawn_instance.Play(); } enemyList.Add(new Enemy(ui1, enemytex, 64, 8, 9999, 9999, 0)); } if (keyState.IsKeyDown(Keys.Y) && keyStatePrev.IsKeyDown(Keys.Y) && debug) { if (sfx) { SoundEffectInstance spawn_instance = snd_spawn.CreateInstance(); spawn_instance.Volume = 0.1f; spawn_instance.Play(); } enemyList.Add(new Enemy(ui1, enemytex, 64, 8, 9999, 9999, 0)); } if (keyState.IsKeyDown(Keys.U) && keyStatePrev.IsKeyDown(Keys.U) && debug) { if (sfx) { SoundEffectInstance spawn_instance = snd_spawn.CreateInstance(); spawn_instance.Volume = 0.1f; spawn_instance.Play(); } enemyList.Add(new Enemy(ui1, enemytex, 64, 8, 9999, 99999, 0)); } if (keyState.IsKeyDown(Keys.Z) && keyStatePrev.IsKeyUp(Keys.Z) && debug) { player1.Death(); } if (keyState.IsKeyDown(Keys.D) && keyState.IsKeyDown(Keys.Back)) { if (!debug) { debug = true; } } if (keyState.IsKeyDown(Keys.Back) && keyStatePrev.IsKeyUp(Keys.Back) && debug) { debug = false; } if (keyState.IsKeyDown(Keys.H) && keyStatePrev.IsKeyUp(Keys.H) && debug) { debugmsg = !debugmsg; } if (keyState.IsKeyDown(Keys.Space) && keyStatePrev.IsKeyUp(Keys.Space)) { gameMode = PAUSE; } } if (gameMode == PAUSE || gameMode == GAMEOVER) { if (keyState.IsKeyDown(Keys.Q) && keyStatePrev.IsKeyUp(Keys.Q)) { gameMode = MENU; } if (keyState.IsKeyDown(Keys.M) && keyStatePrev.IsKeyUp(Keys.M)) { music = !music; } if (keyState.IsKeyDown(Keys.N) && keyStatePrev.IsKeyUp(Keys.N)) { sfx = !sfx; } } } } } private void SpawnEnemies() { if (spawn) { if (spawntimer <= 0) { enemyList.Add(new Enemy(ui1, enemytex, 64, 8, 9999, 9999, 0)); if (sfx) { SoundEffectInstance spawn_instance = snd_spawn.CreateInstance(); spawn_instance.Volume = 0.1f; spawn_instance.Play(); } spawntimer = spawntimerpremax * 60; if (spawntimerpremax > 1) { spawntimerpremax -= 0.125f; } } spawntimer--; } } private void Fire() { switch (player1.CurrentWeapon.Number) { case 1: if (player1.CurrentWeapon.Level != -1) { switch (player1.CurrentWeapon.Level) { case 0: bulletList.Add(new Bullet(player1.CurrentWeapon.Level, player1.Colour, mousePos, player1.Pos, tex_wep_a_f, tex_wep_a_i, 0)); if (sfx) { SoundEffectInstance atatat_instance = snd_atatat.CreateInstance(); atatat_instance.Volume = 0.1f; atatat_instance.Play(); } break; case 1: bulletList.Add(new Bullet(player1.CurrentWeapon.Level, player1.Colour, mousePos, player1.Pos, tex_wep_a_f, tex_wep_a_i, 0)); bulletList.Add(new Bullet(player1.CurrentWeapon.Level, player1.Colour, mousePos, player1.Pos, tex_wep_a_f, tex_wep_a_i, 1)); if (sfx) { SoundEffectInstance atatat_instance = snd_atatat.CreateInstance(); atatat_instance.Volume = 0.1f; atatat_instance.Play(); SoundEffectInstance atatat1_instance = snd_atatat.CreateInstance(); atatat1_instance.Volume = 0.1f; atatat1_instance.Play(); } break; case 2: bulletList.Add(new Bullet(player1.CurrentWeapon.Level, player1.Colour, mousePos, player1.Pos, tex_wep_a_f1, tex_wep_a_i, 0)); bulletList.Add(new Bullet(player1.CurrentWeapon.Level, player1.Colour, mousePos, player1.Pos, tex_wep_a_f1, tex_wep_a_i, 1)); if (sfx) { SoundEffectInstance atatat_instance = snd_atatat.CreateInstance(); atatat_instance.Volume = 0.1f; atatat_instance.Play(); SoundEffectInstance atatat1_instance = snd_atatat.CreateInstance(); atatat1_instance.Volume = 0.1f; atatat1_instance.Play(); } break; } } break; case 2: if (player1.CurrentWeapon.Level != -1) { //switch (player1.CurrentWeapon.Level) //{ // case 0: // bulletList.Add(new Bullet(player1.CurrentWeapon.Level, player1.Colour, mousePos, player1.Pos, tex_wep_a_f, tex_wep_a_i, 0)); // break; // case 1: // bulletList.Add(new Bullet(player1.CurrentWeapon.Level, player1.Colour, mousePos, player1.Pos, tex_wep_a_f, tex_wep_a_i, 0)); // bulletList.Add(new Bullet(player1.CurrentWeapon.Level, player1.Colour, mousePos, player1.Pos, tex_wep_a_f, tex_wep_a_i, 1)); // break; // case 2: // bulletList.Add(new Bullet(player1.CurrentWeapon.Level, player1.Colour, mousePos, player1.Pos, tex_wep_a_f1, tex_wep_a_i, 0)); // bulletList.Add(new Bullet(player1.CurrentWeapon.Level, player1.Colour, mousePos, player1.Pos, tex_wep_a_f1, tex_wep_a_i, 1)); // break; //} } break; case 3: break; case 4: break; } } private void CoolWeapons() { try { for (int i = 0; i <= 4; i++) { weapons[i].Cool(); } } catch (IndexOutOfRangeException) { } } private void MoveItems() { foreach (Bullet b in bulletList) { b.Move(); } foreach (Enemy e in enemyList) { e.Move(); } } private void SortScores() { int pass, current; for (pass = 0; pass < 5; pass++) { int min = pass; for (current = pass + 1; current < 5; current++) { if (hiscores[current].Score > hiscores[min].Score) { min = current; } } Player temp = hiscores[pass]; hiscores[pass] = hiscores[min]; hiscores[min] = temp; } } private void UpdateScores() { for (int i = 0; i < 5; i++) { if (player1.Score > hiscores[i].Score) { Player playercopy = new Player(player1.Score, player1.Name); Player tempplayer = hiscores[i];//copy overwritten player hiscores[i] = playercopy;//insert player score if (i != 4)//if player is not last score { for (int j = 4; j >= i; j--) { if (j > i) { hiscores[j] = hiscores[j - 1]; } if (j == i) { hiscores[j] = tempplayer; } } } break; } } } private void Collisions() { //bullets and enemies foreach (Bullet b in bulletList) { foreach (Enemy e in enemyList) { if (b.GetRect().Intersects(e.GetRect())) { if (!b.Hit) { if (sfx) { SoundEffectInstance hit_instance = snd_hit.CreateInstance(); hit_instance.Volume = 0.1f; hit_instance.Play(); } b.HitObject(); e.Hit(b.Damage, b.Colour); lasthit = enemyList.IndexOf(e); } } } } ////bullets and enemy avoids //foreach (Bullet b in bulletList) //{ // foreach (Enemy e in enemyList) // { // if (b.GetRect().Intersects(e.GetAvoidLeftRect()) || b.GetRect().Intersects(e.GetAvoidRightRect())) // { // e.AvoidSide(b.Pos); // } // } //} //foreach (Bullet b in bulletList) //{ // foreach (Enemy e in enemyList) // { // if (b.GetRect().Intersects(e.GetAvoidFrontRect())) // { // e.AvoidSide(b.Pos); // e.AvoidFront(); // } // } //} //grenades and enemies //coil and enemies //depleted and enemies //enemies and enemies (colour) //enemies and player foreach (Enemy e in enemyList) { if (e.GetRect().Intersects(player1.GetRect())) { player1.Hit(e.Size, e.Colour); e.Death(); } } } private void Cleanup() { for (int b = 0; b < bulletList.Count; b++) { if (bulletList[b].Active == false) { bulletList.RemoveAt(b); } } for (int e = 0; e < enemyList.Count; e++) { enemyList[e].CheckPos(); } for (int e = 0; e < enemyList.Count; e++) { enemyList[e].CheckHealth(); } for (int e = 0; e < enemyList.Count; e++) { if (!enemyList[e].Alive) { if (sfx) { SoundEffectInstance death_instance = snd_death.CreateInstance(); death_instance.Volume = 0.1f; death_instance.Play(); } player1.ChangeScore(enemyList[e].Size, false); player1.GainXP(enemyList[e].Size); } } for (int e = 0; e < enemyList.Count; e++) { if (enemyList[e].Active == false) { enemyList.RemoveAt(e); if (lasthit == e) { lasthit = -1; } } } player1.CheckHealth(); if (!player1.Active) { if (sfx) { snd_explode_instance.Play(); } SortScores(); UpdateScores(); drawScores = true; gameMode = GAMEOVER; } } private void MenuClick(Rectangle clickRect) { if (clickRect.Intersects(menu1)) { ResetGame(); gameMode = GAME; } if (clickRect.Intersects(menu2)) { drawScores = !drawScores; drawHow = false; } if (clickRect.Intersects(menu3)) { drawHow = !drawHow; drawScores = false; } if (clickRect.Intersects(menu4)) { this.Exit(); } if (clickRect.Intersects(noticeRect) && drawScores) { takename = true; } if (!clickRect.Intersects(noticeRect) && takename) { takename = false; } } private void TakeName() { if (takename) { // the keys that were pressed before – initially an empty array // the keys that are currently pressed Keys[] pressedKeys; pressedKeys = keyState.GetPressedKeys(); // work through each key that is presently pressed for (int i = 0; i < pressedKeys.Length; i++) { // set a flag to indicate we have not found the key bool foundIt = false; // work through each key in the old keys for (int j = 0; j < oldKeys.Length; j++) { if (pressedKeys[i] == oldKeys[j]) { // we found the key in the old keys foundIt = true; } } if (foundIt == false) { // if we get here we didn't find the key in the old key // now decode the key value for use in the message string keyString = ""; // initially this is an empty string switch (pressedKeys[i]) { case Keys.D0: keyString = "0"; break; case Keys.D1: keyString = "1"; break; case Keys.D2: keyString = "2"; break; case Keys.D3: keyString = "3"; break; case Keys.D4: keyString = "4"; break; case Keys.D5: keyString = "5"; break; case Keys.D6: keyString = "6"; break; case Keys.D7: keyString = "7"; break; case Keys.D8: keyString = "8"; break; case Keys.D9: keyString = "9"; break; case Keys.A: keyString = "A"; break; case Keys.B: keyString = "B"; break; case Keys.C: keyString = "C"; break; case Keys.D: keyString = "D"; break; case Keys.E: keyString = "E"; break; case Keys.F: keyString = "F"; break; case Keys.G: keyString = "G"; break; case Keys.H: keyString = "H"; break; case Keys.I: keyString = "I"; break; case Keys.J: keyString = "J"; break; case Keys.K: keyString = "K"; break; case Keys.L: keyString = "L"; break; case Keys.M: keyString = "M"; break; case Keys.N: keyString = "N"; break; case Keys.O: keyString = "O"; break; case Keys.P: keyString = "P"; break; case Keys.Q: keyString = "Q"; break; case Keys.R: keyString = "R"; break; case Keys.S: keyString = "S"; break; case Keys.T: keyString = "T"; break; case Keys.U: keyString = "U"; break; case Keys.W: keyString = "W"; break; case Keys.V: keyString = "V"; break; case Keys.X: keyString = "X"; break; case Keys.Y: keyString = "Y"; break; case Keys.Z: keyString = "Z"; break; case Keys.Space: keyString = " "; break; case Keys.OemPeriod: keyString = "."; break; case Keys.Enter: takename = false; break; } if (pressedKeys[i] == Keys.Back) { if (newname.Length > 0) { newname = newname.Remove(newname.Length - 1); } } newname = newname + keyString; if (!takename && newname.Length > 0 && newname.Length <= 8) { player1.Name = newname; } else if (!takename && player1.Name.Length + keyString.Length <= 0) { player1.Name = "Oshino"; } } } // remember the keys for next time oldKeys = pressedKeys; } } private void SaveScores() { SortScores(); try { StreamWriter outputStream = File.CreateText(currentFile); // creates the file for (int i = 0; i <= 4; i++) { int j = i + 1; outputStream.Write("" + j +" "); outputStream.Write("" + hiscores[i].Name.ToUpper() + " "); outputStream.Write("" + hiscores[i].Score + "\n"); } outputStream.Close(); // close the file stream saved = 120; } catch (FileNotFoundException problem) { excepfnf = true; excepfnfproblem = problem; } catch (IOException anException) { excepio = true; } } private void LoadScores(string filename) { try { string line; string[] words; StreamReader inputStream = File.OpenText(filename); for (int i = 0; i <= 4; i++) { line = inputStream.ReadLine(); words = line.Split(' '); hiscores[i].Name = words[1]; hiscores[i].Score = Convert.ToInt32(words[2]); } inputStream.Close(); } catch (FileNotFoundException problem) { excepfnf = true; excepfnfproblem = problem; } catch (IOException anException) { excepio = true; } loaded = 120; } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(grm); spriteBatch.Begin(); if (gameMode == SPLASH) { spriteBatch.Draw(tex_splash, new Rectangle(0, 0, screenwidth, screenheight), Color.White); ui1.DrawHairCentre(mousePos, player1.Pos); } if (gameMode == MENU) { spriteBatch.Draw(tex_splash, new Rectangle(0, 0, screenwidth, screenheight), Color.White); spriteBatch.Draw(tex_menubuttons, menu1, new Rectangle(0, 0, 128, 32), Color.White); spriteBatch.Draw(tex_menubuttons, menu2, new Rectangle(0, 32, 128, 32), Color.White); spriteBatch.Draw(tex_menubuttons, menu3, new Rectangle(0, 64, 128, 32), Color.White); spriteBatch.Draw(tex_menubuttons, menu4, new Rectangle(0, 96, 128, 32), Color.White); ui1.DrawString(105 , 800, "BGM: \"Speaker 1, Speaker 1\" by Ronald Jenkees"); if (drawHow) { spriteBatch.Draw(tex_howto, noticeRect, Color.White); } if (drawScores) { SortScores(); spriteBatch.Draw(tex_scorebg, noticeRect, Color.White); ui1.DrawString(280, 96, "SCORES"); ui1.DrawString(200, 140, "1.\n2.\n3.\n4.\n5."); ui1.DrawString(220, 140, "" + hiscores[0].Name + "\n" + hiscores[1].Name + "\n" + hiscores[2].Name + "\n" + hiscores[3].Name + "\n" + hiscores[4].Name + ""); ui1.DrawString(400, 140, "" + hiscores[0].Score + "\n" + hiscores[1].Score + "\n" + hiscores[2].Score + "\n" + hiscores[3].Score + "\n" + hiscores[4].Score + ""); ui1.DrawString(250, 300, "Name:"); if (takename) { ui1.DrawString(250, 300, "Name:", Color.White); ui1.DrawString(300, 300, newname, Color.White); } else { ui1.DrawString(250, 300, "Name:"); ui1.DrawString(300, 300, "" + player1.Name); } } ui1.DrawHairCentre(mousePos, player1.Pos); } if (gameMode == GAME || gameMode == PAUSE) { foreach (Enemy e in enemyList) { e.Draw(spriteBatch); } foreach (Bullet b in bulletList) { b.Draw(spriteBatch); } try { if (lasthit != -1) { ui1.DrawEnemyHealth(enemyList[lasthit]); } } catch (ArgumentOutOfRangeException) { lasthit = -1; } if (select) { spriteBatch.Draw(tex_trans_red, rectRed, Color.White); spriteBatch.Draw(tex_trans_grn, rectGreen, Color.White); spriteBatch.Draw(tex_trans_blu, rectBlue, Color.White); spriteBatch.Draw(tex_trans_cyn, rectCyan, Color.White); spriteBatch.Draw(tex_trans_mgn, rectMagenta, Color.White); spriteBatch.Draw(tex_trans_ylo, rectYellow, Color.White); if (debug) { spriteBatch.Draw(tex_trans_wht, rectWhite, Color.White); spriteBatch.Draw(tex_trans_blk, rectBlack, Color.White); } } if (debug && debugmsg) { ui1.DrawString(0, 0, "Debug Enabled, Backspace to exit.\n F - Cycle Colours\n E - Level Weapons\n R - Reset Weapons\n 0,1,2,3,4 - Weapon Select\n T - Spawn Enemy\n (Y) - Spawn Enemies\n (U) - Spawn Enemies anywhere\n Z - Die\n V - Automated Spawning Toggle\n H - Hide Keys"); } if (debug && !debugmsg) { ui1.DrawString(0, 0, "Debug Enabled, Backspace to exit."); } if (gameMode == PAUSE) { if (pausetimer <= 0) { pausetimer = 120; } const int PAUSEWIDTH = 256; const int PAUSEHEIGHT = 32; spriteBatch.Draw(tex_pause_over, new Rectangle(0, 0, screenwidth, screenheight), Color.White); if (pausetimer > 60) { spriteBatch.Draw(tex_pause, new Rectangle((int)midpoint.X - PAUSEWIDTH / 2, (int)midpoint.Y - PAUSEHEIGHT / 2, PAUSEWIDTH, PAUSEHEIGHT), new Rectangle(0, 0, PAUSEWIDTH, PAUSEHEIGHT), Color.White); } else if (pausetimer > 0) { spriteBatch.Draw(tex_pause, new Rectangle((int)midpoint.X - PAUSEWIDTH / 2, (int)midpoint.Y - PAUSEHEIGHT / 2, PAUSEWIDTH, PAUSEHEIGHT), new Rectangle(0, PAUSEHEIGHT, PAUSEWIDTH, PAUSEHEIGHT), Color.White); } ui1.DrawString((int)midpoint.X - 80, (int)midpoint.Y + 20, "Click to continue"); ui1.DrawString((int)midpoint.X - 40, (int)midpoint.Y + 40, "Q to quit"); pausetimer--; } ui1.DrawHairs(mousePos, player1.Pos); player1.Draw(spriteBatch, mousePos); } if (gameMode == GAMEOVER) { if (pausetimer <= 0) { pausetimer = 120; } const int PAUSEWIDTH = 256; const int PAUSEHEIGHT = 32; spriteBatch.Draw(tex_pause_over, new Rectangle(0, 0, screenwidth, screenheight), Color.White); if (pausetimer > 60) { spriteBatch.Draw(tex_gameover, new Rectangle((int)midpoint.X - PAUSEWIDTH / 2, (int)midpoint.Y - PAUSEHEIGHT / 2, PAUSEWIDTH, PAUSEHEIGHT), new Rectangle(0, 0, PAUSEWIDTH, PAUSEHEIGHT), Color.White); } else if (pausetimer > 0) { spriteBatch.Draw(tex_gameover, new Rectangle((int)midpoint.X - PAUSEWIDTH / 2, (int)midpoint.Y - PAUSEHEIGHT / 2, PAUSEWIDTH, PAUSEHEIGHT), new Rectangle(0, PAUSEHEIGHT, PAUSEWIDTH, PAUSEHEIGHT), Color.White); } ui1.DrawString((int)midpoint.X - 60, (int)midpoint.Y + 20, "Final score: " + player1.Score); ui1.DrawString((int)midpoint.X - 40, (int)midpoint.Y + 40, "Q to quit"); ui1.DrawHairs(mousePos, player1.Pos); if (drawScores) { SortScores(); spriteBatch.Draw(tex_scorebg, noticeRect, Color.White); ui1.DrawString(280, 96, "SCORES"); ui1.DrawString(200, 140, "1.\n2.\n3.\n4.\n5."); ui1.DrawString(220, 140, "" + hiscores[0].Name + "\n" + hiscores[1].Name + "\n" + hiscores[2].Name + "\n" + hiscores[3].Name + "\n" + hiscores[4].Name + ""); ui1.DrawString(400, 140, "" + hiscores[0].Score + "\n" + hiscores[1].Score + "\n" + hiscores[2].Score + "\n" + hiscores[3].Score + "\n" + hiscores[4].Score + ""); } } if (saved > 0) { ui1.DrawMsg(midpoint,"Hiscores\n Saved", Color.Black); saved--; } if (loaded > 0) { ui1.DrawMsg(midpoint, "Hiscores\n Loaded", Color.Black); loaded--; } if (excepio) { ui1.DrawString(10, 100, "Error occured when trying to write to the file PengiSave.txt", Color.Red); } if (excepfnf) { ui1.DrawString(10, 120, "File not found: " + currentFile + " \n" + excepfnfproblem, Color.Red); } spriteBatch.End(); base.Draw(gameTime); } } }
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; using System.IO; using System.Threading.Tasks; namespace _7in14.Controllers { [Route("api/[controller]")] public class FileController { private readonly IHostingEnvironment _environment; public FileController(IHostingEnvironment environment) { _environment = environment; } // GET api/file [HttpGet] public async Task<JsonResult> Get() { var path = Directory.GetCurrentDirectory(); var readmeContent = await File.ReadAllTextAsync(Path.Combine(_environment.ContentRootPath, "../README.md")); var jObject = new JObject { { "data", readmeContent } }; return new JsonResult(jObject); } } }
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; public class EditorWindowDemo : EditorWindow { static EditorWindowDemo exampleWindow; [MenuItem("Window/EditorWindowDemo")] static void Open() { //var exampleWindow = CreateInstance<EditorWindowDemo>(); //exampleWindow.Show(); //GetWindow<EditorWindowDemo>(typeof(SceneView)); //GetWindow<EditorWindowDemo>(); if (exampleWindow == null) { exampleWindow = CreateInstance<EditorWindowDemo>(); } exampleWindow.ShowUtility(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Unity; namespace _15.RegisterTypeNamed { class Program { static void Main(string[] args) { IUnityContainer container = new UnityContainer(); container.RegisterType<IMessage, ConsoleMessage>("Console"); container.RegisterType<IMessage, FileMessage>(); IMessage message1 = container.Resolve<IMessage>(); message1.Write("Hello World"); IMessage message2 = container.Resolve<IMessage>("Console"); message2.Write("Hello World"); Console.WriteLine(); foreach (var item in container.Registrations) { Console.WriteLine($"Name : {item.Name}"); Console.WriteLine($"RegisteredType : {item.RegisteredType.Name}"); Console.WriteLine($"MappedToType : {item.MappedToType.Name}"); Console.WriteLine($"LifetimeManager : {item.LifetimeManager.LifetimeType.Name}"); Console.WriteLine(); } Console.WriteLine("Press any key for continuing..."); Console.ReadKey(); } } public interface IMessage { void Write(string message); } public class ConsoleMessage : IMessage { public void Write(string message) { Console.WriteLine($"ConsoleMessage: {message} "); } } public class FileMessage : IMessage { public void Write(string message) { Console.WriteLine($"FileMessage: {message} "); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Forms; namespace ReqRaportsApp { public partial class MainForm { private void UpdateMaxValue() { double maxPriceVal = RapGenOps.maxPrice(); MaxMaxValLabel.Text = maxPriceVal.ToString(); MinValueTextBox.Text = 0.ToString(); MaxValueTextBox.Text = maxPriceVal.ToString(); } private void AddFiles() { try { if (AddFilesDialog.ShowDialog() == DialogResult.OK) { string[] filePaths = AddFilesDialog.FileNames; foreach (string fp in filePaths) if (!AddedFiles.Keys.Contains(fp.Substring(fp.LastIndexOf("\\") + 1))) { if (fp.EndsWith(".xml")) { Serializer.DeserializeXmlObject(fp); } else if (fp.EndsWith(".json")) { Serializer.DeserializeJsonObject(fp); } else if (fp.EndsWith(".csv")) { Serializer.DeserializeCsvObject(fp); } string fileName = fp.Substring(fp.LastIndexOf("\\") + 1); if (AddedFiles.Keys.Contains(fileName)) { AddedFilesListBox.Items.Add(fileName); } foreach (request r in AddedFiles[fileName]) { string cid = r.clientId; if (!ClientIdComboBox.Items.Contains(cid)) { ClientIdComboBox.Items.Add(cid); } } } if (AddedFilesListBox.Items.Count != 0) { RaportsComboBox.Enabled = true; RaportGenBtn.Enabled = true; DeleteFilesBtn.Enabled = true; } UpdateMaxValue(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void DeleteFiles() { try { List<object> toRemove = new List<object>(); foreach (object item in AddedFilesListBox.SelectedItems) { toRemove.Add(item); } List<string> clientIdsToCheckList = new List<string>(); foreach (object item in toRemove) { AddedFilesListBox.Items.Remove(item); DataHandler.RemoveData(clientIdsToCheckList, item); } toRemove.Clear(); HashSet<string> clientIdsToCheckSet = new HashSet<string>(clientIdsToCheckList); List<string> clientIdsToRemove = DataHandler.checkClientIds(clientIdsToCheckSet); foreach (string cid in clientIdsToRemove) { ClientIdComboBox.Items.Remove(cid); } if (AddedFilesListBox.Items.Count == 0) { RaportsComboBox.SelectedItem = RaportsComboBox.Items[0]; RaportsComboBox.Enabled = false; ClientIdBox.Visible = false; ValueRangeBox.Visible = false; RaportGenBtn.Enabled = false; DeleteFilesBtn.Enabled = false; SaveRaportBtn.Enabled = false; RaportsDataGrid.ColumnCount = 0; } UpdateMaxValue(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void ShowClientIdsComboBox() { try { ClientIdBox.Visible = true; ClientIdComboBox.Visible = true; ClientIdLabel.Visible = true; HashSet<string> clientIds = DataHandler.getClientIds(); List<object> toRemove = new List<object>(); foreach (object item in ClientIdComboBox.Items) if (!clientIds.Contains(item.ToString())) { toRemove.Add(item); } foreach (object tr in toRemove) { ClientIdComboBox.Items.Remove(tr); } toRemove.Clear(); foreach (string id in clientIds) if (!ClientIdComboBox.Items.Contains(id)) { ClientIdComboBox.Items.Add(id); } if (ClientIdComboBox.SelectedItem == null & ClientIdComboBox.Items.Count != 0) { ClientIdComboBox.SelectedItem = ClientIdComboBox.Items[0]; } } catch (Exception ex) { MessageBox.Show(ex.Message); } } public void RaportTypeChanged() { try { string selectedItem = RaportsComboBox.SelectedItem.ToString(); if (RaportTypes.clientIdRaportsList.Contains(selectedItem)) { ValueRangeBox.Visible = false; ShowClientIdsComboBox(); } else if (selectedItem == RaportTypes.ReqsInValueRangeType) { ClientIdBox.Visible = false; ClientIdComboBox.Visible = false; ClientIdLabel.Visible = false; ValueRangeBox.Visible = true; try { UpdateMaxValue(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { ClientIdBox.Visible = false; ClientIdComboBox.Visible = false; ClientIdLabel.Visible = false; ValueRangeBox.Visible = false; } } catch (Exception ex) { MessageBox.Show(ex.Message); } } public void MinMaxValueValidate(bool isMin) { double maxMaxValue = Double.Parse(MaxMaxValLabel.Text); try { TextBox minMaxValueTextBox = new TextBox(); TextBox otherTextBox = new TextBox(); double defaultVal; if (isMin) { defaultVal = 0; minMaxValueTextBox = MinValueTextBox; otherTextBox = MaxValueTextBox; } else { defaultVal = maxMaxValue; minMaxValueTextBox = MaxValueTextBox; otherTextBox = MinValueTextBox; } double minMaxValue = Double.Parse(minMaxValueTextBox.Text); if (minMaxValue < 0) { minMaxValueTextBox.Text = defaultVal.ToString(); } else if (minMaxValue > maxMaxValue) { minMaxValueTextBox.Text = defaultVal.ToString(); } else if (otherTextBox.Text != "" & otherTextBox.Text != null) { double otherValue = Double.Parse(otherTextBox.Text); if (isMin & minMaxValue >= otherValue) { minMaxValueTextBox.Text = defaultVal.ToString(); } else if (!isMin & minMaxValue < otherValue) { minMaxValueTextBox.Text = defaultVal.ToString(); } } } catch { if (isMin) { MinValueTextBox.Text = 0.ToString(); } else { MaxValueTextBox.Text = maxMaxValue.ToString(); } } } private GridViewData RaportChoiceSwitch() { try { string raportType = RaportsComboBox.SelectedItem.ToString(); string[] cN = { }; List<List<object>> rW = new List<List<object>>(); GridViewData gridViewData = new GridViewData(cN, rW); if (RaportTypes.clientIdRaportsList.Contains(raportType)) { string currentClientId = ClientIdComboBox.SelectedItem.ToString(); switch (raportType) { case RaportTypes.ReqQuantForClientType: gridViewData = RapGens.ReqQuantForClient(currentClientId); break; case RaportTypes.ReqValueSumForClientType: gridViewData = RapGens.ReqValueSumForClientId(currentClientId); break; case RaportTypes.AllReqsListForClientType: gridViewData = RapGens.ReqsListForClientId(currentClientId); break; case RaportTypes.AverageReqValueForClientType: gridViewData = RapGens.AverageReqValueForClientId(currentClientId); break; case RaportTypes.ReqQuantByProdNameForClientType: gridViewData = RapGens.ReqQuantByNameForClientId(currentClientId); break; } } else { switch (raportType) { case RaportTypes.ReqQuantType: gridViewData = RapGens.ReqQuant(); break; case RaportTypes.ReqValueSumType: gridViewData = RapGens.ReqValueSum(); break; case RaportTypes.AllReqsListType: gridViewData = RapGens.AllReqsList(); break; case RaportTypes.AverageReqValueType: gridViewData = RapGens.AverageReqValue(); break; case RaportTypes.ReqQuantByProdNameType: gridViewData = RapGens.ReqQuantByName(); break; case RaportTypes.ReqsInValueRangeType: double minValue = Double.Parse(MinValueTextBox.Text); double maxValue = Double.Parse(MaxValueTextBox.Text); gridViewData = RapGens.ReqsForValueRange(minValue, maxValue); break; } } return gridViewData; } catch(Exception ex) { MessageBox.Show(ex.Message); string[] cN = { }; List<List<object>> rW = new List<List<object>>(); GridViewData gridViewData = new GridViewData(cN, rW); return gridViewData; } } private void GridViewPopulate(string[] colNames, List<List<object>> rows) { RaportsDataGrid.Rows.Clear(); RaportsDataGrid.ColumnCount = colNames.Count(); int i = 0; foreach (string cn in colNames) { RaportsDataGrid.Columns[i].Name = cn; i++; } int rowCount = 0; foreach (List<object> row in rows) { RaportsDataGrid.Rows.Add(); int cellCount = 0; foreach (object cellValue in row) { RaportsDataGrid.Rows[rowCount].Cells[cellCount].ValueType = cellValue.GetType(); RaportsDataGrid.Rows[rowCount].Cells[cellCount].Value = cellValue; cellCount++; } rowCount++; } if (RaportsDataGrid.ColumnCount != 0) { SaveRaportBtn.Enabled = true; } } private void GenerateRaport() { GridViewData gridViewData = RaportChoiceSwitch(); GridViewPopulate(gridViewData.ColNames, gridViewData.Rows); } private void SaveRaportToCsv() { string selectedItem = RaportsComboBox.SelectedItem.ToString(); string raportName = "raport_" + Regex.Replace(selectedItem, " ", "-") + "_" + DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss"); SaveRaportDialog.FileName = raportName; if (SaveRaportDialog.ShowDialog() == DialogResult.OK) { List<List<string>> RowsList = new List<List<string>>(); List<string> rowText = new List<string>(); for (int col = 0; col < RaportsDataGrid.ColumnCount; col++) { rowText.Add(RaportsDataGrid.Columns[col].Name); } RowsList.Add(rowText); for (int row = 0; row < RaportsDataGrid.RowCount; row++) { rowText = new List<string>(); for (int cell = 0; cell < RaportsDataGrid.ColumnCount; cell++) { rowText.Add(RaportsDataGrid.Rows[row].Cells[cell].Value.ToString()); } RowsList.Add(rowText); } DataHandler.ExportGridDataToFile(RowsList, SaveRaportDialog.FileName); SaveRaportDialog.FileName = string.Empty; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using System.Linq; [ExecuteInEditMode] public class ObjectPool { public GameObject tempBuilding; public GameObject rotateImage; public Material rotateImageMat; public List<GameObject> placedObjects = new List<GameObject>(); public List<GameObject> placedFloors = new List<GameObject>(); public List<GameObject> placedTiles = new List<GameObject>(); public DataWrapper<TileData> myTileData = new DataWrapper<TileData>();//wrapper with all TileData public DataWrapper<BuildingData> myMapData = new DataWrapper<BuildingData>();//wrapper with all PlacedObjects public List<Object> myBuildings = new List<Object>(); public List<Object> myTiles = new List<Object>(); //Saves public TextAsset[] myMapSaves; public TextAsset[] myBuildingSaves; public void ReloadAssets() { rotateImageMat = Resources.Load("MapMaker/Materials/PreviewRotation", typeof(Material)) as Material; myMapSaves = Resources.LoadAll<TextAsset>("MapMaker/Saves/Maps/"); myBuildingSaves = Resources.LoadAll<TextAsset>("MapMaker/Saves/Buildings/"); myTiles.Clear(); myTiles.Add(Resources.Load<GameObject>("MapMaker/Prefabs/Tiles/EmptyTile"));//1 myTiles.Add(Resources.Load<GameObject>("MapMaker/Prefabs/Tiles/FloorTile"));//2 myTiles.Add(Resources.Load<GameObject>("MapMaker/Prefabs/Tiles/WallTile"));//3 foreach (Object foundObject in Resources.LoadAll("MapMaker/Prefabs/Tiles")) { if (!myTiles.Contains(foundObject)) { myTiles.Add(foundObject as GameObject); } } myBuildings.Clear(); foreach (Object foundObject in Resources.LoadAll("MapMaker/Prefabs/Buildings")) { if (!myBuildings.Contains(foundObject)) { myBuildings.Add(foundObject as GameObject); } } } public void ReloadMap() { placedObjects.Clear(); myMapData.myData.Clear(); GameObject[] myPlacedObjects = GameObject.FindGameObjectsWithTag("Building"); foreach (GameObject foundPlacedObject in myPlacedObjects) { placedObjects.Add(foundPlacedObject); } for (int i = 0; i < placedObjects.Count; i++) { myMapData.myData.Add(new BuildingData()); for (int j = 0; j < myBuildings.Count; j++) { if(placedObjects[i].name == myBuildings[j].name) { myMapData.myData[i].ID = j; Debug.Log(myMapData.myData[i].ID); myMapData.myData[i].position = placedObjects[i].transform.position; myMapData.myData[i].rotation = placedObjects[i].transform.rotation; } } } } public void ReloadTiles() { placedTiles.Clear(); placedFloors.Clear(); myTileData = new DataWrapper<TileData>(); myTileData.myData = new List<TileData>(); myTileData.myData.Clear(); if (tempBuilding != null) { Transform[] myPlacedTiles = tempBuilding.gameObject.GetComponentsInChildren<Transform>(true);//floors - Tiles - Mesh //GameObject[] myPlacedTiles = GameObject.FindGameObjectsWithTag("Tile"); foreach (Transform foundPlacedObject in myPlacedTiles) { if (foundPlacedObject.transform.parent == tempBuilding.transform) { placedFloors.Add(foundPlacedObject.gameObject); } } Debug.Log("Floor Count: " + placedFloors.Count); foreach (Transform foundPlacedObject in myPlacedTiles) { for (int k = 0; k < placedFloors.Count; k++) { if (foundPlacedObject.transform.parent == placedFloors[k].transform) { placedTiles.Add(foundPlacedObject.gameObject); } } } for (int i = 0; i < placedTiles.Count; i++) { myTileData.myData.Add(new TileData()); for (int j = 0; j < myTiles.Count; j++) { if (placedTiles[i].name == myTiles[j].name) { myTileData.myData[i].ID = i; myTileData.myData[i].ObjectID = j; myTileData.myData[i].myObject = placedTiles[i].gameObject; myTileData.myData[i].xArrayPos = (int)placedTiles[i].transform.position.x; myTileData.myData[i].myFloorNum = (int)placedTiles[i].transform.position.y; myTileData.myData[i].zArrayPos = (int)placedTiles[i].transform.position.z; //myTileData.myData[i].gridPos = new Vector3Int((int)myTileData.myData[i].xArrayPos, myTileData.myData[i].myFloorNum, (int)myTileData.myData[i].zArrayPos); myTileData.myData[i].myRotation = placedTiles[i].transform.rotation; } } //Debug.Log(myTileData.myData[i].gridPos + " " + myTileData.myData[i].ID); } } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace FoodGallery.Models { public class EntityDB : DbContext { public EntityDB() : base ("name = DefaultConnection") { } public DbSet<Restaurent> Restaurents { get; set; } public DbSet<RestaurentReview> Reviews { get; set; } } }
using System; using System.Globalization; using Xamarin.Forms; namespace XF40Demo.Converters { internal class FactionToLogo : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return String.Empty; } string faction = ((string)value).Trim().ToLower(); switch (faction) { case "alliance": return "resource://XF40Demo.Resources.alliance.green.svg"; case "empire": return "resource://XF40Demo.Resources.empire.blue.svg"; case "federation": return "resource://XF40Demo.Resources.federation.red.svg"; case "independent": case "independant": // Uranius can't spell return "resource://XF40Demo.Resources.independent.orange.svg"; default: return String.Empty; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; namespace gView.Framework.Geometry { /// <summary> /// An orderd collection of geometry objects. /// </summary> public sealed class AggregateGeometry : IAggregateGeometry, ITopologicalOperation { private List<IGeometry> _geometries; public AggregateGeometry() { _geometries = new List<IGeometry>(); } #region IAggregateGeometry Member /// <summary> /// Adds a geometry. /// </summary> /// <param name="geometry"></param> public void AddGeometry(IGeometry geometry) { if (geometry == null) { return; } _geometries.Add(geometry); } /// <summary> /// Adds a geometry at the given position. /// </summary> /// <param name="geometry"></param> /// <param name="pos"></param> public void InsertGeometry(IGeometry geometry, int pos) { if (geometry == null) { return; } if (pos > _geometries.Count) { pos = _geometries.Count; } if (pos < 0) { pos = 0; } _geometries.Insert(pos, geometry); } /// <summary> /// Removes the geometry at the given position. /// </summary> /// <param name="pos"></param> public void RemoveGeometry(int pos) { if (pos < 0 || pos >= _geometries.Count) { return; } _geometries.RemoveAt(pos); } /// <summary> /// The number of geometry objects. /// </summary> public int GeometryCount { get { return _geometries == null ? 0 : _geometries.Count; } } /// <summary> /// Returns the geometry object at the given position. /// </summary> public IGeometry this[int geometryIndex] { get { if (geometryIndex < 0 || geometryIndex >= _geometries.Count) { return null; } return _geometries[geometryIndex]; } } public List<IPoint> PointGeometries { get { List<IPoint> points = new List<IPoint>(); foreach (IGeometry geom in _geometries) { if (geom is IPoint) { points.Add(geom as IPoint); } else if (geom is IMultiPoint) { for (int i = 0; i < ((IMultiPoint)geom).PointCount; i++) { if (((IMultiPoint)geom)[i] == null) { continue; } points.Add(((IMultiPoint)geom)[i]); } } else if (geom is IAggregateGeometry) { foreach (IPoint point in ((IAggregateGeometry)geom).PointGeometries) { points.Add(point); } } } return points; } } public IMultiPoint MergedPointGeometries { get { MultiPoint mPoint = new MultiPoint(); foreach (IPoint point in this.PointGeometries) { mPoint.AddPoint(point); } return mPoint; } } public List<IPolyline> PolylineGeometries { get { List<IPolyline> polylines = new List<IPolyline>(); foreach (IGeometry geom in _geometries) { if (geom is IPolyline) { polylines.Add(geom as IPolyline); } else if (geom is IAggregateGeometry) { foreach (IPolyline polyline in ((IAggregateGeometry)geom).PolylineGeometries) { polylines.Add(polyline); } } } return polylines; } } public IPolyline MergedPolylineGeometries { get { List<IPolyline> polylines = this.PolylineGeometries; if (polylines == null || polylines.Count == 0) { return null; } Polyline mPolyline = new Polyline(); foreach (IPolyline polyline in polylines) { for (int i = 0; i < polyline.PathCount; i++) { if (polyline[i] == null) { continue; } mPolyline.AddPath(polyline[i]); } } return mPolyline; } } public List<IPolygon> PolygonGeometries { get { List<IPolygon> polygons = new List<IPolygon>(); foreach (IGeometry geom in _geometries) { if (geom is IPolygon) { polygons.Add(geom as IPolygon); } else if (geom is IAggregateGeometry) { foreach (IPolygon polygon in ((IAggregateGeometry)geom).PolygonGeometries) { polygons.Add(polygon); } } } return polygons; } } public IPolygon MergedPolygonGeometries { get { List<IPolygon> polygons = this.PolygonGeometries; if (polygons == null || polygons.Count == 0) { return null; } return SpatialAlgorithms.Algorithm.MergePolygons(polygons); } } #endregion #region IGeometry Member /// <summary> /// The type of the geometry. /// </summary> public gView.Framework.Geometry.GeometryType GeometryType { get { return GeometryType.Aggregate; } } /// <summary> /// Creates a copy of this geometry's envelope and returns it. /// </summary> public IEnvelope Envelope { get { if (GeometryCount == 0) { return null; } IEnvelope env = this[0].Envelope; for (int i = 1; i < GeometryCount; i++) { env.Union(this[i].Envelope); } return env; } } public int VertexCount => GeometryCount == 0 ? 0 : _geometries.Sum(g => g.VertexCount); /// <summary> /// For the internal use of the framework /// </summary> /// <param name="w"></param> public void Serialize(BinaryWriter w, IGeometryDef geomDef) { w.Write(_geometries.Count); foreach (IGeometry geom in _geometries) { w.Write((System.Int32)geom.GeometryType); geom.Serialize(w, geomDef); } } /// <summary> /// For the internal use of the framework /// </summary> /// <param name="w"></param> public void Deserialize(BinaryReader r, IGeometryDef geomDef) { _geometries.Clear(); int geoms = r.ReadInt32(); for (int i = 0; i < geoms; i++) { IGeometry geom = null; switch ((GeometryType)r.ReadInt32()) { case GeometryType.Aggregate: geom = new AggregateGeometry(); break; case GeometryType.Envelope: geom = new Envelope(); break; case GeometryType.Multipoint: geom = new MultiPoint(); break; case GeometryType.Point: geom = new Point(); break; case GeometryType.Polygon: geom = new Polygon(); break; case GeometryType.Polyline: geom = new Polyline(); break; } if (geom != null) { geom.Deserialize(r, geomDef); _geometries.Add(geom); } else { break; } } } public int? Srs { get; set; } public void Clean(CleanGemetryMethods methods, double tolerance = 1e-8) { foreach(var geometry in _geometries) { geometry.Clean(methods, tolerance); } } public bool IsEmpty() => this.GeometryCount == 0; #endregion #region ICloneable Member public object Clone() { AggregateGeometry aggregate = new AggregateGeometry(); foreach (IGeometry geom in _geometries) { if (geom == null) { continue; } aggregate.AddGeometry(geom.Clone() as IGeometry); } return aggregate; } #endregion #region ITopologicalOperation Member public IPolygon Buffer(double distance) { IMultiPoint mPoint = this.MergedPointGeometries; IPolyline mPolyline = this.MergedPolylineGeometries; IPolygon mPolygon = this.MergedPolygonGeometries; List<IPolygon> polygons = new List<IPolygon>(); if (mPoint != null && mPoint.PointCount > 0) { polygons.Add(((ITopologicalOperation)mPoint).Buffer(distance)); } if (mPolyline != null && mPolyline.PathCount > 0) { polygons.Add(((ITopologicalOperation)mPolyline).Buffer(distance)); } if (mPolygon != null && mPolygon.RingCount > 0) { polygons.Add(((ITopologicalOperation)mPolygon).Buffer(distance)); } if (polygons.Count == 0) { return null; } if (polygons.Count == 1) { return polygons[0]; } return SpatialAlgorithms.Algorithm.MergePolygons(polygons); } public void Clip(IEnvelope clipper) { throw new Exception("The method or operation is not implemented."); } public void Intersect(IGeometry geometry) { throw new Exception("The method or operation is not implemented."); } public void Difference(IGeometry geometry) { throw new Exception("The method or operation is not implemented."); } public void SymDifference(IGeometry geometry) { throw new Exception("The method or operation is not implemented."); } public void Union(IGeometry geometry) { throw new Exception("The method or operation is not implemented."); } public void Clip(IEnvelope clipper, out IGeometry result) { throw new Exception("The method or operation is not implemented."); } public void Intersect(IGeometry geometry, out IGeometry result) { throw new Exception("The method or operation is not implemented."); } public void Difference(IGeometry geometry, out IGeometry result) { throw new Exception("The method or operation is not implemented."); } public void SymDifference(IGeometry geometry, out IGeometry result) { throw new Exception("The method or operation is not implemented."); } public void Union(IGeometry geometry, out IGeometry result) { throw new Exception("The method or operation is not implemented."); } #endregion public override bool Equals(object obj) { return Equals(obj, 0.0); } public bool Equals(object obj, double epsi) { if (obj is IAggregateGeometry) { IAggregateGeometry aGeometry = (IAggregateGeometry)obj; if (aGeometry.GeometryCount != this.GeometryCount) { return false; } for (int i = 0; i < this.GeometryCount; i++) { IGeometry g1 = this[i]; IGeometry g2 = aGeometry[i]; if (!g1.Equals(g2, epsi)) { return false; } } return true; } return false; } public override int GetHashCode() { return base.GetHashCode(); } #region IEnumerable<IGeometry> Members public IEnumerator<IGeometry> GetEnumerator() { return _geometries.GetEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return _geometries.GetEnumerator(); } #endregion } }
using Framework.Core.Common; using OpenQA.Selenium; using Tests.Data.Drupal; namespace Tests.Pages.FastAction { public class FastActionMyProfile : FastActionBase { public FastActionMyProfile(Driver driver) : base(driver) { } #region Page Objects public IWebElement TextBoxEmailAddress { get { return _driver.FindElement(By.CssSelector("input[name='EmailAddress']")); } } public IWebElement TextBoxFirstName { get { return _driver.FindElement(By.CssSelector("input[name='FirstName']")); } } public IWebElement TextBoxLastName { get { return _driver.FindElement(By.CssSelector("input[name='LastName']")); } } public IWebElement TextBoxAddLine1 { get { return _driver.FindElement(By.CssSelector("input[name='AddressLine1']")); } } public IWebElement TextBoxAddLine2 { get { return _driver.FindElement(By.CssSelector("input[name='AddressLine2']")); } } public IWebElement TextBoxCity { get { return _driver.FindElement(By.CssSelector("input[name='City']")); } } public IWebElement DropDownBoxState { get { return _driver.FindElement(By.CssSelector("input[name='PostalCode']")); } } public IWebElement TextBoxZip { get { return _driver.FindElement(By.CssSelector("CallDate")); } } public IWebElement TextBoxMobile { get { return _driver.FindElement(By.CssSelector("input[name='MobilePhone']")); } } public IWebElement TextBoxHome { get { return _driver.FindElement(By.CssSelector("input[name='HomePhone']")); } } public IWebElement TextBoxEmployer { get { return _driver.FindElement(By.CssSelector("input[name='Employer']")); } } public IWebElement TextBoxOccupation { get { return _driver.FindElement(By.CssSelector("input[name='Occupation']")); } } public IWebElement TextBoxCreditCard { get { return _driver.FindElement(By.CssSelector("input[name='Account']")); } } public IWebElement DropDownExpire { get { return _driver.FindElement(By.CssSelector("select[name='ExpirationMonth']")); } } public IWebElement DropDownYear { get { return _driver.FindElement(By.CssSelector("select[name='ExpirationYear']")); } } public IWebElement ButtonSaveProfile { get { return _driver.FindElement(By.CssSelector("input[value='Save Profile']")); } } public IWebElement ButtonCancel { get { return _driver.FindElement(By.CssSelector("input[value='Cancel']")); } } #endregion #region Methods public void GoTo() { Profile(); } public void UpdateProfile(FormUser formUser) { TextBoxEmailAddress.SendKeys(formUser.EmailAddress); TextBoxFirstName.SendKeys(formUser.FirstName); TextBoxLastName.SendKeys(formUser.LastName); TextBoxAddLine1.SendKeys(formUser.AddressLine1); TextBoxAddLine2.SendKeys(formUser.AddressLine2); TextBoxCity.SendKeys(formUser.City); _driver.SelectOptionByValue(DropDownBoxState, formUser.State); TextBoxZip.SendKeys(formUser.PostalCode); TextBoxMobile.SendKeys(formUser.HomePhone); TextBoxHome.SendKeys(formUser.HomePhone); TextBoxEmployer.SendKeys(formUser.Employer); TextBoxOccupation.SendKeys(formUser.Occupation); TextBoxCreditCard.SendKeys(formUser.CreditCardNumber); _driver.SelectOptionByText(DropDownYear, formUser.ExpirationYear); _driver.SelectOptionByValue(DropDownExpire, formUser.ExpirationMonth); _driver.SelectOptionByValue(DropDownBoxState, formUser.State); ButtonSaveProfile.Click(); ButtonCancel.Click(); } #endregion } }
using Terraria.Audio; using System; using System.Collections.Generic; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.DataStructures; using Terraria.ID; using Terraria.ModLoader; using Terraria.ModLoader.IO; using Terraria.GameInput; using System.Linq; using System.Runtime.Serialization; using StarlightRiver.Abilities; using StarlightRiver.Dragons; namespace StarlightRiver.Abilities { public class Ability { public int StaminaCost; public bool Active; public int Timer; public int Cooldown; public bool Locked = true; public Player player; public virtual bool CanUse { get => true; } public Ability(int staminaCost, Player Player) { StaminaCost = staminaCost; player = Player; } public virtual void StartAbility(Player player) { AbilityHandler handler = player.GetModPlayer<AbilityHandler>(); DragonHandler dragon = player.GetModPlayer<DragonHandler>(); //if the player: has enough stamina && unlocked && not on CD && Has no other abilities active if(CanUse && handler.StatStamina >= StaminaCost && !Locked && Cooldown == 0 && !handler.Abilities.Any(a => a.Active)) { handler.StatStamina -= StaminaCost; //Consume the stamina if (dragon.DragonMounted) OnCastDragon(); //Do what the ability should do when it starts else OnCast(); Active = true; //Ability is activated } } public virtual void OnCast() { } public virtual void OnCastDragon() { } public virtual void InUse() { } public virtual void InUseDragon() { } public virtual void UseEffects() { } public virtual void UseEffectsDragon() { } public virtual void OffCooldownEffects() { } public virtual void OnExit() { } } }
using System; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using TransformBlock = System.Threading.Tasks.Dataflow.TransformBlock<WorldDominationCrawler.CrawlJob, WorldDominationCrawler.CrawlJob>; using TransformManyBlock = System.Threading.Tasks.Dataflow.TransformManyBlock<WorldDominationCrawler.CrawlJob, WorldDominationCrawler.CrawlJob>; namespace WorldDominationCrawler { internal class CrawlPipeline { private const int DEFAULT_FETCH_WORKERS = 8; private const int DEFAULT_PARSE_WORKERS = 2; private const int DEFAULT_PARSE_DELAY = 200; private const int DEFAULT_MAX_DEPTH = 3; private const int DEFAULT_MAX_LINKS_PER_NODE = 10; private CrawlJob _RootJob; private CrawlStats _Stats; private ReportData _Report; public CrawlPipeline(string url) { _RootJob = new CrawlJob(url, 0); _Report = new ReportData(_RootJob); _Stats = new CrawlStats(); } public CrawlStats Stats { get { return _Stats; } } public ReportData Report { get { return _Report; } } private async Task<CrawlJob> _FetchHtmlStep(CrawlJob job) { try { job.Html = await HtmlFetcher.GetHtml(job.Url); _Stats.FetchCount += 1; } catch (Exception ex) { job.Exception = ex; _Stats.ErrorCount += 1; } return job; } private CrawlJob _ParseHtmlStep(CrawlJob job, CrawlOptions options) { try { job.PageTitle = HtmlParser.GetTitle(job.Html); job.PageHrefs = HtmlParser.GetHrefs(job.Url, job.Html); _Stats.ParseCount += 1; } catch (Exception ex) { job.Exception = ex; _Stats.ErrorCount += 1; } //delay a little bit, just to make stats interesting System.Threading.Thread.Sleep(options.ParseDelay.GetValueOrDefault(DEFAULT_PARSE_DELAY)); return job; } private CrawlJob _ReportJobStep(CrawlJob job, TransformBlock fetchBlock, TransformBlock parseBlock) { _Report.TrackJob(job); _Stats.FetchPending = fetchBlock.InputCount; _Stats.ParsePending = parseBlock.InputCount; ConsoleMonitor.PrintStatus(_Stats, job); return job; } private IEnumerable<CrawlJob> _SpanNewJobsStep(CrawlJob parentJob, TransformBlock fetchBlock, CrawlOptions options) { var newJobs = parentJob .PageHrefs .Select((href) => new CrawlJob(href, parentJob.Depth+1)) .Take(options.MaxLinksPerNode.GetValueOrDefault(DEFAULT_MAX_LINKS_PER_NODE)); if (parentJob.Depth == 0 && newJobs.Count() == 0) { fetchBlock.Complete(); } return newJobs; } private void _RequeueJobStep(CrawlJob newJob, TransformBlock fetchBlock, TransformBlock parseBlock, CrawlOptions options) { if (newJob.Depth <= options.MaxDepth.GetValueOrDefault(DEFAULT_MAX_DEPTH)) fetchBlock.Post(newJob); if (fetchBlock.InputCount == 0 && parseBlock.InputCount == 0) fetchBlock.Complete(); } public async Task<ReportData> RunAsync(CrawlOptions options) { _Stats.Reset(); _Report.Reset(); var fetchHtmlBlock = new TransformBlock((job) => _FetchHtmlStep(job), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = options.FetchWorkers.GetValueOrDefault(DEFAULT_FETCH_WORKERS) }); var parseHtmlBlock = new TransformBlock((job) => _ParseHtmlStep(job, options), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = options.ParseWorkers.GetValueOrDefault(DEFAULT_PARSE_WORKERS) }); var reportJobBlock = new TransformBlock((job) => _ReportJobStep(job, fetchHtmlBlock, parseHtmlBlock)); var spawnNewJobsBlock = new TransformManyBlock((job) => _SpanNewJobsStep(job, fetchHtmlBlock, options)); var requeueJobs = new ActionBlock<CrawlJob>((job) => _RequeueJobStep(job, fetchHtmlBlock, parseHtmlBlock, options)); fetchHtmlBlock.LinkTo(parseHtmlBlock, new DataflowLinkOptions { PropagateCompletion = true }); parseHtmlBlock.LinkTo(reportJobBlock, new DataflowLinkOptions { PropagateCompletion = true }); reportJobBlock.LinkTo(spawnNewJobsBlock, new DataflowLinkOptions { PropagateCompletion = true }); spawnNewJobsBlock.LinkTo(requeueJobs, new DataflowLinkOptions { PropagateCompletion = true }); fetchHtmlBlock.Post(_RootJob); await requeueJobs.Completion; return _Report; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.Common; using System.Reflection; namespace MVCHackathon.utilities { public class Common { private static Common _instance; public static Common Instance { get { if (_instance == null) _instance = new Common(); return _instance; } } public Common() { } public void ConvertRsObj(ref object oObject, DbDataReader reader) { Type oClassType; try { oClassType = oObject.GetType(); reader.Read(); for (int i = 0; i < reader.FieldCount; i++) { string sTableColumnName = reader.GetName(i); Type oFieldType = reader.GetFieldType(i); Type oPropertyType = null; PropertyInfo oPropertyInfo = oClassType.GetProperty(sTableColumnName); if (oPropertyInfo != null) oPropertyType = oClassType.GetProperty(sTableColumnName).PropertyType; else continue; object oFieldValue = reader[sTableColumnName]; string sFieldValue = null; if (!DBNull.Value.Equals(oFieldValue)) { sFieldValue = Convert.ToString(reader[sTableColumnName]); } object o; if (oPropertyType.Name != oFieldType.Name) o = fieldTypeInfo(oPropertyType, sFieldValue); else o = fieldTypeInfo(oFieldType, sFieldValue); try { if (o != null && oPropertyInfo.CanWrite) oPropertyInfo.SetValue(oObject, o, null); } catch (Exception exception) { string s = exception.Message; } } } catch (Exception e) { string message = "Unable to retrieve data."; string debugInformation = string.Format("Exception occured in rsToObject"); throw new DataException(message, e); } } public void ConvertRsObj(ref object oObject, DbDataReader oDDReader, object oClassName) { Type oCllctnType = null; object oClassObject = null; Type oClassType = null; try { //Get type of the collection object oCllctnType = oObject.GetType(); if (oClassName != null) { oClassType = oClassName.GetType(); } if (oDDReader.HasRows) { //Reading record one by one while (oDDReader.Read()) { //create instance of the class specified. oClassObject = (object)Activator.CreateInstance(oClassType); //Getting details of each field in a particular record. for (int i = 0; i < oDDReader.FieldCount; i++) { // Returns the name of Field string Name = oDDReader.GetName(i); //Returns the type of each Field Type oFieldType = oDDReader.GetFieldType(i); //Returns the value of Field string sValue = Convert.ToString(oDDReader[Name]); if (Name == "InsertTimeStamp") { sValue = Convert.ToString(Convert.ToDateTime(oDDReader[Name])); } //Call to the function which returns object of Actual Data Type and value of the Field Passed PropertyInfo objectPropertyInfo = oClassType.GetProperty(Name); if (objectPropertyInfo == null) { // Property of "Name" does not exist on the class ... skip and // go to next field --- Added by SV 16/07/12 continue; } Type oPropertyType = oClassType.GetProperty(Name).PropertyType; object o; if (oPropertyType.FullName != oFieldType.FullName) o = fieldTypeInfo(oPropertyType, sValue); else o = fieldTypeInfo(oFieldType, sValue); //Set the value to object if (!objectPropertyInfo.CanWrite) continue; objectPropertyInfo.SetValue(oClassObject, o, null); } object[] oArrayClassObject = new object[1]; oArrayClassObject[0] = oClassObject; //Invoke Add method of the collection class. oCllctnType.GetMethod("Add").Invoke(oObject, oArrayClassObject); } } } catch (Exception e) { string message = "Unable to retrieve data."; string debugInformation = string.Format("Exception occured in rsToCollection"); throw new DataException(message, e); } } public object fieldTypeInfo(Type sFieldType, string sFieldValue) { object type = null; switch (sFieldType.Name) { case "String": { string lFieldValue = sFieldValue; type = Convert.ChangeType(lFieldValue, sFieldType); break; } case "Int16": { short lFieldValue = 0; if (sFieldValue != string.Empty) lFieldValue = Convert.ToInt16(sFieldValue); //sType = short ; type = Convert.ChangeType(lFieldValue, sFieldType); break; } case "Int32": { int lFieldValue = 0; if (sFieldValue != string.Empty) lFieldValue = Convert.ToInt32(sFieldValue); type = Convert.ChangeType(lFieldValue, sFieldType); break; } case "Int64": { long lFieldValue = 0L; if (sFieldValue != string.Empty) lFieldValue = Convert.ToInt64(sFieldValue); type = Convert.ChangeType(lFieldValue, sFieldType); break; } case "Double": { double lFieldValue = 0.0; if (sFieldValue != string.Empty) lFieldValue = Convert.ToDouble(sFieldValue); type = Convert.ChangeType(lFieldValue, sFieldType); break; } case "Single": { float lFieldValue = 0.0F; if (sFieldValue != string.Empty) lFieldValue = Convert.ToSingle(sFieldValue); type = Convert.ChangeType(lFieldValue, sFieldType); break; } case "Decimal": { decimal lFieldValue = 0.0M; if (sFieldValue != string.Empty) lFieldValue = Convert.ToDecimal(sFieldValue); type = Convert.ChangeType(lFieldValue, sFieldType); break; } case "DateTime": { DateTime lFieldValue; if (!string.IsNullOrEmpty(sFieldValue)) { lFieldValue = Convert.ToDateTime(sFieldValue); string sDate = String.Format("{0:s}", lFieldValue); //type = new object(); type = Convert.ChangeType(sDate, sFieldType); } break; } case "Boolean": { bool lFieldValue = false; if (!string.IsNullOrEmpty(sFieldValue)) lFieldValue = Convert.ToBoolean(Convert.ToInt32(sFieldValue)); type = Convert.ChangeType(lFieldValue, sFieldType); } break; case "Nullable`1": { if (sFieldValue != null) { Type nullableType = Nullable.GetUnderlyingType(sFieldType); type = fieldTypeInfo(nullableType, sFieldValue); } else type = null; } break; default: { if (sFieldType.BaseType.Name == "Enum") { // This logic handles conversion of an integer value in the // user defined Enum Type type = System.Activator.CreateInstance(sFieldType); int lFieldValue = 0; if (sFieldValue != string.Empty) lFieldValue = Convert.ToInt32(sFieldValue); type = lFieldValue; } else type = null; break; } } return type; } public DbDataReader CloseReader(DbDataReader reader) { if (reader != null) { if (!reader.IsClosed) reader.Close(); reader.Dispose(); } reader = null; return reader; } } }
namespace Aria.Core.Interfaces { public interface IUpdatable { /// <summary> /// Call to provide logic update code when window ticks. /// </summary> /// <param name="elapsed"></param> void Update(double elapsed); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GlobalBoolsDB : MonoBehaviour { public List<bool> globalBools = new List<bool>(); #region Singleton public static GlobalBoolsDB instance; //call instance to get the single active GlobalBoolsDB for the game private void Awake() { if (instance != null) { //Debug.LogWarning("More than one instance of GlobalBoolsDB found!"); return; } instance = this; } #endregion }
namespace UnityAtoms.BaseAtoms { /// <summary> /// Action of type `AtomBaseVariable`. Inherits from `AtomAction&lt;AtomBaseVariable&gt;`. /// </summary> [EditorIcon("atom-icon-purple")] public abstract class AtomBaseVariableAction : AtomAction<AtomBaseVariable> { } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using gMediaTools.Extensions; using gMediaTools.Models; namespace gMediaTools.Services.TimeCodes { public enum TimeCodesFileVersion { Unknown, Version1, Version2 } public class TimeCodesParserService { public List<VideoFrameInfo> ParseTimeCodes(string timeCodesFilename, bool writeDump = false) { // Create the Video Frame List to return List<VideoFrameInfo> videoFrameList = new List<VideoFrameInfo>(); try { // Open timecodes file using (StreamReader reader = new StreamReader(timeCodesFilename, Encoding.UTF8)) { string currentLine; string previousLine = ""; TimeCodesFileVersion timeCodesVersion = TimeCodesFileVersion.Unknown; // Read timecodes file while ((currentLine = reader.ReadLine()) != null) { // Get currentLine to lowercase string currentLineLower = currentLine.ToLower(); // Check for comment lines if (currentLine.StartsWith("#")) { if (currentLineLower.Contains("v1")) { timeCodesVersion = TimeCodesFileVersion.Version1; } else if (currentLineLower.Contains("v2")) { timeCodesVersion = TimeCodesFileVersion.Version2; } } // Check for assume line else if (currentLineLower.Contains("assume")) { currentLine = currentLineLower.Replace("assume", "").RemoveSpaces(); } else { // Check for empty line if (string.IsNullOrWhiteSpace(currentLine)) { // Do nothing continue; } switch (timeCodesVersion) { case TimeCodesFileVersion.Unknown: throw new Exception("Could not recognize TimeCodes file version!"); case TimeCodesFileVersion.Version1: AnalyseV1(currentLine, videoFrameList); break; case TimeCodesFileVersion.Version2: // First Frame if (string.IsNullOrWhiteSpace(previousLine)) { // Set current line as previous previousLine = currentLine; // Read the next line and set it as current currentLine = reader.ReadLine(); videoFrameList.Add(AnalyseV2(previousLine, currentLine, 0)); // Set the next line as previous for the next iteration previousLine = currentLine; } // Other Frames else { videoFrameList.Add(AnalyseV2(previousLine, currentLine, videoFrameList.Count)); previousLine = currentLine; } break; default: break; } } } // Calculate last frame's FrameInfo data if v2 timecodes if (timeCodesVersion == TimeCodesFileVersion.Version2) { videoFrameList.Add( new VideoFrameInfo { Number = videoFrameList.Count, StartTime = previousLine.ParseDecimal(), Duration = videoFrameList[videoFrameList.Count - 1].Duration } ); } } } catch (Exception ex) { throw new Exception("Error in reading timecodes file!", ex); } // Check timecode dump if (writeDump) { try { StringBuilder dumpBuilder = new StringBuilder(); for (int i = 0; i < videoFrameList.Count; i++) { dumpBuilder.AppendLine($"Frame_Number:{videoFrameList[i].Number} Frame_Fps:{videoFrameList[i].FrameRate.ToString(CultureInfo.InvariantCulture)} Frame_Duration:{videoFrameList[i].Duration.ToString(CultureInfo.InvariantCulture)}"); } // Write Timecode Dump file using (StreamWriter writer = new StreamWriter($"{timeCodesFilename}.dmp".GetNewFileName(), false, Encoding.UTF8)) { writer.Write(dumpBuilder.ToString()); } } catch (Exception ex) { throw new Exception("Error writing timecode file dump!", ex); } } return videoFrameList; } private void AnalyseV1(string frameLine, List<VideoFrameInfo> videoFrameList) { // Get elements // elements[0] first frame // elememts[1] last frame // elements[2] framerate string[] elements = frameLine.Split(new string[] { "," }, StringSplitOptions.None); // Check for valid elements if (elements.Length == 3) { // Calculate FrameInfo data if (!int.TryParse(elements[0], out int start)) { throw new Exception("Could not parse V1 timecodes!"); } if (!int.TryParse(elements[1], out int end)) { throw new Exception("Could not parse V1 timecodes!"); } for (int i = start; i <= end; i++) { VideoFrameInfo tmp = new VideoFrameInfo { Number = i, FrameRate = elements[2].ParseDecimal() }; if (i == 0) { tmp.StartTime = 0.0m; } else { tmp.StartTime = videoFrameList[i - 1].Duration + videoFrameList[i - 1].StartTime; } // Add FrameInfo to FrameList videoFrameList.Add(tmp); } } else { throw new Exception("Invalid format v1 timecodes!"); } } private VideoFrameInfo AnalyseV2(string frameLine, string nextFrameLine, int frameNumber) { // Calculate VideoFrame data return new VideoFrameInfo() { Number = frameNumber, StartTime = frameLine.ParseDecimal(), Duration = nextFrameLine.ParseDecimal() - frameLine.ParseDecimal() }; } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; using UnityEngine.Networking; class Client{ int conID { get; set; } string ID { get; set; } string userID { get; set; } string password { get; set; } } class MessageBaseLoginServer : MessageBase { public string networkmsg = ""; } public class LoginServerMsgTypes { public static short PLAYER_REQUEST_INFO = 1001; public static short SERVER_RESPONSE_INFO = 1002; public static short PLAYER_REQUEST_MM = 1003; public static short SERVER_RESPONE_MM = 1004; public static short INSTANCE_REQUEST_PORT = 1007; public static short SERVER_RESPONE_PORT = 1008; public static short CLIENT_KEEPALIVE = 1010; public static short SERVER_BROADCAST = 1011; }; public class LoginServer : MonoBehaviour { private string rcvmsg = ""; public string globalmsg = "TEST"; public static DataBaseManager DBManager; public GameObject MatchMakingManager; Matchmakingmanager MMManager; // Use this for initialization void Awake(){ DBManager = gameObject.AddComponent<DataBaseManager>() as DataBaseManager; MMManager = MatchMakingManager.GetComponent<Matchmakingmanager> (); } void Start () { StartServer (); } // Update is called once per frame void Update () { if (NetworkServer.active == true) { NetworkServer.RegisterHandler (MsgType.Connect, OnConnected); NetworkServer.RegisterHandler (LoginServerMsgTypes.PLAYER_REQUEST_INFO, ReadNetworkMessage); NetworkServer.RegisterHandler (LoginServerMsgTypes.PLAYER_REQUEST_MM, ReadNetworkMessage); NetworkServer.RegisterHandler (MsgType.Disconnect, OnDisConnected); } } void StartServer() { int ServerPorts = 49001; NetworkServer.Listen (ServerPorts); } void OnConnected(NetworkMessage netMsg) { Debug.Log ("Client connected : ConID = " + netMsg.conn.connectionId + " : " + NetworkServer.connections); globalmsg = "Client connected : ConID = " + netMsg.conn.connectionId + " : " + NetworkServer.connections; } void OnDisConnected(NetworkMessage netMsg) { DBManager.DelDisconnectPlayer (netMsg.conn.connectionId); MMManager.PlayerCancelFinding (netMsg.conn.connectionId); Debug.Log ("Client Disconnected : ConID = " + netMsg.conn.connectionId); globalmsg = "Client Disconnected : ConID = " + netMsg.conn.connectionId; } void ResponseInfo(int cID, string info){ var messageb = new MessageBaseLoginServer (); messageb.networkmsg = info; NetworkServer.SendToClient (cID,LoginServerMsgTypes.SERVER_RESPONSE_INFO,messageb); globalmsg = "Send to Client : "+cID + info; Debug.Log (globalmsg); } void BroadcastInfo(string info){ var messageb = new MessageBaseLoginServer (); messageb.networkmsg = info; NetworkServer.SendToAll (LoginServerMsgTypes.SERVER_BROADCAST,messageb); } public void ReadNetworkMessage (NetworkMessage netmsg){ MessageBaseLoginServer messageb = netmsg.ReadMessage<MessageBaseLoginServer>(); rcvmsg = messageb.networkmsg.ToString (); globalmsg = messageb.networkmsg.ToString (); Debug.Log ("Recieved Network Message :" + rcvmsg); if (rcvmsg.StartsWith ("@REQUEST_LOGIN")) { RequestLogin (netmsg.conn.connectionId,rcvmsg); } if(rcvmsg.StartsWith("@REQUEST_MM")){ rcvmsg = rcvmsg.Substring (rcvmsg.IndexOf ("#")); rcvmsg = rcvmsg.Substring (1); MMManager.MakeMatchFinderList (netmsg.conn.connectionId,rcvmsg); } } void RequestLogin(int conID ,string rcvmsg) { int ID; string user; string pass; string[] sp; string PlayerResponeInfo; string PlayerResponeHero; string PlayerResponeHeroItem; rcvmsg = rcvmsg.Substring (rcvmsg.IndexOf ("#")); Debug.Log ("After Substring : "+ rcvmsg); sp = rcvmsg.Split ('#'); List<string> userpass = new List<string> (sp.Length); userpass.AddRange (sp); user = userpass [1]; pass = userpass [2]; Debug.Log (user +" "+pass); ID = DBManager.CheckUserPass (user, pass); if (ID != 0) { PlayerResponeInfo = DBManager.GetPlayerInfo (ID,conID); PlayerResponeHero = DBManager.GetHeroInfo (ID); PlayerResponeHeroItem = DBManager.GetItemHeroInfo (ID); ResponseInfo (conID, PlayerResponeInfo); ResponseInfo (conID, PlayerResponeHero); ResponseInfo (conID, PlayerResponeHeroItem); } else ResponseInfo (conID,"@UnsuccesslLogin"); } void UpdateSyncPlayerInfo() { } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CustomListClass { public class CustomListClass<T> : IEnumerable<T> { //member variables T[] array; private int count; int capacity; public CustomListClass() { capacity = 5; count = 0; array = new T[capacity]; } public IEnumerator<T> GetEnumerator() { foreach (T item in array) { if (item == null) { break; } yield return item; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } //indexer public T this[int i] { get { return array[i]; } set { array[i] = value; } } //add method public void Add(T value) { if (count < capacity) { array[count] = value; } else { capacity = capacity * 2; T[] capacityArray; capacityArray = new T[capacity]; for (int i = 0; i < count; i++) { capacityArray[i] = array[i]; } capacityArray[count] = value; array = capacityArray; } count++; } //count method public int Count { get { return count; } } //remove method public bool Remove(T value) { T[] removeArray = new T[capacity]; bool setTempArray = false; for (int j = 0; j < count; j++) { if (value.ToString() == array[j].ToString()) { for (int k = 0; k < count; k++) { if (value.ToString() != array[k].ToString()) { removeArray[k] = array[k]; setTempArray = true; } else { for (int l = 0; l < count; l++) { removeArray[k] = array[k + 1]; if (k < count - 2) { k++; } } array = removeArray; count--; return setTempArray; } } } } return setTempArray; } public override string ToString() { string stringArray; stringArray = ""; for (int m = 0; m < count; m++) { stringArray += array[m].ToString(); } return stringArray; } public static CustomListClass<T> operator +(CustomListClass<T> list1, CustomListClass<T> list2) { CustomListClass<T> combined = new CustomListClass<T>(); for (int n = 0; n < list1.count; n++) { combined.Add(list1[n]); } for (int o = 0; o < list2.count; o++) { combined.Add(list2[o]); } return combined; } public static CustomListClass<T> operator -(CustomListClass<T> list1, CustomListClass<T> list2) { CustomListClass<T> removed = new CustomListClass<T>(); for (int n = 0; n < list1.count; n++) { removed.Add(list1[n]); } for (int o = 0; o < list2.count; o++) { removed.Remove(list2[o]); } return removed; } public void ZipList(CustomListClass<int> myList1, CustomListClass<int> myList2, CustomListClass<int> zippedList) { int takeAway = 1; for (int p = 0; p < zippedList.count; p++) { if (p < 1) { zippedList[0] = myList1[0]; } else if (p % 2 != 0) { zippedList[p] = myList2[p-takeAway]; } else if (p % 2 == 0) { zippedList[p] = myList1[p-takeAway]; takeAway++; } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.ImageEffects; public class ColorCorrectionUpdate : MonoBehaviour { private ColorCorrectionCurves m_curves; private void Awake() { m_curves = GetComponent<ColorCorrectionCurves>(); } private void Update() { Debug.Log("Always Updating"); m_curves.UpdateParameters(); } }
using System; using System.Linq; using System.Reflection; using Autofac; using CommonInterface; using Microsoft.Extensions.DependencyInjection; using SAAS.InfrastructureCore; using SAAS.InfrastructureCore.Autofac; namespace Demo.Service { /// <summary> /// 实现依赖注入接口(autofac) /// </summary> public class DependencyAutofacRegistrar : IDependencyAutofacRegistrar { public void Register(ContainerBuilder builder, ITypeFinder typeFinder) { var allType = Assembly.GetExecutingAssembly();//获取当前运行的程序集 builder.RegisterAssemblyTypes(allType) .Where(a => a.IsClass && a.GetInterfaces().Contains(typeof(AutoInject))) .AsImplementedInterfaces().InstancePerLifetimeScope(); //builder.RegisterType<DemoService>().As<IDemoService>().SingleInstance(); } } }
namespace LimitedMemory { using System.Collections.Generic; using System.Collections; public class LimitedMemoryCollection<K, V> : ILimitedMemoryCollection<K, V> { private readonly LinkedList<Pair<K, V>> pairNodes; private readonly Dictionary<K, LinkedListNode<Pair<K, V>>> nodeByKey; public LimitedMemoryCollection(int capacity) { this.Capacity = capacity; this.pairNodes = new LinkedList<Pair<K, V>>(); this.nodeByKey = new Dictionary<K, LinkedListNode<Pair<K, V>>>(); } public IEnumerator<Pair<K, V>> GetEnumerator() { return this.pairNodes.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public int Capacity { get; } public int Count { get; private set; } public void Set(K key, V value) { if (this.Count == this.Capacity) { if (this.nodeByKey.ContainsKey(key)) { var node = this.nodeByKey[key]; this.pairNodes.Remove(node); this.nodeByKey.Remove(key); node.Value.Value = value; this.nodeByKey.Add(key, node); this.pairNodes.AddFirst(node); } else { var last = this.pairNodes.Last; this.pairNodes.RemoveLast(); this.nodeByKey.Remove(last.Value.Key); var newPair = new Pair<K, V>(key, value); var newNodePair = this.pairNodes.AddFirst(newPair); this.nodeByKey.Add(key, newNodePair); } } else { if (this.nodeByKey.ContainsKey(key)) { var existingNode = this.nodeByKey[key]; this.pairNodes.Remove(existingNode); this.nodeByKey.Remove(existingNode.Value.Key); existingNode.Value.Value = value; var newLinkedNode = this.pairNodes.AddFirst(existingNode.Value); this.nodeByKey.Add(key, newLinkedNode); } else { var pair = new Pair<K, V>(key, value); var nodePair = this.pairNodes.AddFirst(pair); this.nodeByKey.Add(key, nodePair); this.Count++; } } } public V Get(K key) { if (!this.nodeByKey.ContainsKey(key)) { throw new KeyNotFoundException(); } var requestedNode = this.nodeByKey[key]; this.nodeByKey.Remove(requestedNode.Value.Key); this.pairNodes.Remove(requestedNode); var newPositionedNode = this.pairNodes.AddFirst(requestedNode.Value); this.nodeByKey.Add(requestedNode.Value.Key, newPositionedNode); return this.nodeByKey[key].Value.Value; } } }
namespace SciVacancies.WebApp.ViewModels { public class ResearchDirectionAggregationViewModel { public int Id { get; set; } public decimal AverageSalary { get; set; } public long Count { get; set; } } }
using System; using System.Collections.Generic; class CurrencyConvert { static void Main() { double amount = double.Parse(Console.ReadLine()); string inputCurrency = Console.ReadLine(); string outputCurrency = Console.ReadLine(); Dictionary<string, double> currency = new Dictionary<string, double>() { { "BGN", 1}, { "USD",1.79549 }, { "EUR",1.95583},{ "GBP",2.53405} }; double result = amount * currency[inputCurrency] / currency[outputCurrency]; Console.WriteLine(Math.Round(result, 2) + " " + outputCurrency); } }
using System; namespace Grandma { public class State { public Action OnEnter; public Action OnExit; public virtual State TransitionTo() { return null; } public virtual void Enter() { OnEnter?.Invoke(); } public virtual void Exit() { OnExit?.Invoke(); } public virtual void Update() { } } }
using System.Collections.Generic; using System.Threading.Tasks; using FamilyAccounting.Api.Controllers; using FamilyAccounting.BL.DTO; using FamilyAccounting.BL.Interfaces; using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; namespace FamilyAccounting.Tests.ControllerTests { public class AuditsControllerTests { [Test] public void AuditsController_CreateAnObject() { //Arrange string expected = "AuditsController"; var mock = new Mock<IAuditService>(); //Act AuditsController controller = new AuditsController(mock.Object); //Assert Assert.IsNotNull(controller); Assert.AreEqual(expected, controller.GetType().Name); } [Test] public void GetPersonsAsync_IsNotNull() { //Arrange var mock = new Mock<IAuditService>(); mock.Setup(a => a.GetPersonsAsync()); Mock<AuditsController> controller = new Mock<AuditsController>(mock.Object); //Act var result = controller.Object.GetActions(); //Assert Assert.IsNotNull(result); } [Test] public void GetPersonsAsync_VerifyOnce() { //Arrange var mock = new Mock<IAuditService>(); AuditsController controller = new AuditsController(mock.Object); //Act var result = controller.GetPersons(); //Assert mock.Verify(a => a.GetPersonsAsync(), Times.Once); } [Test] public void GetActionsAsync_IsNotNull() { //Arrange var mock = new Mock<IAuditService>(); mock.Setup(a => a.GetActionsAsync()); Mock<AuditsController> controller = new Mock<AuditsController>(mock.Object); //Act var result = controller.Object.GetActions(); //Assert Assert.IsNotNull(result); } [Test] public void GetActionsAsync_VerifyOnce() { //Arrange var mock = new Mock<IAuditService>(); AuditsController controller = new AuditsController(mock.Object); //Act var result = controller.GetActions(); //Assert mock.Verify(a => a.GetActionsAsync(), Times.Once); } [Test] public void GetWalletsAsync_IsNotNull() { //Arrange var mock = new Mock<IAuditService>(); mock.Setup(a => a.GetWalletsAsync()); Mock<AuditsController> controller = new Mock<AuditsController>(mock.Object); //Act var result = controller.Object.GetWallets(); //Assert Assert.IsNotNull(result); } [Test] public void GetWalletsAsync_VerifyOnce() { //Arrange var mock = new Mock<IAuditService>(); AuditsController controller = new AuditsController(mock.Object); //Act var result = controller.GetWallets(); //Assert mock.Verify(a => a.GetWalletsAsync(), Times.Once); } } }
using Compent.CommandBus; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Uintra.Core.Member.Commands; using Uintra.Core.Member.Models; using Uintra.Core.User; using Uintra.Infrastructure.Extensions; namespace Uintra.Core.Member.Services { public class MentionService : IMentionService { private readonly ICommandPublisher _commandPublisher; private const string MentionDetectionRegex = "(?<=\\bdata-id=\")[^\"]*"; public MentionService(ICommandPublisher commandPublisher) { _commandPublisher = commandPublisher; } public IEnumerable<Guid> GetMentions(string text) { var matches = Regex.Matches(text, MentionDetectionRegex) .Cast<Match>() .Select(x => x.Value); return matches .Select(m => { Guid.TryParse(m, out var guid); return guid; }) .Where(g => g != default(Guid)); } public void ProcessMention(MentionModel model) { var command = model.Map<MentionCommand>(); _commandPublisher.Publish(command); } } }
using NGeoNames.Entities; namespace NGeoNames.Composers { /// <summary> /// Provides methods for composing a string representing an <see cref="ISOLanguageCode"/>. /// </summary> public class ISOLanguageCodeComposer : BaseComposer<ISOLanguageCode> { /// <summary> /// Composes the specified <see cref="ISOLanguageCode"/> into a string. /// </summary> /// <param name="value">The <see cref="ISOLanguageCode"/> to be composed into a string.</param> /// <returns>A string representing the specified <see cref="ISOLanguageCode"/>.</returns> public override string Compose(ISOLanguageCode value) { return string.Join(this.FieldSeparator.ToString(), value.ISO_639_3, value.ISO_639_2, value.ISO_639_1, value.LanguageName); } } }
using BO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace DAL { public class CompetitorRepository : ADORepository<Competitor> { protected override Competitor Construct(SqlDataReader rd) { return new Competitor { Id = (int)rd["Id"], Nom = (string)rd["Nom"], Prenom = (string)rd["Prenom"], DateNaissance = DateTime.Parse(rd["DateNaissance"].ToString()), Email = (string)rd["Email"] }; } protected override string GetUpdateSql(Competitor element) { return $"UPDATE COMPETITOR SET Nom ='{element.Nom}', Prenom ='{element.Prenom}', DateNaissance ='{element.DateNaissance}', Email ='{element.Email}' " + $"WHERE Id = {element.Id}"; } protected override string GetValues(Competitor element) { return $"'{element.Id}','{element.Nom}','{element.Prenom}','{element.DateNaissance}','{element.Email}'"; } } }
using ConsoleApplication1; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MarioKart { public class SkyFusion : Kart, IEquipamentos { public SkyFusion(Corredor corredor): base(corredor) { } public int Bonus { get { int totalBonus = Equipamentos.Count*2 + CorredorKart.GetBonusHabilidade()*2; BonusTipoKart = totalBonus; totalBonus = (Velocidade > 12) ? (int)this.Velocidade + 5 : totalBonus; return totalBonus; } } } }
using gView.Interoperability.GeoServices.Rest.Json; namespace gView.Interoperability.GeoServices.Extensions { static internal class ImageFormatExtensions { static public GraphicsEngine.ImageFormat ToGraphicsEngineImageFormat(this ImageFormat imageFormat) { switch (imageFormat) { case ImageFormat.png: case ImageFormat.png24: case ImageFormat.png32: return GraphicsEngine.ImageFormat.Png; case ImageFormat.jpg: return GraphicsEngine.ImageFormat.Jpeg; case ImageFormat.webp: return GraphicsEngine.ImageFormat.Webp; case ImageFormat.bmp: return GraphicsEngine.ImageFormat.Bmp; case ImageFormat.gif: return GraphicsEngine.ImageFormat.Gif; case ImageFormat.astc: return GraphicsEngine.ImageFormat.Astc; case ImageFormat.dng: return GraphicsEngine.ImageFormat.Dng; case ImageFormat.heif: return GraphicsEngine.ImageFormat.Heif; case ImageFormat.ico: return GraphicsEngine.ImageFormat.Ico; case ImageFormat.ktx: return GraphicsEngine.ImageFormat.Ktx; case ImageFormat.pkm: return GraphicsEngine.ImageFormat.Pkm; case ImageFormat.wbmp: return GraphicsEngine.ImageFormat.Wbmp; default: throw new System.Exception($"Unknown GraphicsEngine ImageFormat {imageFormat}"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EasyDev.Taobao { public static class Constants { public static readonly string ERROR_XML = @"<error_response> <args list=""true""><arg><key>post</key><value>{2}</value></arg></args> <code>{0}</code> <msg>{1}</msg> <sub_code></sub_code> <sub_msg></sub_msg> </error_response>"; public static readonly string REST_URL = "REST_URL"; public static readonly string APPKEY = "APPKEY"; public static readonly string APPSECRET = "APPSECRET"; } }
using System.Data; using System.Windows.Controls; namespace MMDB.Utils { public static class TableToFromDb { #region Constants private const string CONNETION_S = ""; #endregion #region Public static methods public static DataTable GetDataFromDb(DataGrid dataGrid, string tableName) { var dataTable = new DataTable(tableName); dataGrid.DataContext = dataTable.DefaultView; return dataTable; } public static void SaveDataToDb(DataTable dataTable, string tableName) { } #endregion } }
namespace Dixin.IO { using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using Dixin.Common; internal static class Video { private const string Separator = "."; internal static void RenameAllAlbums(string root, bool otherLettersFirst = false) { bool hasError = false; Directory.EnumerateDirectories(root).Where(IsNotFormated).ForEach(album => { Trace.WriteLine(album); hasError = true; }); if (hasError) { throw new OperationCanceledException(); } Directory.EnumerateDirectories(root).ForEach(album => { string[] names = Path.GetFileName(album).Split(Separator.ToCharArray()); if ((otherLettersFirst && names.Last().HasOtherLetter()) || (!otherLettersFirst && names.First().HasOtherLetter())) { new DirectoryInfo(album).Rename(string.Join(Separator, names.Last(), names[1], names.First())); } }); } internal static void FixAlbums(string source, string target) { Directory.EnumerateDirectories(target).ForEach(targetAlbum => { string name = Path.GetFileName(targetAlbum).Split(Separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Last(); string[] sources = Directory.EnumerateDirectories(source) .Where(sourceAlbum => name.EqualsOrdinal(Path.GetFileName(sourceAlbum).Split(Separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).First())) .ToArray(); if (sources.Length == 1) { try { new DirectoryInfo(targetAlbum).Rename(Path.GetFileName(sources.Single())); } catch (Exception exception) when(exception.IsNotCritical()) { } } }); } private static bool IsNotFormated(string album) { string[] names = Path.GetFileName(album).Split(Separator.ToCharArray()); int result; return names.Length != 3 || names[1].Length != 4 || !int.TryParse(names[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out result) || string.IsNullOrWhiteSpace(names.First()) || string.IsNullOrWhiteSpace(names.Last()) || (names.First().HasOtherLetter() && names.Last().HasOtherLetter()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _01.AskMyName { class AskName { static void Main() { Console.WriteLine("Please enter your name: "); string userName = Console.ReadLine(); SayHello(userName); } private static string SayHello(string userName) { Console.WriteLine("Hello, {0}!", userName); return userName; } } }
using System; using System.Text; using System.IO; using System.Collections.Generic; namespace Sudoku { class SudokuGrid { public const int SudokuDimension = 9; private const int SudokuGroupDimension = 3; public const int EmptyCellValue = 0; private static readonly Random randGenerator = new Random(); private readonly int[,] numbers; private readonly bool[,] editableFlags; public readonly Difficulty GameDifficulty; private int emptyCellsCount; public void SaveGame() { using (StreamWriter save = new StreamWriter("SavedGame.txt", false)) { for (int group = 0; group < SudokuGroupDimension; group++) { for (int row = group * SudokuGroupDimension; row < SudokuGroupDimension * (group + 1); row++) { save.WriteLine("{0} {1} {2} {3} {4} {5} {6} {7} {8}", numbers[row, 0], numbers[row, 1], numbers[row, 2], numbers[row, 3], numbers[row, 4], numbers[row, 5], numbers[row, 6], numbers[row, 7], numbers[row, 8]); } } } } public void LoadGame() { string text = ""; int[,] loadedGame = new int[9, 9]; using (StreamReader read = new StreamReader("SavedGame.txt")) text = read.ReadToEnd(); string[] splitedText = text.Split('\n'); for (int row = 0; row < 9; row++) { string[] values = splitedText[row].Split(' '); for (int col = 0; col < 9; col++) { loadedGame[row, col] = int.Parse(values[col]); } } } public int EmptyCells { get { return emptyCellsCount; } set { emptyCellsCount = value; } } public SudokuGrid() { numbers = new int[9, 9]; editableFlags = new bool[9, 9]; } public SudokuGrid(int[,] numbers,Difficulty gameDifficulty, bool isEditable) { GameDifficulty = gameDifficulty; this.numbers = new int[numbers.GetLength(0), numbers.GetLength(1)]; Array.Copy(numbers, this.numbers, numbers.Length); if (isEditable) { editableFlags = new bool[9, 9]; MakeEditable(); } else { editableFlags = new bool[9, 9]; } } //Indexer for the grid's elements public int this[int row, int col] { get { return numbers[row, col]; } set { numbers[row, col] = value; } } public bool WriteNumber(int row, int col, int newValue) { //Check if cell is editable if (editableFlags[row, col]) { numbers[row, col] = newValue; EmptyCells = GetEmptyCellCount(); return true; } else return false; } public int GetEmptyCellCount() { int emptyCellsCount = 0; for (int row = 0; row < SudokuDimension; row++) { for (int col = 0; col < SudokuDimension; col++) { if (numbers[row, col] == EmptyCellValue) emptyCellsCount++; } } if (emptyCellsCount == 0) { CheckUserSolution(numbers); } return emptyCellsCount; } private void CheckUserSolution(int[,] numbers) { IList<int> currRow = new List<int>(); IList<int> currCol = new List<int>(); IList<int> subBox = new List<int>(); //check horizontal for (int row = 0; row < numbers.GetLength(0); row++) { for (int col = 0; col < numbers.GetLength(1); col++) { currRow.Add(numbers[row, col]); } if (!IsRowCorrect(currRow)) { throw new SudokuException("The row is not correct!"); //custom sudoku exception } currRow = new List<int>(); } //check vertical for (int row = 0; row < numbers.GetLength(0); row++) { for (int col = 0; col < numbers.GetLength(1); col++) { currCol.Add(numbers[col, row]); } if (!IsColCorrect(currCol)) { throw new SudokuException("The col is not correct!"); //custom sudoku exception } currCol = new List<int>(); } //check sudoku subbox int rows = numbers.GetLength(0); int cols = numbers.GetLength(1); for (int row = 0; row < numbers.GetLength(0); row++) { for (int col = 0; col < numbers.GetLength(1); col++) { if ((row + 1) % 3 == 0 && (col + 1) % 3 == 0) { subBox.Add(numbers[row, col]); subBox.Add(numbers[row, col - 1]); subBox.Add(numbers[row, col - 2]); subBox.Add(numbers[row - 1, col]); subBox.Add(numbers[row - 1, col - 1]); subBox.Add(numbers[row - 1, col - 2]); subBox.Add(numbers[row - 2, col]); subBox.Add(numbers[row - 2, col - 1]); subBox.Add(numbers[row - 2, col - 2]); } if (!IsBoxCorrect(subBox) && subBox.Count == 9) { throw new ArgumentException("The subbox is not correct"); //custom sudoku exception } subBox = new List<int>(); } } } private static bool IsBoxCorrect(IList<int> subBox) { int boxNumberPresent = 0; for (int number = 0; number < subBox.Count; number++) { for (int numberInRow = 0; numberInRow < subBox.Count; numberInRow++) { if (subBox[number] == subBox[numberInRow]) { boxNumberPresent++; if (boxNumberPresent > 1) { return false; } } } boxNumberPresent = 0; } return true; } private static bool IsColCorrect(IList<int> currCol) { int colNumberPresent = 0; for (int number = 0; number < currCol.Count; number++) { for (int numberInCol = 0; numberInCol < currCol.Count; numberInCol++) { if (currCol[number] == currCol[numberInCol]) { colNumberPresent++; if (colNumberPresent > 1) { return false; } } } colNumberPresent = 0; } return true; } private static bool IsRowCorrect(IList<int> currRow) { int rowNumberPresent = 0; for (int number = 0; number < currRow.Count; number++) { for (int numberInRow = 0; numberInRow < currRow.Count; numberInRow++) { if (currRow[number] == currRow[numberInRow]) { rowNumberPresent++; if (rowNumberPresent > 1) { return false; } } } rowNumberPresent = 0; } return true; } public void ClearCell(int row, int col) { numbers[row, col] = 0; editableFlags[row, col] = true; } public void ClearUserCells() { for (int row = 0; row < SudokuDimension; row++) { for (int col = 0; col < SudokuDimension; col++) { WriteNumber(row,col,EmptyCellValue); } } } public void MakeEditable() { for (int row = 0; row < SudokuDimension; row++) { for (int col = 0; col < SudokuDimension; col++) { editableFlags[row, col] = true; } } } public void Transform(TransformType type) { switch (type) { #region Swap Rows in the same group. case TransformType.SwapRows: { int sourceRow = randGenerator.Next(1, 3); int sourceGroup = randGenerator.Next(0, 2); int destinationRow = randGenerator.Next(-2, 2); int newRowIndex = sourceRow + destinationRow; //Ensure there will be a swap in the group while (sourceRow == newRowIndex || newRowIndex < 1 || newRowIndex > 3) { if (sourceRow == newRowIndex) { destinationRow = randGenerator.Next(-2, 2); } if (sourceRow + destinationRow > 3) { destinationRow--; } else if (sourceRow + destinationRow < 1) { destinationRow++; } newRowIndex = sourceRow + destinationRow; } //Transform values to array indexer-friendly values. sourceRow = sourceRow + SudokuGroupDimension * sourceGroup - 1; newRowIndex = newRowIndex + SudokuGroupDimension * sourceGroup - 1; SwapRows(sourceRow, newRowIndex); break; } #endregion #region Swap whole groups. case TransformType.SwapGroups: { int sourceGroup = randGenerator.Next(1, 3); int destinationGroup = randGenerator.Next(-2, 2); int newGroupIndex = sourceGroup + destinationGroup; //Ensure there will be a swap within grid limits while (sourceGroup == newGroupIndex || newGroupIndex < 1 || newGroupIndex > 3) { if (destinationGroup == 0) { destinationGroup = randGenerator.Next(-2, 2); } if (sourceGroup + destinationGroup > 3) { destinationGroup--; } else if (sourceGroup + destinationGroup < 1) { destinationGroup++; } newGroupIndex = sourceGroup + destinationGroup; } //Transform values to array indexer-friendly values. sourceGroup--; newGroupIndex--; for (int row = 0; row < SudokuGroupDimension; row++) { SwapRows(row + SudokuGroupDimension * sourceGroup, row + SudokuGroupDimension * newGroupIndex); } break; } #endregion #region Transpose whole grid across left-right diagonal. case TransformType.Transpose: { Transpose(); break; } #endregion } } private void SwapRows(int row1, int row2) { int value; for (int col = 0; col < SudokuDimension; col++) { value = numbers[row1, col]; numbers[row1, col] = numbers[row2, col]; numbers[row2, col] = value; } } private void Transpose() { int value; for (int row = 0; row < SudokuDimension; row++) { for (int col = 0; col < SudokuDimension; col++) { value = numbers[row, col]; numbers[row, col] = numbers[col, row]; numbers[col, row] = value; } } } public bool IsEditable(int row, int col) { return editableFlags[row, col]; } public bool IsRowEmpty(int row) { for (int col = 0; col < SudokuDimension; col++) { if (numbers[row, col] != 0) { return false; } } return true; } public bool IsSingleInRow(int row, int col) { for (int colIndex = 0; colIndex < col; colIndex++) { if (numbers[row, colIndex] != 0) { return false; } } for (int colIndex = col + 1; colIndex < SudokuDimension; colIndex++) { if (numbers[row, colIndex] != 0) { return false; } } return true; } public override string ToString() { StringBuilder output = new StringBuilder(144); for (int group = 0; group < SudokuGroupDimension; group++) { for (int row = group * SudokuGroupDimension; row < SudokuGroupDimension * (group + 1); row++) { output.AppendFormat("{0}{1}{2} {3}{4}{5} {6}{7}{8}\n", numbers[row, 0], numbers[row, 1], numbers[row, 2], numbers[row, 3], numbers[row, 4], numbers[row, 5], numbers[row, 6], numbers[row, 7], numbers[row, 8]); } output.AppendLine(); } return output.ToString(); } public enum Difficulty { Easy, Medium, Hard } public enum TransformType { SwapRows, SwapGroups, Transpose } } }
using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace BassClefStudio.GameModel.Input { /// <summary> /// Represents a single, abstracted input detected by an <see cref="IInputWatcher"/>, of any kind. /// </summary> public interface IInput { } /// <summary> /// An <see cref="IInput"/> with a spatial component associated with it by the <see cref="IInputWatcher"/> that detected it. /// </summary> public interface ISpatialInput : IInput { /// <summary> /// The point in input- or graphics- space that the <see cref="IInputWatcher"/> associated with this input (for example, if a mouse click was processed, this would include the location where the mouse was at the time). /// </summary> Vector2 Point { get; } } /// <summary> /// Represents any button or other binary input that can be enabled and disabled (pressed and released). /// </summary> public interface IBinaryInput : IInput { /// <summary> /// A <see cref="bool"/> indicating whether the <see cref="IBinaryInput"/> represents a press ('true') or release ('false') input detection. /// </summary> bool IsPressed { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace YourContacts.Models { public class Contact { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; } public Status Status { get; set; } } public enum Status { Undefined, Inactive, Active } }
using jaytwo.Common.Extensions; using jaytwo.Common.Http; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; namespace jaytwo.Common.Test.Http { [TestFixture] public static partial class HttpProviderTests { private static IEnumerable<TestCaseData> HttpProvider_SubmitHead_TestCases() { yield return new TestCaseData(new Func<string, HttpWebResponse>(url => new HttpClient().SubmitHead(url))); yield return new TestCaseData(new Func<string, HttpWebResponse>(url => new HttpClient().SubmitHead(new Uri(url)))); yield return new TestCaseData(new Func<string, HttpWebResponse>(url => new HttpClient().SubmitHead(WebRequest.Create(url) as HttpWebRequest))); yield return new TestCaseData(new Func<string, HttpWebResponse>(url => HttpProvider.SubmitHead(url))); yield return new TestCaseData(new Func<string, HttpWebResponse>(url => HttpProvider.SubmitHead(new Uri(url)))); yield return new TestCaseData(new Func<string, HttpWebResponse>(url => HttpProvider.SubmitHead(WebRequest.Create(url) as HttpWebRequest))); yield return new TestCaseData(new Func<string, HttpWebResponse>(url => new Uri(url).SubmitHead())); yield return new TestCaseData(new Func<string, HttpWebResponse>(url => (WebRequest.Create(url) as HttpWebRequest).SubmitHead())); } [Test] [TestCaseSource("HttpProvider_SubmitHead_TestCases")] public static void HttpProvider_SubmitHead(Func<string, HttpWebResponse> submitMethod) { // http://httpbin.org/ var url = "http://httpbin.org/get"; using (var response = submitMethod(url)) { var responseString = HttpHelper.GetContentAsString(response); Console.WriteLine(responseString); HttpHelper.VerifyResponseStatusOK(response); Assert.IsNullOrEmpty(responseString); } } } }
using AtendimentoProntoSocorro.Repositories; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace AtendimentoProntoSocorro.Models { public class Ficha : BaseModel { public new int Id { get; set; } public Paciente Paciente { get; set; } public DateTime DataFicha { get; set; } public string Queixa { get; set; } public string InformacaoResgate { get; set; } public int StatusDaFicha { get; set; } public Especialidade Especialidade { get; set; } public Procedencia Procedencia { get; set; } public DadoClinico DadoClinico { get; set; } } public enum Especialidade { BucoMaxilo, CirurgiaGeral, ClínicaMédica, COVID, Neurocirugia, Pediatria, Traumatologia, Obstetrícia } public enum Procedencia { Espontânea, Bombeiro, PolíciaMilitar, GCM, Metrô, AMASÉ, SAMU, AmbulânciaPartilular } }
using SharpDX; using SharpDX.Toolkit; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProtoCar { class GameOver : IGameState { int points1; int points2; string gameOverString; public GameOver(int player1Point, int player2Points) { this.points1 = player1Point; this.points2 = player2Points; if (player1Point > player2Points) gameOverString = "Player1 has won with " + points1 + "!\nPlayer2 has " + points2 + " points!" ; else if(player2Points > player1Point) gameOverString = "Player2 has won with " + points2 + "!\nPlayer1 has " + points1 + " points!"; else gameOverString = "Draw! Both player have " + points1 + " points!"; } public void init() { } public EGameState update(GameTime gameTime) { if (Game1.keyboardState.IsKeyPressed(SharpDX.Toolkit.Input.Keys.Enter)) return EGameState.MainMenu; return EGameState.GameOver; } public void draw(GameTime gameTime) { Game1.gManager.GraphicsDevice.Clear(Color.Black); Game1.spriteBatch.Begin(); Game1.spriteBatch.DrawString(Game1.font, "GameOver", new Vector2(0, 0), Color.White, 0, Vector2.Zero, 2.0f, SharpDX.Toolkit.Graphics.SpriteEffects.None, 0); Game1.spriteBatch.DrawString(Game1.font, gameOverString + "\n\nPress Enter...", new Vector2(0, 40), Color.White, 0, Vector2.Zero, 2.0f, SharpDX.Toolkit.Graphics.SpriteEffects.None, 0); Game1.spriteBatch.End(); } } }
using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New Item", menuName = "Inventory/Item")] //to create scriptable object for items. used to display in menus public class Item : ScriptableObject { public Sprite icon = null; new public string name = "New Item"; public string description = "Item Description"; public bool usableInMenu; public int sellValue; public List<BaseStatusEffect> statusEffects = new List<BaseStatusEffect>(); public enum UseStates { HERO, ALLHEROES, ENEMY, ALLENEMIES, } public UseStates useState; public enum Types { RESTORATIVE, DAMAGE, HEALSTATUS, INFLICTSTATUS, KEYITEM } public Types type; public void RemoveFromInventory() { Inventory.instance.items.Reverse(); Inventory.instance.items.Remove(this); Inventory.instance.items.Reverse(); } }
using UnityEngine; public class ShopkeeperScript : MonoBehaviour { // base components [HideInInspector] public Transform myTransform; [HideInInspector] public GameObject myGameObject; // eyes [Header("eyes")] public GameObject[] eyeNormalObjects; public GameObject[] eyeBlinkObjects; public enum EyeState { Normal, Blink, Dead }; public EyeState curEyeState; // movement Vector3 posOriginal, posCur; // blink int blinkHoldDur, blinkHoldCounter, blinkRateMin, blinkRateMax, blinkRate, blinkRateCounter, blinkIndex; void Start () { // base components myTransform = transform; myGameObject = gameObject; // movement posOriginal = myTransform.position; posCur = posOriginal; // blink blinkIndex = 0; blinkHoldDur = 6; blinkHoldCounter = 0; blinkRateMin = 120; blinkRateMax = 360; blinkRate = Mathf.RoundToInt(TommieRandom.instance.RandomRange(blinkRateMin, blinkRateMax)); blinkRateCounter = 0; } void Update () { if (!SetupManager.instance.inFreeze) { // eyes blinking if (blinkIndex == 0) { if (blinkRateCounter < blinkRate) { blinkRateCounter++; } else { blinkHoldCounter = 0; blinkIndex = 1; } } else { if (blinkHoldCounter < blinkHoldDur) { blinkHoldCounter++; } else { blinkRateCounter = 0; blinkRate = Mathf.RoundToInt(TommieRandom.instance.RandomRange(blinkRateMin, blinkRateMax)); blinkIndex = 0; } } switch (blinkIndex) { case 0: SetEyeState(EyeState.Normal); break; case 1: SetEyeState(EyeState.Blink); break; } // movement float moveLerpie = 2.5f; float moveRadius = .675f; Vector3 p0 = posOriginal; Vector3 p1 = GameManager.instance.playerFirstPersonDrifter.myTransform.position; p1.y = p0.y; Vector3 p2 = (p1 - p0).normalized; Vector3 posTarget = posOriginal; posTarget += (p2 * moveRadius); float t0 = Time.time * 20f; float f0 = .25f; float s0 = Mathf.Sin(t0) * f0; posTarget.y += s0 * Vector3.Distance(posCur,posTarget); posCur = Vector3.Lerp(posCur,posTarget,moveLerpie * Time.deltaTime); myTransform.position = posCur; } } public void SetEyeState(EyeState _to) { for (int i = 0; i < 2; i++) { eyeNormalObjects[i].SetActive(_to == EyeState.Normal); eyeBlinkObjects[i].SetActive(_to == EyeState.Blink); } curEyeState = _to; } }
using System; using System.Collections.Generic; using System.Text; namespace Vehicles { public abstract class Vehicle { private double fuelQuant; public Vehicle(double fuelQuantity, double fuelConsumption, double tankCap) { this.FuelConsumption = fuelConsumption; this.TankCap = tankCap; this.FuelQuantity = fuelQuantity; } public double FuelQuantity { get => fuelQuant; protected set { if (value > TankCap) { fuelQuant = 0; } else { fuelQuant = value; } } } public double FuelConsumption { get; protected set; } public double TankCap { get; } public abstract string Drive(double distance); public abstract void Refuel(double fuel); } }
using System.Xml.Linq; namespace LoneWolf.Migration.Files { public class Heading : ISubTransformer { public XElement Transform(XElement element) { // <h3> var heading = element.Element("h3"); if(heading != null) heading.Name = "h1"; // <h2> heading = element.Element("h2"); if (heading != null) heading.Name = "h1"; return element; } } }
using System.Runtime.CompilerServices; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Org.Common.DataProvider; using Org.Common.Model; using Org.DAL.MySql.DataProvider; [assembly:InternalsVisibleTo("EmployeePortal.Tests")] namespace Org.DAL.MySql { public static class DalRegistrationExtensions { private const string CONNECTION_STRING_NAME = "EmpoyeePortalConnection"; public static void RegisterDal(this IServiceCollection services, IConfiguration configuration) { var connectionString = configuration.GetConnectionString(CONNECTION_STRING_NAME); services.AddDbContextPool<EmployeContext>(o => { o.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)) .EnableSensitiveDataLogging() .EnableDetailedErrors(); }); services.AddScoped<IDatabaseMigrationProvider, DatabaseMigrationProvider>(); services.AddScoped<ILeaveDataProvider, LeaveDataProvider>(); services.AddAutoMapper(cfg => { cfg.CreateMap<Leave, Common.Domain.Leave>(); cfg.CreateMap<Common.Domain.Leave, Leave>(); }); } public static void AddIdentityEfStores(this IdentityBuilder identityBuilder) { identityBuilder.AddEntityFrameworkStores<EmployeContext>(); } } }
using UnityEngine; using System.Collections; public class singleBulletScript : MonoBehaviour { private int health = 1; void Start () { } void Update () { if (health <= 0) { Destroy (gameObject); } } void removeHealth(int damage) { health -= damage; } void setHealth(int newHealth) { health = newHealth; } public void dieOnContact() { health = 0; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerWaterBubble : MonoBehaviour { [SerializeField] private GameObject playerWater; private void Start() { StartCoroutine(BubbleExplor()); } IEnumerator BubbleExplor() { yield return new WaitForSeconds(1.5f); gameObject.GetComponent<AudioSource>().Play(); for (int i = 0; i < 15; i++) { yield return new WaitForSeconds(0.2f); Vector3 pos = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y); GameObject k = Instantiate(playerWater, pos, Quaternion.identity) as GameObject; k.transform.Rotate(0, 0, transform.rotation.z + i * -30, Space.Self); Destroy(k, 2); } Destroy(gameObject); } }