text
stringlengths
13
6.01M
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using API.DTOs; using API.Entities; using API.Interfaces; using AutoMapper; using Microsoft.EntityFrameworkCore; namespace API.Data { public class TripsRepository : ITripsRepository { private readonly DataContext _context; private readonly IMapper _mapper; public TripsRepository(DataContext context, IMapper mapper) { _mapper = mapper; _context = context; } public async Task<IEnumerable<AttractionDto>> GetAttractions(int tripId) { var query = _context.Attractions.AsQueryable(); query = query.Where(a => a.TripId == tripId); return await query.Select(query => new AttractionDto { Id = query.Id, Name = query.Name, Address = query.Address, Type = query.Type, Theme = query.Theme, Subtheme = query.Subtheme, DateTimeOfVisit = query.DateTimeOfVisit, WasVisited = query.WasVisited }).ToListAsync(); } public async Task<Attraction> GetAttraction(int attId) { return await _context.Attractions.FindAsync(attId); } public async Task<Trip> GetUserTrip(int tripId) { return await _context.Trips.Include(a => a.Attractions).SingleOrDefaultAsync(x => x.Id == tripId); } public async Task<IEnumerable<TripDto>> GetUserTrips(int userId) { var query = _context.Trips.AsQueryable(); query = query.Where(t => t.AppUserId == userId); return await query.Select(query => new TripDto { Id = query.Id, Place = query.Place, TripDate = query.TripDate, TripFinishDate = query.TripFinishDate }).ToListAsync(); } public async Task<IEnumerable<int>> GetTripsId(int userId) { var query = _context.Trips.AsQueryable(); var ids = query.Where(t => t.AppUserId == userId).Select(x => x.Id).ToListAsync(); return await ids; } public async Task<IEnumerable<EventDto>> GetSCategoryEvents(string sCategory, int cityId) { var events = _context.Events.AsQueryable(); events = events.Where(c => c.Subtheme == sCategory).Where(c => c.CityId == cityId); return await events.Select(events => new EventDto { Id = events.Id, Name = events.Name, Address = events.Address, StartTime = events.StartTime, FinishTime = events.FinishTime, Theme = events.Theme, Subtheme = events.Subtheme, ExpectedTimeSpent = events.ExpectedTimeSpent }).ToListAsync(); } public async Task<IEnumerable<PlaceDto>> GetSCategoryPlaces (string sCategory, int cityId) { var places = _context.Places.AsQueryable(); places = places.Where(c => c.Subtheme == sCategory); places = places.Where(c => c.CityId == cityId); return await places.Select(places => new PlaceDto { Id = places.Id, Name = places.Name, Address = places.Address, OpenTime = places.OpenTime, CloseTime = places.CloseTime, Theme = places.Theme, Subtheme = places.Subtheme, Rating = places.Rating, Promotion = places.Promotion, ExpectedTimeSpent = places.ExpectedTimeSpent }).ToListAsync(); } public async Task<IEnumerable<EventDto>> GetCategoryEvents(string Category, int cityId) { var events = _context.Events.AsQueryable(); events = events.Where(c => c.Theme == Category).Where(c => c.CityId == cityId); return await events.Select(events => new EventDto { Id = events.Id, Name = events.Name, Address = events.Address, StartTime = events.StartTime, FinishTime = events.FinishTime, Theme = events.Theme, Subtheme = events.Subtheme, ExpectedTimeSpent = events.ExpectedTimeSpent }).ToListAsync(); } public async Task<IEnumerable<PlaceDto>> GetCategoryPlaces (string Category, int cityId) { var places = _context.Places.AsQueryable(); places = places.Where(c => c.Theme == Category); places = places.Where(c => c.CityId == cityId); return await places.Select(places => new PlaceDto { Id = places.Id, Name = places.Name, Address = places.Address, OpenTime = places.OpenTime, CloseTime = places.CloseTime, Theme = places.Theme, Subtheme = places.Subtheme, Rating = places.Rating, Promotion = places.Promotion, ExpectedTimeSpent = places.ExpectedTimeSpent }).ToListAsync(); } public async Task<IEnumerable<PlaceDto>> GetOtherPlaces (int cityId) { var places = _context.Places.AsQueryable(); places = places.Where(c => c.CityId == cityId); return await places.Select(places => new PlaceDto { Id = places.Id, Name = places.Name, Address = places.Address, OpenTime = places.OpenTime, CloseTime = places.CloseTime, Theme = places.Theme, Subtheme = places.Subtheme, Rating = places.Rating, Promotion = places.Promotion, ExpectedTimeSpent = places.ExpectedTimeSpent }).ToListAsync(); } } }
using System; using System.IO; namespace No8.Solution.Printers { public class CanonPrinter : Printer { public CanonPrinter(string model) : base(model) { } public override string Name => "Canon"; protected override void PrintEmulation(FileStream stream) { using (stream) { for(int i = 0; i < stream.Length; i++) { stream.ReadByte(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data; public partial class Presentation_Sermons_Archive_Default : System.Web.UI.Page { #region Declarations DataSet dsSermons = new DataSet(); #endregion protected void Page_Load(object sender, EventArgs e) { //LoadSermonComps(); } private void LoadSermonComps() { GetSermons(); foreach (DataRow row in dsSermons.Tables[0].Rows) { sermonsgrid.Controls.Add(MakeSermonComp(row["SermonID"].ToString(), row["ArtSmall"].ToString(), row["IsSeries"].ToString(), row["SeriesID"].ToString(), row["PreachedDate"].ToString())); } //sermonsgrid.Controls.Add(MakeSermonComp("1", "../../Images/album-art.png", "true", "1")); } private Panel MakeSermonComp(string sermonID, string albumArtPath, string isSeries, string seriesID, string preachedDate) { Panel innerpnl = new Panel(); innerpnl.CssClass = "sermon-grid-comp"; HtmlGenericControl a = new HtmlGenericControl("a"); #region Link To Series Or Sermon if (isSeries == "true") a.Attributes.Add("href", "../Sermons/Default.aspx?seriesID=" + seriesID); else a.Attributes.Add("href", "../Sermons/Default.aspx?sermonID=" + sermonID); #endregion Panel artpnl = new Panel(); artpnl.CssClass = "sermons-art"; Image img = new Image(); img.ImageUrl = albumArtPath; artpnl.Controls.Add(img); Panel typepnl = new Panel(); typepnl.CssClass = "grid-type"; if (isSeries == "true") { Label lblSeries = new Label(); lblSeries.CssClass = "issermon"; lblSeries.Text = "Sermon Series"; typepnl.Controls.Add(lblSeries); } else { Label lblSermon = new Label(); lblSermon.CssClass = "issermon"; lblSermon.Text = "Sermon"; typepnl.Controls.Add(lblSermon); } Label lblDate = new Label(); lblDate.Text = preachedDate != "" ? Convert.ToDateTime(preachedDate).ToShortDateString() : ""; lblDate.CssClass = "date"; typepnl.Controls.Add(lblDate); a.Controls.Add(artpnl); a.Controls.Add(new HiddenField { Value = sermonID }); a.Controls.Add(typepnl); innerpnl.Controls.Add(a); return innerpnl; } private void GetSermons() { DataLink link = new DataLink(); dsSermons = link.GetSermons(); } private string GetColumnValue(DataSet ds, string columnName) { return ds.Tables[0].Rows[0][columnName].ToString(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace OnlineExamSytem.Models { public class Exam { [Key] public int ExamID { get; set; } public string Identifier { get; set; } [DataType(DataType.DateTime)] public DateTime Date { get; set; } public int Score { get; set; } public string Owner { get; set; } public int QuestionNumber { get; set; } public int TrueQuestionNumber { get; set; } public int FalseQuestionNumber { get; set; } public int ExamTime { get; set; } public virtual ICollection<Question> ListQuestion { get; set; } } }
// -------------------------------- // <copyright file="Special.cs" > // © 2013 KarzPlus Inc. // </copyright> // <author>JOrtega</author> // <summary> // Special Entity Layer Object. // </summary> // --------------------------------- using System; using KarzPlus.Entities.Common; namespace KarzPlus.Entities { /// <summary> /// Special entity object. /// </summary> [Serializable] public class Special { public bool IsItemModified { get; set; } private int? specialId; /// <summary> /// Gets or sets SpecialId. /// </summary> [SqlName("SpecialId")] public int? SpecialId { get { return specialId; } set { if (value != specialId) { specialId = value; IsItemModified = true; } } } private int inventoryId; /// <summary> /// Gets or sets InventoryId. /// </summary> [SqlName("InventoryId")] public int InventoryId { get { return inventoryId; } set { if (value != inventoryId) { inventoryId = value; IsItemModified = true; } } } private DateTime dateStart; /// <summary> /// Gets or sets DateStart. /// </summary> [SqlName("DateStart")] public DateTime DateStart { get { return dateStart; } set { if (value != dateStart) { dateStart = value; IsItemModified = true; } } } private DateTime dateEnd; /// <summary> /// Gets or sets DateEnd. /// </summary> [SqlName("DateEnd")] public DateTime DateEnd { get { return dateEnd; } set { if (value != dateEnd) { dateEnd = value; IsItemModified = true; } } } private decimal price; /// <summary> /// Gets or sets Price. /// </summary> [SqlName("Price")] public decimal Price { get { return price; } set { if (value != price) { price = value; IsItemModified = true; } } } /// <summary> /// Initializes a new instance of the Special class. /// </summary> public Special() { SpecialId = default(int?); InventoryId = default(int); DateStart = default(DateTime); DateEnd = default(DateTime); Price = default(decimal); IsItemModified = false; } public override string ToString() { return string.Format("SpecialId: {0}, InventoryId: {1}, Price: {2};", SpecialId, InventoryId, Price); } } }
using System; using System.IO; using System.Text; using UnityEngine; using UnityEngine.UI; namespace RecordSaveAudio { [RequireComponent(typeof(AudioSource))] public class RecordSaveAudio : MonoBehaviour { #region Constants & Static Variables /// <summary> /// Audio Source to store Microphone Input, An AudioSource Component is required by default /// </summary> static AudioSource audioSource; /// <summary> /// The samples are floats ranging from -1.0f to 1.0f, representing the data in the audio clip /// </summary> static float[] samplesData; #endregion #region Editor Exposed Variables public Button RecordAndSaveButton; /// <summary> /// What should the saved file name be, the file will be saved in Streaming Assets Directory /// </summary> [Tooltip("What should the saved file name be, the file will be saved in Streaming Assets Directory, Don't add .wav at the end")] public string fileName; #endregion #region MonoBehaviour Callbacks void Start() { audioSource = GetComponent<AudioSource>(); audioSource.clip = Microphone.Start(Microphone.devices[0], true, 10, 22050); // third argument restrict the duration of the audio to 10 seconds if (RecordAndSaveButton == null) { return; } RecordAndSaveButton.onClick.AddListener(() => { RecordAndSave(fileName); }); } public static void RecordAndSave(string fileName = "test") { while (!(Microphone.GetPosition(null) > 0)) { } samplesData = new float[audioSource.clip.samples * audioSource.clip.channels]; audioSource.clip.GetData(samplesData, 0); string filePath = Path.Combine(Application.persistentDataPath, fileName + ".wav"); // Delete the file if it exists. if (File.Exists(filePath)) { File.Delete(filePath); } try { SavWav.TrimSilence(audioSource.clip, 0.9f); SavWav.Save(fileName, audioSource.clip); Debug.Log("File Saved Successfully at: " + filePath); } catch (DirectoryNotFoundException) { Debug.LogError("Please, Create a StreamingAssets Directory in the Assets Folder"); } catch (Exception e) { Debug.Log(e.Message); //check for other Exceptions } } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ClassBase : MonoBehaviour { //Stats public float health, defense; //Body components //public RuntimeAnimatorController player; //Attack system public Transform attackPoint; public float attackRange, normalAttackRate, heavyAttackRate, specialAttackRate; public float attackDamage, normalAttackDamage, heavyAttackDamage, specialAttackDamage; public bool normalAtk, heavyAtk; //Sound system public AudioSource normalAttackSound, heavyAttackSound, specialAttackSound, damageSound; [HideInInspector] public Rigidbody rb; //Private private Animator animator; public float lastNormalAttack, lastHeavyAttack, lastSpecialAttack = 0; //HealthBar objects public GameObject HealthBar; ProgressBar Health; //AttackBar Objects public GameObject specialBar; ProgressBarCircle special; public float specialEnergy, specialEnergyCost, specialIncrease; public GameObject normalBar; ProgressBarCircle normal; public float normalEnergy, normalEnergyCost, restoreNormal; public GameObject heavyBar; ProgressBarCircle heavy; public float heavyEnergy, heavyEnergyCost, restoreHeavy; public ParticleSystem explosionParticle; [HideInInspector] public bool frozen = false; public float normalAttackFreeze = 0; public bool isGuarding; private float normalTimer; private float heavyTimer; public GameObject spawnPoint; //--------------------------------------------------------------------------------------------------// // Start and Update // //--------------------------------------------------------------------------------------------------// void Start() { rb = GetComponent<Rigidbody>(); animator = GetComponentInChildren<Animator>(); animator.SetFloat("Animation Speed", 1f); Health = HealthBar.GetComponent<ProgressBar>(); if (specialBar) special = specialBar.GetComponent<ProgressBarCircle>(); if(normalBar) { normal = normalBar.GetComponent<ProgressBarCircle>(); normal.Alert = 100; } if(heavyBar) { heavy = heavyBar.GetComponent<ProgressBarCircle>(); heavy.Alert = 100; } normalAttackFreeze = normalAttackRate; isGuarding = false; normalEnergy = 100f; heavyEnergy = 100f; _Start(); StartCoroutine ("tick"); } void Update() { Health.UpdateValue(health); if (specialBar) special.UpdateValue(specialEnergy); if(normalBar) normal.UpdateValue(normalEnergy); if(heavyBar) heavy.UpdateValue(heavyEnergy); normalTimer += Time.deltaTime; heavyTimer += Time.deltaTime; if(normalTimer >= 5f) restoreNormalEnergy(); if(heavyTimer >= 10f) restoreHeavyEnergy(); if(normalBar) { if (Time.time - lastNormalAttack > normalAttackRate && normalEnergy >= normalEnergyCost) normal.Alert = 0; } if(heavyBar) { if (Time.time - lastHeavyAttack > heavyAttackRate && heavyEnergy >= heavyEnergyCost) heavy.Alert = 0; } } public virtual void _Start() { } //--------------------------------------------------------------------------------------------------// // Helper Functions // //--------------------------------------------------------------------------------------------------// public void reset () { health = 100; normalAtk = false; heavyAtk = false; lastNormalAttack = 0; lastHeavyAttack = 0; lastSpecialAttack = 0; heavyEnergy = 100; normalEnergy = 100; isGuarding = false; gameObject.transform.position = spawnPoint.transform.position; rb.constraints = ~RigidbodyConstraints.FreezePosition; AIbase aiScript = GetComponent<AIbase>(); if (aiScript) { StartCoroutine(aiScript.tick ()); } } public IEnumerator normalAttack() { if (Time.time - lastNormalAttack > normalAttackRate && normalEnergy >= normalEnergyCost) { lastNormalAttack = Time.time; normalEnergy -= normalEnergyCost; restoreSpecialEnergy(); animator.SetInteger("Trigger Number", 2); animator.SetTrigger("Trigger"); if (normalAttackRate != 0) { animator.SetFloat("Animation Speed", 1f / normalAttackRate); yield return new WaitForSeconds(0.4f); animator.SetFloat("Animation Speed", 1f); } if(normalBar) normal.Alert = 100; _normalAttack(); } } public virtual void _normalAttack() { print ("Implement normal attack in subclass"); } public IEnumerator heavyAttack() { if (Time.time - lastHeavyAttack > heavyAttackRate && heavyEnergy >= heavyEnergyCost) { lastHeavyAttack = Time.time; heavyEnergy -= heavyEnergyCost; restoreSpecialEnergy(); animator.SetInteger("Trigger Number", 2); animator.SetTrigger("Trigger"); if (heavyAttackRate != 0) { animator.SetFloat("Animation Speed", 1f / heavyAttackRate ); yield return new WaitForSeconds(0.4f); animator.SetFloat("Animation Speed", 1f); } if(heavyBar) heavy.Alert = 100; _heavyAttack(); } } public virtual void _heavyAttack() { print ("Implement heavy attack in subclass"); } public IEnumerator specialAttack(Vector3 pos) { if (Time.time - lastSpecialAttack > specialAttackRate && specialEnergy >= specialEnergyCost) { specialEnergy -= specialEnergyCost; lastSpecialAttack = Time.time; animator.SetInteger("Trigger Number", 2); animator.SetTrigger("Trigger"); if (specialAttackRate != 0) { animator.SetFloat("Animation Speed", 1f / specialAttackRate); yield return new WaitForSeconds(0.4f); animator.SetFloat("Animation Speed", 1f); } StartCoroutine (Freeze(normalAttackFreeze)); _specialAttack(pos); } } public IEnumerator Freeze(float duration) { frozen = true; rb.velocity = new Vector3(0, 0, 0); yield return new WaitForSeconds (duration); frozen = false; } public virtual void _specialAttack(Vector3 pos) { print ("Implement special attack in subclass"); } public virtual void takeDamage(float damage) { if(isGuarding) damage = Mathf.Abs(damage*(defense/100f)); health -= damage; if (health <= 0) { health = 0; this.gameObject.transform.position = new Vector3(0f, -10f, 0f); rb.constraints = RigidbodyConstraints.FreezePosition; } restoreSpecialEnergy(); } public virtual void explosion() { Instantiate(explosionParticle, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity); } public virtual void restoreNormalEnergy() { if(normalEnergy <= 99f) normalEnergy += restoreNormal; normalTimer = 0; } public virtual void restoreHeavyEnergy() { if(heavyEnergy <= 99f) heavyEnergy += restoreHeavy; heavyTimer = 0; } public virtual void restoreSpecialEnergy() { if(specialEnergy < 100f) specialEnergy += specialIncrease; } public IEnumerator tick() { while(health > 0) { yield return new WaitForSeconds(1f); if(specialEnergy < 100) specialEnergy += 2f; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; using Microsoft.Kinect; namespace Stuba.BioSandbox { public struct Coordinates2D { public int X; public int Y; public int Width; public int Height; public int TrackingId; public int PlayerIndex; public int LeftEyeX; public int LeftEyeY; public int RightEyeX; public int RightEyeY; } struct NativeEngine { public IntPtr engine; public IntPtr inputModule; public IntPtr outputModule; } public class BiometricEngine { // Kinect private static readonly Dictionary<int, SkeletonFaceTracker> trackedSkeletons = new Dictionary<int, SkeletonFaceTracker>(); private const uint MaxMissedFrames = 100; private static List<Coordinates2D> coordinates = new List<Coordinates2D>(); // Native private bool _isLoaded = false; public bool IsLoaded { get { return _isLoaded; } } private NativeEngine _nativeEngine; public BiometricEngine() { Console.WriteLine("Creating BiometricEngine."); } ~BiometricEngine() { Console.WriteLine("Calling destructor."); } [DllImport("libBioSandbox.dll")] private static extern bool ProcessImage(NativeEngine engine, byte[] pixelDataGrayscale, int width, int height, Coordinates2D[] faces, int numFaces, int[] identities);// TODO Here should be a check if there is supported module for inserting images [DllImport("libBioSandbox.dll")] private static extern bool ProcessImageWithDistances(NativeEngine engine, byte[] pixelData, int width, int height, Coordinates2D[] faces, int numFaces, int[] identities, int numDistances, double[] distances); [DllImport("libBioSandbox.dll")] private static extern bool ProcessImageWithDepth(NativeEngine engine, byte[] pixelData, int width, int height, short[] depthData, int depthWidth, int depthHeight, Coordinates2D[] faces, int numFaces, int[] identities, int numDistances, double[] distances); public void ProcessImage(byte[] pixelDataGrayscale,int width, int height, Coordinates2D [] faces, int [] identities){ ProcessImage(_nativeEngine, pixelDataGrayscale, width, height, faces, faces.Length, identities ); } public void ProcessImage(byte[] pixelDataGrayscale, int width, int height, Coordinates2D[] faces, int[] identities, double[] distances) { //if(faces.Length > 0) // Console.WriteLine("Coords: {0},{1},{2},{3}", faces[0].LeftEyeX, faces[0].LeftEyeY, faces[0].RightEyeX, faces[0].RightEyeY); ProcessImageWithDistances( _nativeEngine, pixelDataGrayscale, width, height, faces, faces.Length, identities, (faces.Length == 0 ? 0 : distances.Length / faces.Length), distances); } public bool ProcessImage(byte[] pixelDataGrayscale, int width, int height,short [] depthMap, int dWidth,int dHeight, Coordinates2D[] faces, int[] identities, double[] distances) { //if(faces.Length > 0) // Console.WriteLine("Coords: {0},{1},{2},{3}", faces[0].LeftEyeX, faces[0].LeftEyeY, faces[0].RightEyeX, faces[0].RightEyeY); return ProcessImageWithDepth( _nativeEngine, pixelDataGrayscale, width, height, depthMap, dWidth, dHeight, faces, faces.Length, identities, (faces.Length == 0 ? 0 : distances.Length / faces.Length), distances); } [DllImport("libBioSandbox.dll")] private static extern NativeEngine InitializeBiosandbox(string configFile); public bool Initialize(string configFile) { _nativeEngine = InitializeBiosandbox(configFile); return _nativeEngine.engine == IntPtr.Zero ? false : true; } [DllImport("libBioSandbox.dll")] private static extern void DeinitializeBiosandbox(NativeEngine engine); public void Denitialize() { DeinitializeBiosandbox(_nativeEngine); _nativeEngine.engine = IntPtr.Zero; } #region Kinect private HashSet<int> scannedIdentities = new HashSet<int>(); public void ProcessFrame(KinectSensor sensor, byte[] colorImage, ColorImageFormat colorImageFormat, DepthImageFrame depthFrame, short[] depthImage, DepthImageFormat depthImageFormat, Skeleton[] skeletonData, SkeletonFrame skeletonFrame) { //Console.WriteLine("N: ---------"); coordinates.Clear(); int detectedFace = 0; int trackedSkeletonsCount = 0; int playerIndex = -1; for (int i = 0; i < skeletonData.Length; i++) //foreach (Skeleton skeleton in skeletonData) { Skeleton skeleton = skeletonData[i]; if (skeleton.TrackingState == SkeletonTrackingState.Tracked || skeleton.TrackingState == SkeletonTrackingState.PositionOnly) { // We want keep a record of any skeleton, tracked or untracked. if (!trackedSkeletons.ContainsKey(skeleton.TrackingId)) { trackedSkeletons.Add(skeleton.TrackingId, new SkeletonFaceTracker()); } DepthImagePoint depthPoint = depthFrame.MapFromSkeletonPoint(skeleton.Joints[JointType.Head].Position); ColorImagePoint colorPoint = depthFrame.MapToColorImagePoint(depthPoint.X, depthPoint.Y, colorImageFormat); Coordinates2D c = new Coordinates2D(); playerIndex = i + 1; c.X = colorPoint.X; c.Y = colorPoint.Y; c.Width = 0; c.Height = 0; c.LeftEyeX = 0; c.LeftEyeY = 0; c.RightEyeX = 0; c.RightEyeY = 0; c.PlayerIndex = playerIndex; trackedSkeletonsCount++; // Give each tracker the upated frame. SkeletonFaceTracker skeletonFaceTracker; if (!scannedIdentities.Contains(skeleton.TrackingId) && detectedFace < 1 && trackedSkeletons.TryGetValue(skeleton.TrackingId, out skeletonFaceTracker)) { detectedFace++; scannedIdentities.Add(skeleton.TrackingId); skeletonFaceTracker.OnFrameReady(sensor, colorImageFormat, colorImage, depthImageFormat, depthImage, skeleton); skeletonFaceTracker.LastTrackedFrame = skeletonFrame.FrameNumber; Coordinates2D? realCoords = skeletonFaceTracker.GetFaceCoordinates(); if (realCoords.HasValue) { c = realCoords.Value; c.PlayerIndex = playerIndex; } } c.TrackingId = skeleton.TrackingId; coordinates.Add(c); } } if (scannedIdentities.Count > 0 && scannedIdentities.Count >= trackedSkeletonsCount) { scannedIdentities.Clear(); //Console.WriteLine("Clearing"); } RemoveOldTrackers(skeletonFrame.FrameNumber); //if (coordinates.Count > 0) { int[] identities = new int[coordinates.Count]; // stopwatch.Reset(); // stopwatch.Start(); double[] distances = new double[coordinates.Count * 8]; this. ProcessImage(colorImage, GetWidth(colorImageFormat), GetHeight(colorImageFormat), depthImage, 640, 480, coordinates.ToArray(), identities, distances); // stopwatch.Stop(); // foreach (int i in identities) // { // Console.WriteLine("Recognized: {0} (in {1} millis - {2} ticks)", i, stopwatch.ElapsedMilliseconds, stopwatch.ElapsedTicks); // } } } private static Stopwatch stopwatch = new Stopwatch(); private Skeleton GetTrackedSkeleton(Skeleton[] skeletons) { foreach (Skeleton skeleton in skeletons) { if (SkeletonTrackingState.Tracked == skeleton.TrackingState) { return skeleton; } } return null; } /// <summary> /// Clear out any trackers for skeletons we haven't heard from for a while /// </summary> private void RemoveOldTrackers(int currentFrameNumber) { var trackersToRemove = new List<int>(); foreach (var tracker in trackedSkeletons) { uint missedFrames = (uint)currentFrameNumber - (uint)tracker.Value.LastTrackedFrame; if (missedFrames > MaxMissedFrames) { // There have been too many frames since we last saw this skeleton trackersToRemove.Add(tracker.Key); } } foreach (int trackingId in trackersToRemove) { RemoveTracker(trackingId); } } private void RemoveTracker(int trackingId) { trackedSkeletons[trackingId].Dispose(); trackedSkeletons.Remove(trackingId); } public void ResetFaceTracking() { foreach (int trackingId in new List<int>(trackedSkeletons.Keys)) { RemoveTracker(trackingId); } } #endregion public static int GetWidth(ColorImageFormat format) { switch (format) { case ColorImageFormat.RgbResolution1280x960Fps12: return 1280; case ColorImageFormat.RawYuvResolution640x480Fps15: case ColorImageFormat.RgbResolution640x480Fps30: case ColorImageFormat.YuvResolution640x480Fps15: return 640; default: return 640; } } public static int GetHeight(ColorImageFormat format) { switch (format) { case ColorImageFormat.RgbResolution1280x960Fps12: return 960; case ColorImageFormat.RawYuvResolution640x480Fps15: case ColorImageFormat.RgbResolution640x480Fps30: case ColorImageFormat.YuvResolution640x480Fps15: return 480; default: return 480; } } } public class SkeletonFaceTracker : IDisposable { private static FaceTriangle[] faceTriangles; private EnumIndexableCollection<FeaturePoint, PointF> facePoints; private FaceTracker faceTracker; private bool lastFaceTrackSucceeded; private SkeletonTrackingState skeletonTrackingState; public int LastTrackedFrame { get; set; } public void Dispose() { if (this.faceTracker != null) { this.faceTracker.Dispose(); this.faceTracker = null; } } /// <summary> /// Updates the face tracking information for this skeleton /// </summary> public void OnFrameReady(KinectSensor kinectSensor, ColorImageFormat colorImageFormat, byte[] colorImage, DepthImageFormat depthImageFormat, short[] depthImage, Skeleton skeletonOfInterest) { this.skeletonTrackingState = skeletonOfInterest.TrackingState; if (this.skeletonTrackingState != SkeletonTrackingState.Tracked) { // nothing to do with an untracked skeleton. return; } if (this.faceTracker == null) { try { this.faceTracker = new FaceTracker(kinectSensor); } catch (InvalidOperationException) { // During some shutdown scenarios the FaceTracker // is unable to be instantiated. Catch that exception // and don't track a face. Debug.WriteLine("AllFramesReady - creating a new FaceTracker threw an InvalidOperationException"); this.faceTracker = null; } } if (this.faceTracker != null) { FaceTrackFrame frame = this.faceTracker.Track( colorImageFormat, colorImage, depthImageFormat, depthImage, skeletonOfInterest); this.lastFaceTrackSucceeded = frame.TrackSuccessful; if (this.lastFaceTrackSucceeded) { if (faceTriangles == null) { // only need to get this once. It doesn't change. faceTriangles = frame.GetTriangles(); } this.facePoints = frame.GetProjected3DShape(); } } } public Coordinates2D? GetFaceCoordinates() { return faceTracker == null ? null : faceTracker.GetFaceCoordinates(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; using Common; using Model.Domain.Common; using Model.Domain.Cost; using MODEL.COST; using System.Data; /// <summary> ///ExpenseUseDataHandler 的摘要说明 /// </summary> public class ExpenseUseDataHandler : IHttpHandler, IRequiresSessionState { BLL.COST.ExpenseUseBLL bll = new BLL.COST.ExpenseUseBLL(); public void ProcessRequest(HttpContext context) { string strType = context.Request["handlerType"];//获取操作类型 if (!string.IsNullOrEmpty(strType)) { switch (strType.ToLower()) { //费用使用列表 case "list": List(context); break; case "single": Single(context); break; case "add": Add(context); break; case "edit": Edit(context); break; case "view": Veiw(context); break; case "delete": Delete(context); break; } } } #region 列表 //列表 private void List(HttpContext context) { IDictionary<string, string> idic = new Dictionary<string, string>(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); int PageSize = int.Parse(context.Request["rows"]); int PageNo = int.Parse(context.Request["page"]); idic.Add("CustName", context.Request["CustName"]);// 客户名称 idic.Add("StartTime", context.Request["StartTime"]);//提交时间起 idic.Add("EndTime", context.Request["EndTime"]);//提交时间止 MODEL.SYSTEM.LoginModel user = Common.CacheHelper.Get<MODEL.SYSTEM.LoginModel>(context.Session["UserID"].ToString()); if (user.UserType == "V")//为客户 { idic.Add("CustId", user.DeptID.ToString());//客户ID } DataSet ds = bll.GetList(PageNo, PageSize, idic); DataTable dtList = ds.Tables[1]; int tatal = int.Parse(ds.Tables[0].Rows[0][0].ToString()); sb.Append("{"); sb.Append("\"total\":" + tatal + ",\"rows\":"); sb.Append("["); int len = dtList.Rows.Count; if (ds != null && len > 0) { for (int i = 0; i < len; i++) { if (i > 0) { sb.Append(","); } sb.Append("{"); sb.Append("\"chk\":\"" + dtList.Rows[i]["ExpenseUseId"].ToString() + "\","); sb.Append("\"rowno\":\"" + (i + 1).ToString() + "\","); sb.Append("\"ExpenseBillNo\":\"" + dtList.Rows[i]["ExpenseBillNo"].ToString() + "\","); sb.Append("\"CustName\":\"" + dtList.Rows[i]["CustName"].ToString() + "\","); sb.Append("\"ExpenseTotal\":\"" + dtList.Rows[i]["ExpenseTotal"].ToString() + "\","); sb.Append("\"CreateTime\":\"" + (dtList.Rows[i]["CreateTime"].ToString() == "" ? "" : DateTime.Parse(dtList.Rows[i]["CreateTime"].ToString()).ToString("yyyy-MM-dd HH:mm")) + "\","); sb.Append("\"edit\":\"" + dtList.Rows[i]["ExpenseUseId"].ToString() + "\""); sb.Append("}"); } } sb.Append("]"); sb.Append("}"); context.Response.Write(sb.ToString()); } #endregion #region 主数据 //添加 private void Add(HttpContext context) { ExpenseUseModel model = new ExpenseUseModel(); model.CreateTime = DateTime.Now; model.CreateUserId = context.Session["UserID"].ToString();//创建人ID model.CustId = int.Parse(context.Request["custId"]);//客户ID model.CustName = context.Request["custName"];//客户姓名 model.ExpenseTotal = double.Parse(context.Request["expenseTotal"]);//费用合计 model.Remark = context.Request["remark"];//备注 model.ExpenseBillNo = BLL.COMMON.CommonBLL.GetBillNo("ExpenseUse", "ExpenseBillNo", "");//单号 string sXml = context.Request["checkMsg"].ToString(); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(sXml); System.Xml.XmlNodeList list1 = doc.SelectNodes("//root//record"); int iLen = list1.Count; int count = 0; for (int i = 0; i < iLen; i++) { if (list1.Item(i)["CheckId"].InnerText.Trim() == "") { count++; } } int[] itemIDs = bll.CreateMaxID("ExpenseUseDetail", count); for (int i = 0, j = 0; i < iLen; i++) { if (list1.Item(i)["CheckId"].InnerText.Trim() == "") { list1.Item(i)["CheckId"].InnerText = itemIDs[j++].ToString(); } } //Todo... bool flag = bll.Insert(model, doc.OuterXml) > 0; HandlerResult result = new HandlerResult(); result.success = flag; result.msg = flag ? "添加成功" : "添加失败"; string jsonResult = JsonHelper.ToJson(result); context.Response.Clear(); context.Response.Write(jsonResult); } //删除 private void Delete(HttpContext context) { HandlerResult result = new HandlerResult(); string ids = context.Request["ID"]; if (!string.IsNullOrWhiteSpace(ids)) { bool flag = bll.Delete(ids) > 0; result.success = flag; result.msg = flag ? "删除成功" : "删除失败"; } string jsonResult = JsonHelper.ToJson(result); context.Response.Clear(); context.Response.Write(jsonResult); } //查询 private void Single(HttpContext context) { string expenseId = context.Request["expenseId"];//部门级别编码 //Todo... ExpenseSetModel model = null;// bll.GetModel(int.Parse(expenseId)); if (model != null) { ExpenseSetEdit edit = new ExpenseSetEdit(); edit.ExpenseId = model.ExpenseId; edit.ExpenseName = model.ExpenseName; edit.Price = model.Price; edit.Unit = model.Unit; string jsonResult = JsonHelper.ToJson(edit); context.Response.Write(jsonResult); } } //修改 private void Edit(HttpContext context) { string hidId = context.Request["hidId"];//主键 ExpenseUseModel model = new ExpenseUseModel(); //model.CreateUserId = context.Session["UserID"].ToString();//创建人ID model.ExpenseUseId = int.Parse(hidId); model.LastModifyTime = DateTime.Now; model.LastModifyUserId = context.Session["UserID"].ToString();//修改人 model.CustId = int.Parse(context.Request["custId"]);//客户ID model.CustName = context.Request["custName"];//客户姓名 model.ExpenseTotal = double.Parse(context.Request["expenseTotal"]);//费用合计 model.Remark = context.Request["remark"];//备注 //model.ExpenseBillNo = BLL.COMMON.CommonBLL.GetBillNo("ExpenseUse", "ExpenseBillNo", "FYZD");//单号 string sXml = context.Request["checkMsg"].ToString(); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(sXml); System.Xml.XmlNodeList list1 = doc.SelectNodes("//root//record"); int iLen = list1.Count; int count = 0; for (int i = 0; i < iLen; i++) { if (list1.Item(i)["CheckId"].InnerText.Trim() == "") { count++; } } int[] itemIDs = bll.CreateMaxID("ExpenseUseDetail", count); for (int i = 0, j = 0; i < iLen; i++) { if (list1.Item(i)["CheckId"].InnerText.Trim() == "") { list1.Item(i)["CheckId"].InnerText = itemIDs[j++].ToString(); } } //Todo... bool flag = bll.Update(model, doc.OuterXml) > 0; HandlerResult result = new HandlerResult(); result.success = flag; result.msg = flag ? "修改成功" : "修改失败"; string jsonResult = JsonHelper.ToJson(result); context.Response.Clear(); context.Response.Write(jsonResult); } //查看 private void Veiw(HttpContext context) { } #endregion public bool IsReusable { get { return false; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Windows.Forms; using Relocation.Data; using Relocation.Com; using Relocation.Com.Tools; using Relocation.UI.Interface; using Relocation.Base; namespace Relocation.UI { public partial class HousesList : HouseListHelp, IPrintForm { #region 构造函数 public HousesList() : base() { InitializeComponent(); Initialize(); } public HousesList(Session session) : base(session) { InitializeComponent(); Initialize(); } #endregion #region 初始化、加载 private void Initialize() { this.BindingSource.DataSourceChanged += new System.EventHandler(this.housesBindingSource_DataSourceChanged); this.S_text_houses_code.Tag = new ControlTag(null, null, new SearchInfo(House.GetPropName(t=>t.house_code))); this.S_text_storeroom.Tag = new ControlTag(null, null, new SearchInfo(House.GetPropName(t => t.storeroom))); this.S_comboBoxDistrict.Tag = new ControlTag(null, null, new SearchInfo(House.GetPropName(t => t.district))); this.S_comboBoxState.Tag = new ControlTag(null, null, new SearchInfo(House.GetPropName(t => t.isUsed), SearchInfo.SearchFieldTypes.Number, new SearchInfo.RanderHandler(delegate(Control control) { if (string.IsNullOrEmpty(control.Text.Trim())) return ""; return control.Text.Equals("未分配") ? "false" : control.Text.Equals("已分配") ? "true" : ""; }), new SearchInfo.ReseterHandler(delegate(Control control) { if (control == null) return; control.Text = "全部"; }))); this.SortField = House.GetPropName(t => t.updated); this.SortDirection = ListSortDirection.Descending; this.ObjectQuery = this.Session.DataModel.Houses.Where("it."+House.GetPropName(t=>t.project_id)+"="+this.Session.Project.project_id.ToString()); this.ObjectQuerySearch = this.ObjectQuery.Where("it." + House.GetPropName(t => t.isUsed) + "=false"); ControlTag roleTag=new ControlTag(new RoleInfo(Session.KEY_ROLE_ADMIN,Session.KEY_ROLE_OPERATOR)); this.ButtonAdd.Tag = roleTag; this.ButtonEdit.Tag = roleTag; this.ButtonDel.Tag = roleTag; } /// 初始化地区下拉框 /// </summary> public void InitComboBox() { try { List<string> districts = this.ObjectQuery.Where(it=>it.district!=null&&it.district!="").OrderBy(t => t.updated).Select(t => t.district).Distinct().ToList(); districts.Insert(0,""); this.S_comboBoxDistrict.DataSource =districts; this.S_comboBoxState.SelectedIndex = 0; } catch (Exception ex) { Log.Error(ex.GetInnerExceptionMessage()); } } /// <summary> /// 窗体加载 /// </summary> private void HousesList_Load(object sender, EventArgs e) { try { InitComboBox(); } catch (Exception ex) { Log.Error(ex.GetInnerExceptionMessage()); } } /// <summary> /// 刷新数据 /// </summary> public override void Refresh() { try { this.Reload(); InitComboBox(); } catch (Exception ex) { Log.Error(ex.GetInnerExceptionMessage()); } } #endregion #region 增、删、改 /// <summary> /// 添加按钮 /// </summary> private void ButtonAdd_Click_1(object sender, EventArgs e) { try { using (HousesWindow window = new HousesWindow(this.Session)) { if (DialogResult.OK.Equals(window.ShowDialog(this))) this.Reload(); } } catch (Exception ex) { Log.Error(ex.GetInnerExceptionMessage()); MyMessagebox.Error("操作失败!"); } } /// <summary> /// 修改按钮 /// </summary> private void ButtonEdit_Click(object sender, EventArgs e) { try { House houses = this.GetSelectEntity(); if (houses != null) { HousesWindow window = new HousesWindow(Session, houses); if (window.ShowDialog(this).IsOK()) { this.Reload(); } } } catch (Exception ex) { Log.Error(ex.GetInnerExceptionMessage()); MyMessagebox.Error(ex); } } /// <summary> /// 删除按钮 /// </summary> private void ButtonDel_Click(object sender, EventArgs e) { try { House houses = this.GetSelectEntity(); if (houses == null) return; if (MyMessagebox.Confirm("您确定要删除吗?").IsYes()) { if (houses.IsUsed()) { MyMessagebox.Show("安置房已被使用,无法删除!"); return; } this.Session.DataModel.Delete(houses); } } catch (Exception ex) { Log.Error(ex.GetInnerExceptionMessage()); MyMessagebox.Error("删除失败!"); } this.Reload(); } #endregion #region DataGridView事件 /// <summary> /// 数据绑定改变(刷新序号) /// </summary> private void housesBindingSource_DataSourceChanged(object sender, EventArgs e) { try { House house = new House(); house.area1 = this.ObjectQuerySearch.Sum(t => t.area1); house.area2 = this.ObjectQuerySearch.Sum(t => t.area2); house.streetArea = this.ObjectQuerySearch.Sum(t => t.streetArea); house.carbarnArea = this.ObjectQuerySearch.Sum(t=>t.carbarnArea); this.BindingSource.Add(house); this.DataGridView.Rows[this.DataGridView.Rows.Count - 1].Cells[this.Column_Index.Name].Value = "总计:"; } catch (Exception ex) { Log.Error(ex.GetInnerExceptionMessage()); } } protected override string Entity2ToolTipText(House entity, string remarkName = "remark") { return base.Entity2ToolTipText(entity, remarkName); } /// <summary> /// 弹出对应拆迁户 /// </summary> private void housesDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e) { try { if (e.RowIndex < 0) return; string dataPropertyName = DataGridView.Columns[e.ColumnIndex].DataPropertyName; if (string.IsNullOrEmpty(dataPropertyName) || !dataPropertyName.Equals(House.GetPropName(t=>t.isUsed))) return; House house = this.GetSelectEntity(); Relocatees_House relocatees_House = house.GetRelocateHouse().FirstOrDefault(); if (relocatees_House == null) return; RelocateesWindow rWindow = new RelocateesWindow(this.Session, relocatees_House.GetRelocate()); rWindow.Text = "安置情况"; rWindow.MinimumSize = new System.Drawing.Size(800, 600); rWindow.LoadEntity(relocatees_House); rWindow.ShowDialog(this); } catch (Exception ex) { Log.Error(ex); MyMessagebox.Error(ex.Message); } } /// <summary> /// 格式化内容 /// </summary> private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { string _name = this.DataGridView.Columns[e.ColumnIndex].Name; if (_name.Equals(this.Column_Index.Name)) { if (e.Value == null) { e.Value = (e.RowIndex + 1).ToString(); e.FormattingApplied = true; } } else if (_name.Equals(this.relocateesHouseDataGridViewTextBoxColumn.Name)) { House house = this.DataGridView.Rows[e.RowIndex].DataBoundItem as House; if (house == null||house.isUsed == false) return; //house.Relocatees_House.Load(); Relocatees_House relocate_House = house.Relocatees_House.FirstOrDefault(); if (relocate_House == null) return; relocate_House.LoadRelocate(); if (relocate_House.Relocatee == null) return; e.Value = relocate_House.Relocatee.head; e.FormattingApplied = true; } else if (_name.Equals(this.isUsedDataGridViewCheckBoxColumn.Name)) { House house = this.DataGridView.Rows[e.RowIndex].DataBoundItem as House; e.Value = house == null ? string.Empty : house.isUsed ? "已分配" : string.Empty; } else if (_name.Equals(this.organizationDataGridViewTextBoxColumn.Name)) { House house = this.DataGridView.Rows[e.RowIndex].DataBoundItem as House; if (house == null || house.isUsed == false) return; Relocatees_House relocate_House = house.Relocatees_House.FirstOrDefault(); if (relocate_House == null) return; relocate_House.LoadRelocate(); if (relocate_House.Relocatee == null) return; e.Value = relocate_House.Relocatee.organization; e.FormattingApplied = true; } } #endregion #region IPrintForm 成员 public void Print() { ExcelHelp.DataGridToExcel(this.DataGridView); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SynchWebService.Entity { public class HrEmployeeITEMEntity: AppHdr { /// <summary> /// 构造函数,不生成主键 /// </summary> public HrEmployeeITEMEntity() : this(false) { } /// <summary> /// 构造函数 /// </summary> /// <param name="isCreateKeyField">是否要创建主键</param> public HrEmployeeITEMEntity(bool isCreateKeyField = false) { } public string Employee_Code { get; set; } public string Employee_Name { get; set; } public int? Avatar_ID2 { get; set; } public int? Sex { get; set; } public string Telphone { get; set; } public string Email { get; set; } public string RegisterAddress { get; set; } public string EmpStatID { get; set; } public string ORGCode { get; set; } public string ORGName { get; set; } public string UORGCode { get; set; } public string UORGName { get; set; } public double? Lv_Num { get; set; } public string Updator { get; set; } public string ID_Number { get; set; } public DateTime? LjDate { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TheLivingRoom { class TriggerPoint { public TriggerPoint() { TriggerSound = null; setID(); } public TriggerPoint(Sound newSound) { TriggerSound = newSound; setID(); } public void Set(Sound newSound) { TriggerSound = newSound; } public bool IsSet() { return (TriggerSound != null); } public bool Clear() { if (TriggerSound == null) return false; TriggerSound = null; return true; } private void setID() { ID = GetHashCode().ToString(); } public Sound TriggerSound { get; set; } public String ID { get; private set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Behaviors.Properties; namespace Behaviors.Selenium { internal class Workspace { private readonly SeleniumContext _context; public Workspace(SeleniumContext context) { _context = context; _context.Driver.Navigate().GoToUrl(Settings.Default.DefaultUrl + "/#/Workspace"); } private WorkItemTree _workItemTree; internal WorkItemTree WorkItemTree { get { return _workItemTree ?? (_workItemTree = new WorkItemTree(_context)); } } } }
using QuanLyQuanCafe.DAO; using QuanLyQuanCafe.DTO; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QuanLyQuanCafe { public partial class FrmLogin : Form { public FrmLogin() { InitializeComponent(); } private void label2_Click(object sender, EventArgs e) { } private void btnLogin_Click(object sender, EventArgs e) { try { string userName = txtTen.Text; string passWord = txtPass.Text; if (Login(userName, passWord)) { //Account loginAccount = AccountDAO.Instance.GetAccountbyUserName(userName); //FrmMain fr = new FrmMain(loginAccount); FrmMain fr = new FrmMain(); this.Hide(); fr.ShowDialog(); this.Show(); } else MessageBox.Show("Sai Tên Tài Khoản Hoặc Mật Khẩu", "Thông Báo !"); } catch{} } public bool Login(string Username, string Password) { return AccountDAO.Instance.Login(Username, Password); } private void FrmLogin_Load(object sender, EventArgs e) { } private void btnExit_Click(object sender, EventArgs e) { this.Close(); } private void FrmLogin_FormClosing(object sender, FormClosingEventArgs e) { if (MessageBox.Show("Bạn muốn thoát chương trình?", "Thông Báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) e.Cancel = true; } private void txtTen_TextChanged(object sender, EventArgs e) { } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Assets.Scripts { public class Player : MonoBehaviour { public int Health = 100; public static bool IsDead = false; public static int Score = 100; public int KillCount = 0; public InventoryManager InventoryManager; public List<AudioSource> gruntingSounds; public AudioSource gruntSound; public List<AudioSource> playerDamagedSounds; public AudioSource playerDamagedSound; public List<AudioSource> playerRemarksOnAlien; public InventoryItem EquippedItem { get { return InventoryManager.activeItem; } } void Start() { StartCoroutine(RegenerateHealth()); } private IEnumerator RegenerateHealth() { while (!IsDead) { if (Health < 100) { Health += 20; yield return new WaitForSeconds(3.5f); } else { yield return null; } } } public void IncreaseScore(bool HitEnemy = false, bool BuiltBarrier = false) { if(HitEnemy) { Score += 15; Debug.Log($"Score is {Score}"); } else if(BuiltBarrier) { // rebuilt a barrier Score += 10; } } public void DecreaseScore(int Amount) { Score -= Amount; Debug.Log($"Score is {Score}"); } public void IncreaseKillCount() { KillCount += 1; // have the player say some random remark about the aliens/house every 8 kills if (KillCount % 8 == 0) { GetRandomPlayerRemarkOnAliens().Play(); } Debug.Log($"Kill count is {KillCount}"); } public void TakeDamage(int damage) { Health -= damage; if(!gruntSound.isPlaying) { gruntSound = GetRandomGrunt(); gruntSound.PlayDelayed(1.5f); } if(!playerDamagedSound.isPlaying) { playerDamagedSound = GetRandomDamagedSound(); playerDamagedSound.PlayDelayed(1f); } if(Health <= 0) { IsDead = true; } } private AudioSource GetRandomGrunt() { return gruntingSounds[Random.Range(0, gruntingSounds.Count)]; } private AudioSource GetRandomDamagedSound() { return playerDamagedSounds[Random.Range(0, playerDamagedSounds.Count)]; } private AudioSource GetRandomPlayerRemarkOnAliens() { return playerRemarksOnAlien[Random.Range(0, playerRemarksOnAlien.Count)]; } } }
using System; namespace RO { public static class CoreEventSingleton<T> where T : CoreEvent, new() { public static readonly T Me = Activator.CreateInstance<T>(); } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using MySQL.Data.EntityFrameworkCore.Extensions; namespace MyConsole { public class Demo { public int Key { get; set; } public int? Id { get; set; } } public class Context : DbContext { public Context(DbContextOptions<Context> options) : base(options) { } public DbSet<Demo> Demos { get; set; } } class Program { private static async Task AsyncCode(Context context) { using (var transaction = context.Database.BeginTransaction()) { var row = await context.Demos.FirstOrDefaultAsync(x => x.Id == 666); if (row == null) { row = new Demo { Id = 666 }; } context.Demos.Add(row); context.SaveChanges(); transaction.Commit(); } } static void Main(string[] args) { var builder = new DbContextOptionsBuilder<Context>() .UseMySQL("server=localhost;user=root;password=root;Database=bugdemo;port=3306;SslMode=None;default command timeout=1800"); var context = new Context(builder.Options); AsyncCode(context).Wait(); } } }
using RestSharp; namespace CloneDeploy_ApiCalls { public class BaseAPI { protected readonly RestRequest Request; protected readonly string Resource; public BaseAPI(string resource) { Request = new RestRequest(); Resource = resource; } } }
using System; using System.Collections.Generic; using PortioningMachine; using PortioningMachine.ItemProviders; using PortioningMachine.SystemComponents; using PortioningMachine.Logger; namespace ProgramController { class Program { static void Main(string[] args) { IControlUnit ctrl = new ControlUnit(new ConsoleLogger(), new RoundRobinAlogrithm(), 10); IItemProvider provider = new ItemProvider(new GaussianDistribution(20, 2)); Machine RoundRobinMachine = new Machine(ctrl, provider); // RoundRobinMachine.start(); IControlUnit ctrl1 = new ControlUnit(new ConsoleLogger(), new ItemScoreAlgo(), 10, new SocreFunc()); IItemProvider provider1 = new ItemProvider(new GaussianDistribution(50, 2)); Machine ScoreItemMachine = new Machine(ctrl1, provider1); ScoreItemMachine.start(); } } }
using System.Diagnostics; using System.Linq; using Chushka.Data; using Microsoft.AspNetCore.Mvc; using Chushka.ViewModels; namespace Chushka.Controllers { public class HomeController : BaseController { public IActionResult Index() { if (this.User.Identity.IsAuthenticated) { var products = this.Db .Products .Select(x => new ShowProductViewModel(x.Id, x.Name, x.Price, x.Description, x.Type.ToString())) .ToList(); return this.View("IndexLoggedIn", products); } return this.View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return this.View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Net.NetworkInformation; using System.Text; namespace ExtMeth.Extensions { static class DateTimeExtensions { public static string ElapsedTime(this DateTime thisObj) { TimeSpan duration = DateTime.Now.Subtract(thisObj); if (duration.TotalHours < 24) { return duration.TotalHours.ToString("F1", CultureInfo.InvariantCulture) + " hours"; } else { return duration.TotalDays.ToString("F2", CultureInfo.InvariantCulture) + " days"; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercice3 { class Program { static void Main(string[] args) { Console.Write("****calculatrice v2 (V1.0, 07 / 07 / 2016) ****"); Console.WriteLine(); double resultat; double saisie; string comb; string deuxcomb; double deuxsaisie; Console.WriteLine("Entrez un chiffre : "); comb = Console.ReadLine(); saisie = Double.Parse(comb); Console.WriteLine("Entrez un deuxieme chiffre : "); deuxcomb = Console.ReadLine(); deuxsaisie = double.Parse(deuxcomb); resultat = saisie / deuxsaisie; Console.Write("resultat " + resultat); Console.WriteLine(); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ParkingLotSimulation { public enum VehicleType { TwoWheelers, FourWheelers, HeavyVehicles }; public class ParkingLotSimulater { public ParkingLot ParkingLot { get; set; } public ParkingLotSimulater(params int[] VehicleCapacities) { this.ParkingLot = new ParkingLot(); this.ParkingLot.CreateSlots(VehicleCapacities); } public void StartSimulation() { while (true) { Console.WriteLine("Select an Option Given Below : "); Console.WriteLine("1) Park Vehicle."); Console.WriteLine("2) Unpark Vehicle"); int.TryParse(Console.ReadLine(), out int selectedOption); switch (selectedOption) { case 1: this.ParkVehicle(); break; case 2: this.UnparkVehicle(); break; default: Console.WriteLine("please enter correct option."); break; } } } public void ParkVehicle() { Console.WriteLine("Select an Option Given Below"); string[] vehicleTypes = Enum.GetNames(typeof(VehicleType)); for (int i = 0; i < vehicleTypes.Length; i++) { Console.WriteLine("{0}) press {0} for {1}", i, vehicleTypes[i]); } int type = Convert.ToInt32(Console.ReadLine().Trim()); if (type >= vehicleTypes.Count()) { Console.WriteLine("\nSorry Slots are not available for your vehicle type.\n"); return; } VehicleType vehicleType = (VehicleType)type; Console.WriteLine("Enter your Vehicle Number : "); String vehicleNumber = Console.ReadLine(); bool[] parkingLotStatus = this.ParkingLot.GetParkingLotStatus(vehicleType); Console.WriteLine("Present Parking Lot Status is : "); int count = 0; foreach (var i in parkingLotStatus) { if (i) Console.WriteLine("{0}) Free", ++count); else Console.WriteLine("{0}) Occupied", ++count); } if (this.ParkingLot.IsSlotAvailable(vehicleType)) { Vehicle vehicle = new Vehicle(vehicleNumber, vehicleType); int slotId = this.ParkingLot.GetAvailableSlotIdToPark(vehicleType); int ticketId = this.ParkingLot.ParkVehicle(vehicle, slotId); this.PrintTicket(ticketId); } else { Console.WriteLine("Sorry our Parking Lot is Full."); } } public void UnparkVehicle() { Console.WriteLine("Enter Your Ticket Number : "); int.TryParse(Console.ReadLine(), out int ticketId); if (this.ParkingLot.UnparkVehicle(ticketId)) { this.PrintTicket(ticketId); } else { Console.WriteLine("This ticket is not valid."); } } public void PrintTicket(int ticketId) { Ticket ticket = this.ParkingLot.GetTicket(ticketId); Console.WriteLine("Your Parking Ticket is :"); Console.WriteLine("Your Ticket Id is : {0}", ticket.Id); Console.WriteLine("Slot Number : {0}", ticket.SlotNumber); Console.WriteLine("Vehicle Number : {0}", ticket.VehicleNumber); Console.WriteLine("Check In Time : {0}", ticket.InTime); Console.WriteLine("Check Out Time : {0}", ticket.OutTime); } } }
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media; using SimpleVisioModels; using SimpleVisioBL; using SimpleVisioDataAccess; namespace SimpleVisioService { public class ShapeService : IShapeService { ISimpleVisio simpleVisio; ISimpleVisioSaver saver; ISimpleVisioLoader loader; public ShapeService(ISimpleVisio simpleVisio, ISimpleVisioLoader loader, ISimpleVisioSaver saver) { this.simpleVisio = simpleVisio; this.loader = loader; this.saver = saver; } public void AddShape(VisioShape shape) { simpleVisio.AddShape(shape); } public void ChangeColor(Guid shapeGuid, Color color) { simpleVisio.ChangeColor(shapeGuid, color); } public void ChangeText(Guid shapeGuid, string text) { simpleVisio.ChangeText(shapeGuid, text); } public void ConnectShapes(Guid parentGuid, Guid childGuid) { simpleVisio.ConnectShapes(parentGuid, childGuid); } public void CopyShape(Guid shapeGuid) { simpleVisio.CopyShape(shapeGuid); } public void DisconnectShapes(Guid childShape) { simpleVisio.DisconnectShapes(childShape); } public List<VisioShape> GetShapes() { return simpleVisio.Shapes; } public List<VisioShape> Load(string diagramName) { simpleVisio.Shapes = loader.Load(diagramName); return simpleVisio.Shapes; } public void MoveShape(Guid shapeGuid, Point newPosition) { simpleVisio.MoveShape(shapeGuid, newPosition); } public void PasteShape(Point position) { simpleVisio.PasteShape(position); } public void Redo() { simpleVisio.Undo(); } public void RemoveShape(Guid shapeGuid) { simpleVisio.RemoveShape(shapeGuid); } public void ResizeShape(Guid shapeGuid, double width, double height) { simpleVisio.ResizeShape(shapeGuid, width, height); } public void Save(string diagramName) { saver.Save(simpleVisio.Shapes, diagramName); } public void Undo() { simpleVisio.Undo(); } public void СutShape(Guid shapeGuid) { simpleVisio.СutShape(shapeGuid); } public void Clear() { simpleVisio.Shapes = new List<VisioShape>(); } } }
using System; using Xunit; namespace IoUring.Tests { public class RingSupportTest { [Fact] public void SmokeTest() { Assert.True(Ring.IsSupported); using var r = new Ring(8); foreach (var i in Enum.GetValues(typeof(RingOperation))) { Assert.True(r.Supports((RingOperation)i), $"{((RingOperation)i).ToString()} not supported"); } } } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Xml.Linq; using System.Linq; using System.Windows.Resources; using System.Collections.Generic; using Tff.Panzer.Models.Scenario; using Tff.Panzer.Models.Campaign; namespace Tff.Panzer.Factories.Campaign { public class CampaignFactory { public List<CampaignInfo> Campaigns { get; private set; } public CampaignBriefingFactory CampaignBriefingFactory { get; set; } public CampaignStepFactory CampaignStepFactory { get; set; } public CampaignStepTypeFactory CampaignStepTypeFactory { get; set; } public CampaignTreeFactory CampaignTreeFactory { get; set; } public CampaignFactory() { Campaigns = new List<CampaignInfo>(); CampaignBriefingFactory = new CampaignBriefingFactory(); CampaignStepFactory = new CampaignStepFactory(); CampaignStepTypeFactory = new CampaignStepTypeFactory(); CampaignTreeFactory = new CampaignTreeFactory(); PopulateCampaigns(); } private void PopulateCampaigns() { Uri uri = new Uri(Constants.CampaignDataPath, UriKind.Relative); XElement applicationXml; StreamResourceInfo xmlStream = Application.GetResourceStream(uri); applicationXml = XElement.Load(xmlStream.Stream); var data = from wz in applicationXml.Descendants("Campaign") select wz; CampaignInfo campaignInfo = null; foreach (var d in data) { campaignInfo = new CampaignInfo(); campaignInfo.CampaignId = (Int32)d.Element("CampaignId"); campaignInfo.CampaignDescription = (String)d.Element("CampaignDescription"); campaignInfo.CampaignName = (String)d.Element("CampaignName"); campaignInfo.CampaignTitle = (String)d.Element("CampaignTitle"); campaignInfo.Nation = Game.NationFactory.GetNation((Int32)d.Element("Nation")); campaignInfo.FreeEliteReplacements = (Boolean)d.Element("FreeEliteReplacement"); campaignInfo.SideId = (Int32)d.Element("Side"); campaignInfo.StartingCampaignStepId = (Int32)d.Element("StartingCampaignStepId"); Campaigns.Add(campaignInfo); } } public CampaignInfo GetCampaignInfo(int campaignId) { CampaignInfo campaignInfo = (from ci in this.Campaigns where ci.CampaignId == campaignId select ci).First(); return campaignInfo; } } }
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling; using Microsoft.Practices.EnterpriseLibrary.Logging; namespace ExceptionHandlingFramework { /// <summary> /// Calss to manage the exception raised in the code /// </summary> public class ExceptionHandlingManager { #region Prvate members private static ExceptionManager exManager; #endregion #region Constructor /// <summary> /// Inititalizes the instance of Exception manager /// </summary>S static ExceptionHandlingManager() { IConfigurationSource config = ConfigurationSourceFactory.Create(); ExceptionPolicyFactory factory = new ExceptionPolicyFactory(config); // Update the logger with the exception handler Logger.SetLogWriter(LoggingManager.Logger); // create the exception manager exManager = factory.CreateManager(); } #endregion #region Singleton instance /// <summary> /// Exception manager /// </summary> public static ExceptionManager Instance { get { return exManager; } } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] public class xAxisLock : MonoBehaviour { public Transform verticalScale; public void xLock() { transform.localScale = new Vector3(0.05f / verticalScale.localScale.x ,transform.localScale.y, 1); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assignment_Part_A { class AssignmentsPerStudent { public Student student; public List<Assignment> assignmentsStudent = new List<Assignment>(); public List<AssignmentsInCourse> assignmentsInCourse { set; get; } = new List<AssignmentsInCourse>(); public AssignmentsPerStudent(Student student, List<Assignment> assignmentsStudent) { this.student = student; this.assignmentsStudent = assignmentsStudent; foreach (var assignment in assignmentsStudent) { assignment.student = student; } student.Assignments = assignmentsStudent; } public void OutputAssignmentsPerStudent() { int i = 1; //αρίθμηση του καθε assignment Console.WriteLine(" "); Console.WriteLine(student.FirstName+" "+student.LastName); Console.WriteLine(); foreach (var assignment in assignmentsStudent) { Console.Write("Assignment "+i+": "); assignment.Output(); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; using System.Threading; namespace Jatsz.MiniHttpServer { public class MiniHttpServer { private int _numOfProcessThread = 1; private int _listenPort = 8080; private Dictionary<string, EventHandler<ContextEventArgs>> _registeredHandlers = new Dictionary<string, EventHandler<ContextEventArgs>>(); private HttpListener listener = new HttpListener(); public MiniHttpServer(int numOfProcessThread, int listenPort) { _numOfProcessThread = numOfProcessThread; _listenPort = listenPort; string prefix = string.Format("http://*:{0}/",_listenPort); listener.Prefixes.Add(prefix); } public MiniHttpServer(int listenPort) :this(1,listenPort) { } public void Start() { if (!HttpListener.IsSupported) throw new NotSupportedException("Windows XP SP2 or Server 2003 is required to use the HttpListener class."); listener.Start(); Console.WriteLine("Listening..."); for (int i = 0; i < _numOfProcessThread; i++) { ThreadPool.QueueUserWorkItem(WorkerThread, listener); } } public void Stop() { listener.Stop(); } public void RegisterHandler(string prefix, EventHandler<ContextEventArgs> handler) { _registeredHandlers.Add(prefix, handler); } private void WorkerThread(object objListener) { HttpListener listener = objListener as HttpListener; while (listener.IsListening) { try { HttpListenerContext context = listener.GetContext(); ProcessRequest(context); } catch (HttpListenerException) { //catch exception when stop listener } } } /// <summary> /// URL dispatch/router /// </summary> /// <param name="context"></param> private void ProcessRequest(HttpListenerContext context) { bool isHandled = false; HttpListenerRequest request = context.Request; foreach (var handler in _registeredHandlers) { if (request.RawUrl.StartsWith(handler.Key)) { handler.Value(this, new ContextEventArgs(context)); isHandled = true; break; //it's been handled, stop propagation } } if (!isHandled) { DefaultHander(context); } } /// <summary> /// Handle URL which do not registered the corresponding handler /// Just return the server time /// </summary> /// <param name="context"></param> private void DefaultHander(HttpListenerContext context) { string html = string.Format("<HTML><BODY> <div>Not Handled:{0}</div> <div>{1}</div></BODY></HTML>", context.Request.RawUrl, DateTime.Now); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(html); HttpListenerResponse response = context.Response; response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); // You must close the output stream. output.Close(); } } }
using Lykke.Service.SmsSender.Core.Domain.SmsRepository; using ProtoBuf; namespace Lykke.Service.SmsSender.Sagas.Events { [ProtoContract] public class SmsMessageDeliveryFailed { [ProtoMember(1)] public SmsMessage Message { get; set; } } }
using System; using Service; using MKModel; using System.Collections.ObjectModel; using ReDefNet; namespace MKService.Updates { internal interface IUpdatableGame : IUpdatable, IGameModel, IQueryResponse { new Guid User1Id { get; set; } new Guid User2Id { get; set; } new Guid Id{ get; set; } new int TurnCount { get; set; } } internal interface IUpdatableGames : IUpdatable, IGameModels, IQueryResponse { new IObservableCollection<IUpdatableGame> Games { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HCL.Academy.Model { public class ExternalUserRequest:RequestBase { public int Id { get; set; } public int EmployeeId { get; set; } public string UserName { get; set; } public string Name { get; set; } public string EncryptedPassword { get; set; } public string Password { get; set; } public string PasswordSalt { get; set; } public int OrganizationId { get; set; } public int GroupId { get; set; } public int RoleId { get; set; } public int SkillId { get; set; } public int CompetencyLevelId { get; set; } public int GEOId { get; set; } } }
using System.Linq; /******************************************/ /* */ /* Copyright (c) 2018 monitor1394 */ /* https://github.com/monitor1394 */ /* */ /******************************************/ using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace XCharts { public static class ChartDrawer { private static UIVertex[] vertex = new UIVertex[4]; private static List<Vector3> s_CurvesPosList = new List<Vector3>(); public static void DrawArrow(VertexHelper vh, Vector3 startPos, Vector3 arrowPos, float width, float height, float offset, float dent, Color32 color) { var dir = (arrowPos - startPos).normalized; var sharpPos = arrowPos + (offset + height / 2) * dir; var middle = sharpPos + (dent - height) * dir; var diff = Vector3.Cross(dir, Vector3.forward).normalized * width / 2; var left = sharpPos - height * dir + diff; var right = sharpPos - height * dir - diff; DrawTriangle(vh, middle, sharpPos, left, color); DrawTriangle(vh, middle, sharpPos, right, color); } public static void DrawLine(VertexHelper vh, Vector3 p1, Vector3 p2, float size, Color32 color) { if (p1 == p2) return; Vector3 v = Vector3.Cross(p2 - p1, Vector3.forward).normalized * size; vertex[0].position = p1 - v; vertex[1].position = p2 - v; vertex[2].position = p2 + v; vertex[3].position = p1 + v; for (int j = 0; j < 4; j++) { vertex[j].color = color; vertex[j].uv0 = Vector2.zero; } vh.AddUIVertexQuad(vertex); } public static void DrawDashLine(VertexHelper vh, Vector3 p1, Vector3 p2, float size, Color32 color, float dashLen = 15f, float blankLen = 7f, List<Vector3> posList = null) { float dist = Vector3.Distance(p1, p2); if (dist < 0.1f) return; int segment = Mathf.CeilToInt(dist / (dashLen + blankLen)); Vector3 dir = (p2 - p1).normalized; Vector3 sp = p1, np; if (posList != null) posList.Clear(); for (int i = 1; i <= segment; i++) { if (posList != null) posList.Add(sp); np = p1 + dir * dist * i / segment; var dashep = np - dir * blankLen; DrawLine(vh, sp, dashep, size, color); sp = np; } if (posList != null) posList.Add(p2); DrawLine(vh, sp, p2, size, color); } public static void DrawDotLine(VertexHelper vh, Vector3 p1, Vector3 p2, float size, Color32 color, float dotLen = 5f, float blankLen = 5f, List<Vector3> posList = null) { float dist = Vector3.Distance(p1, p2); if (dist < 0.1f) return; int segment = Mathf.CeilToInt(dist / (dotLen + blankLen)); Vector3 dir = (p2 - p1).normalized; Vector3 sp = p1, np; if (posList != null) posList.Clear(); for (int i = 1; i <= segment; i++) { if (posList != null) posList.Add(sp); np = p1 + dir * dist * i / segment; var dashep = np - dir * blankLen; DrawLine(vh, sp, dashep, size, color); sp = np; } if (posList != null) posList.Add(p2); DrawLine(vh, sp, p2, size, color); } public static void DrawDashDotLine(VertexHelper vh, Vector3 p1, Vector3 p2, float size, Color32 color, float dashLen = 15f, float blankDotLen = 15f, List<Vector3> posList = null) { float dist = Vector3.Distance(p1, p2); if (dist < 0.1f) return; int segment = Mathf.CeilToInt(dist / (dashLen + blankDotLen)); Vector3 dir = (p2 - p1).normalized; Vector3 sp = p1, np; if (posList != null) posList.Clear(); for (int i = 1; i <= segment; i++) { if (posList != null) posList.Add(sp); np = p1 + dir * dist * i / segment; var dashep = np - dir * blankDotLen; DrawLine(vh, sp, dashep, size, color); if (posList != null) posList.Add(dashep); var dotsp = dashep + (blankDotLen - 2 * size) / 2 * dir; var dotep = dotsp + 2 * size * dir; DrawLine(vh, dotsp, dotep, size, color); if (posList != null) posList.Add(dotsp); sp = np; } if (posList != null) posList.Add(p2); DrawLine(vh, sp, p2, size, color); } public static void DrawDashDotDotLine(VertexHelper vh, Vector3 p1, Vector3 p2, float size, Color32 color, float dashLen = 15f, float blankDotLen = 20f, List<Vector3> posList = null) { float dist = Vector3.Distance(p1, p2); if (dist < 0.1f) return; int segment = Mathf.CeilToInt(dist / (dashLen + blankDotLen)); Vector3 dir = (p2 - p1).normalized; Vector3 sp = p1, np; if (posList != null) posList.Clear(); for (int i = 1; i <= segment; i++) { if (posList != null) posList.Add(sp); np = p1 + dir * dist * i / segment; var dashep = np - dir * blankDotLen; DrawLine(vh, sp, dashep, size, color); if (posList != null) posList.Add(dashep); var dotsp = dashep + (blankDotLen / 2 - 2 * size) / 2 * dir; var dotep = dotsp + 2 * size * dir; DrawLine(vh, dotsp, dotep, size, color); if (posList != null) posList.Add(dotep); var dotsp2 = dashep + blankDotLen / 2 * dir; dotsp2 = dotsp2 + (blankDotLen / 4 - 2 * size) / 2 * dir; var dotep2 = dotsp2 + 2 * size * dir; DrawLine(vh, dotsp2, dotep2, size, color); if (posList != null) posList.Add(dotep2); sp = np; } if (posList != null) posList.Add(p2); DrawLine(vh, sp, p2, size, color); } public static void DrawZebraLine(VertexHelper vh, Vector3 p1, Vector3 p2, float size, float zebraWidth, float zebraGap, Color32 color) { DrawDotLine(vh, p1, p2, size, color, zebraWidth, zebraGap); } public static void DrawDiamond(VertexHelper vh, Vector3 pos, float size, Color32 color) { DrawDiamond(vh, pos, size, color, color); } public static void DrawDiamond(VertexHelper vh, Vector3 pos, float size, Color32 color, Color32 toColor) { var p1 = new Vector2(pos.x - size, pos.y); var p2 = new Vector2(pos.x, pos.y + size); var p3 = new Vector2(pos.x + size, pos.y); var p4 = new Vector2(pos.x, pos.y - size); DrawTriangle(vh, p4, p1, p2, color, color, toColor); DrawTriangle(vh, p3, p4, p2, color, color, toColor); } public static void DrawPolygon(VertexHelper vh, Vector3 p, float radius, Color32 color, bool vertical = true) { DrawPolygon(vh, p, radius, color, color, vertical); } public static void DrawPolygon(VertexHelper vh, Vector3 p, float radius, Color32 color, Color32 toColor, bool vertical = true) { Vector3 p1, p2, p3, p4; if (vertical) { p1 = new Vector3(p.x + radius, p.y - radius); p2 = new Vector3(p.x - radius, p.y - radius); p3 = new Vector3(p.x - radius, p.y + radius); p4 = new Vector3(p.x + radius, p.y + radius); } else { p1 = new Vector3(p.x - radius, p.y - radius); p2 = new Vector3(p.x - radius, p.y + radius); p3 = new Vector3(p.x + radius, p.y + radius); p4 = new Vector3(p.x + radius, p.y - radius); } DrawPolygon(vh, p1, p2, p3, p4, color, toColor); } public static void DrawPolygon(VertexHelper vh, Vector3 p1, Vector3 p2, float radius, Color32 color) { DrawPolygon(vh, p1, p2, radius, color, color); } public static void DrawPolygon(VertexHelper vh, Vector3 p1, Vector3 p2, float radius, Color32 color, Color32 toColor) { var dir = (p2 - p1).normalized; var dirv = Vector3.Cross(dir, Vector3.forward).normalized; var p3 = p1 + dirv * radius; var p4 = p1 - dirv * radius; var p5 = p2 - dirv * radius; var p6 = p2 + dirv * radius; DrawPolygon(vh, p3, p4, p5, p6, color, toColor); } public static void DrawPolygon(VertexHelper vh, Vector3 p, float xRadius, float yRadius, Color32 color, bool vertical = true) { DrawPolygon(vh, p, xRadius, yRadius, color, color, vertical); } public static void DrawPolygon(VertexHelper vh, Vector3 p, float xRadius, float yRadius, Color32 color, Color toColor, bool vertical = true) { Vector3 p1, p2, p3, p4; if (vertical) { p1 = new Vector3(p.x + xRadius, p.y - yRadius); p2 = new Vector3(p.x - xRadius, p.y - yRadius); p3 = new Vector3(p.x - xRadius, p.y + yRadius); p4 = new Vector3(p.x + xRadius, p.y + yRadius); } else { p1 = new Vector3(p.x - xRadius, p.y - yRadius); p2 = new Vector3(p.x - xRadius, p.y + yRadius); p3 = new Vector3(p.x + xRadius, p.y + yRadius); p4 = new Vector3(p.x + xRadius, p.y - yRadius); } DrawPolygon(vh, p1, p2, p3, p4, color, toColor); } public static void DrawPolygon(VertexHelper vh, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4, Color32 color) { DrawPolygon(vh, p1, p2, p3, p4, color, color); } public static void DrawPolygon(VertexHelper vh, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4, Color32 startColor, Color32 toColor) { vertex[0].position = p1; vertex[1].position = p2; vertex[2].position = p3; vertex[3].position = p4; for (int j = 0; j < 4; j++) { vertex[j].color = j >= 2 ? toColor : startColor; vertex[j].uv0 = Vector2.zero; } vh.AddUIVertexQuad(vertex); } private static void InitCornerRadius(float[] cornerRadius, float width, float height, ref float brLt, ref float brRt, ref float brRb, ref float brLb, ref bool needRound) { brLt = cornerRadius != null && cornerRadius.Length > 0 ? cornerRadius[0] : 0; brRt = cornerRadius != null && cornerRadius.Length > 1 ? cornerRadius[1] : 0; brRb = cornerRadius != null && cornerRadius.Length > 2 ? cornerRadius[2] : 0; brLb = cornerRadius != null && cornerRadius.Length > 3 ? cornerRadius[3] : 0; needRound = brLb != 0 || brRt != 0 || brRb != 0 || brLb != 0; if (needRound) { if (brLt + brRt > width) { var total = brLt + brRt; brLt = width * (brLt / total); brRt = width * (brRt / total); } if (brRt + brRb > height) { var total = brRt + brRb; brRt = height * (brRt / total); brRb = height * (brRb / total); } if (brRb + brLb > width) { var total = brRb + brLb; brRb = width * (brRb / total); brLb = width * (brLb / total); } if (brLb + brLt > height) { var total = brLb + brLt; brLb = height * (brLb / total); brLt = height * (brLt / total); } if (brLt + brRb > height) { var total = brLt + brRb; brLt = height * (brLt / total); brRb = height * (brRb / total); } if (brRt + brLb > height) { var total = brRt + brRt; brRt = height * (brRt / total); brLb = height * (brLb / total); } } } /// <summary> /// 绘制圆角矩形 /// </summary> /// <param name="vh"></param> /// <param name="center"></param> /// <param name="rectWidth"></param> /// <param name="rectHeight"></param> /// <param name="color"></param> /// <param name="rotate"></param> /// <param name="cornerRadius"></param> public static void DrawRoundRectangle(VertexHelper vh, Vector3 center, float rectWidth, float rectHeight, Color32 color, float rotate = 0, float[] cornerRadius = null) { var halfWid = rectWidth / 2; var halfHig = rectHeight / 2; float brLt = 0, brRt = 0, brRb = 0, brLb = 0; bool needRound = false; InitCornerRadius(cornerRadius, rectWidth, rectHeight, ref brLt, ref brRt, ref brRb, ref brLb, ref needRound); var tempCenter = Vector3.zero; var lbIn = new Vector3(center.x - halfWid, center.y - halfHig); var ltIn = new Vector3(center.x - halfWid, center.y + halfHig); var rtIn = new Vector3(center.x + halfWid, center.y + halfHig); var rbIn = new Vector3(center.x + halfWid, center.y - halfHig); if (needRound) { var lbIn2 = lbIn; var ltIn2 = ltIn; var rtIn2 = rtIn; var rbIn2 = rbIn; var roundLb = lbIn; var roundLt = ltIn; var roundRt = rtIn; var roundRb = rbIn; if (brLt > 0) { roundLt = new Vector3(center.x - halfWid + brLt, center.y + halfHig - brLt); DrawSector(vh, roundLt, brLt, color, color, 270, 360); ltIn = roundLt + brLt * Vector3.left; ltIn2 = roundLt + brLt * Vector3.up; } if (brRt > 0) { roundRt = new Vector3(center.x + halfWid - brRt, center.y + halfHig - brRt); DrawSector(vh, roundRt, brRt, color, color, 0, 90); rtIn = roundRt + brRt * Vector3.up; rtIn2 = roundRt + brRt * Vector3.right; } if (brRb > 0) { roundRb = new Vector3(center.x + halfWid - brRb, center.y - halfHig + brRb); DrawSector(vh, roundRb, brRb, color, color, 90, 180); rbIn = roundRb + brRb * Vector3.right; rbIn2 = roundRb + brRb * Vector3.down; } if (brLb > 0) { roundLb = new Vector3(center.x - halfWid + brLb, center.y - halfHig + brLb); DrawSector(vh, roundLb, brLb, color, color, 180, 270); lbIn = roundLb + brLb * Vector3.left; lbIn2 = roundLb + brLb * Vector3.down; } var maxup = Mathf.Max(brLt, brRt); DrawPolygon(vh, ltIn2, rtIn, rtIn + maxup * Vector3.down, ltIn2 + maxup * Vector3.down, color); DrawPolygon(vh, ltIn, roundLt, roundLt + (maxup - brLt) * Vector3.down, ltIn + (maxup - brLt) * Vector3.down, color); DrawPolygon(vh, roundRt, rtIn2, rtIn2 + (maxup - brRt) * Vector3.down, roundRt + (maxup - brRt) * Vector3.down, color); var maxdown = Mathf.Max(brLb, brRb); DrawPolygon(vh, lbIn2, lbIn2 + maxdown * Vector3.up, rbIn2 + maxdown * Vector3.up, rbIn2, color); DrawPolygon(vh, lbIn, lbIn + (maxdown - brLb) * Vector3.up, roundLb + (maxdown - brLb) * Vector3.up, roundLb, color); DrawPolygon(vh, roundRb, roundRb + (maxdown - brRb) * Vector3.up, rbIn2 + (maxdown - brRb) * Vector3.up, rbIn2, color); var clt = new Vector3(center.x - halfWid, center.y + halfHig - maxup); var crt = new Vector3(center.x + halfWid, center.y + halfHig - maxup); var crb = new Vector3(center.x + halfWid, center.y - halfHig + maxdown); var clb = new Vector3(center.x - halfWid, center.y - halfHig + maxdown); if (clt.y > clb.y) DrawPolygon(vh, clt, crt, crb, clb, color); } else { DrawPolygon(vh, lbIn, ltIn, rtIn, rbIn, color); } } /// <summary> /// 绘制(圆角)边框 /// </summary> /// <param name="vh"></param> /// <param name="center"></param> /// <param name="rectWidth"></param> /// <param name="rectHeight"></param> /// <param name="borderWidth"></param> /// <param name="color"></param> /// <param name="rotate"></param> /// <param name="cornerRadius"></param> public static void DrawBorder(VertexHelper vh, Vector3 center, float rectWidth, float rectHeight, float borderWidth, Color32 color, float rotate = 0, float[] cornerRadius = null) { if (borderWidth == 0 || color == Color.clear) return; var halfWid = rectWidth / 2; var halfHig = rectHeight / 2; var lbIn = new Vector3(center.x - halfWid, center.y - halfHig); var lbOt = new Vector3(center.x - halfWid - borderWidth, center.y - halfHig - borderWidth); var ltIn = new Vector3(center.x - halfWid, center.y + halfHig); var ltOt = new Vector3(center.x - halfWid - borderWidth, center.y + halfHig + borderWidth); var rtIn = new Vector3(center.x + halfWid, center.y + halfHig); var rtOt = new Vector3(center.x + halfWid + borderWidth, center.y + halfHig + borderWidth); var rbIn = new Vector3(center.x + halfWid, center.y - halfHig); var rbOt = new Vector3(center.x + halfWid + borderWidth, center.y - halfHig - borderWidth); float brLt = 0, brRt = 0, brRb = 0, brLb = 0; bool needRound = false; InitCornerRadius(cornerRadius, rectWidth, rectHeight, ref brLt, ref brRt, ref brRb, ref brLb, ref needRound); var tempCenter = Vector3.zero; if (needRound) { var lbIn2 = lbIn; var lbOt2 = lbOt; var ltIn2 = ltIn; var ltOt2 = ltOt; var rtIn2 = rtIn; var rtOt2 = rtOt; var rbIn2 = rbIn; var rbOt2 = rbOt; if (brLt > 0) { tempCenter = new Vector3(center.x - halfWid + brLt, center.y + halfHig - brLt); DrawDoughnut(vh, tempCenter, brLt, brLt + borderWidth, color, Color.clear, 270, 360); ltIn = tempCenter + brLt * Vector3.left; ltOt = tempCenter + (brLt + borderWidth) * Vector3.left; ltIn2 = tempCenter + brLt * Vector3.up; ltOt2 = tempCenter + (brLt + borderWidth) * Vector3.up; } if (brRt > 0) { tempCenter = new Vector3(center.x + halfWid - brRt, center.y + halfHig - brRt); DrawDoughnut(vh, tempCenter, brRt, brRt + borderWidth, color, Color.clear, 0, 90); rtIn = tempCenter + brRt * Vector3.up; rtOt = tempCenter + (brRt + borderWidth) * Vector3.up; rtIn2 = tempCenter + brRt * Vector3.right; rtOt2 = tempCenter + (brRt + borderWidth) * Vector3.right; } if (brRb > 0) { tempCenter = new Vector3(center.x + halfWid - brRb, center.y - halfHig + brRb); DrawDoughnut(vh, tempCenter, brRb, brRb + borderWidth, color, Color.clear, 90, 180); rbIn = tempCenter + brRb * Vector3.right; rbOt = tempCenter + (brRb + borderWidth) * Vector3.right; rbIn2 = tempCenter + brRb * Vector3.down; rbOt2 = tempCenter + (brRb + borderWidth) * Vector3.down; } if (brLb > 0) { tempCenter = new Vector3(center.x - halfWid + brLb, center.y - halfHig + brLb); DrawDoughnut(vh, tempCenter, brLb, brLb + borderWidth, color, Color.clear, 180, 270); lbIn = tempCenter + brLb * Vector3.left; lbOt = tempCenter + (brLb + borderWidth) * Vector3.left; lbIn2 = tempCenter + brLb * Vector3.down; lbOt2 = tempCenter + (brLb + borderWidth) * Vector3.down; } DrawPolygon(vh, lbIn, lbOt, ltOt, ltIn, color); DrawPolygon(vh, ltIn2, ltOt2, rtOt, rtIn, color); DrawPolygon(vh, rtIn2, rtOt2, rbOt, rbIn, color); DrawPolygon(vh, rbIn2, rbOt2, lbOt2, lbIn2, color); } else { if (rotate > 0) { lbIn = ChartHelper.RotateRound(lbIn, center, Vector3.forward, rotate); lbOt = ChartHelper.RotateRound(lbOt, center, Vector3.forward, rotate); ltIn = ChartHelper.RotateRound(ltIn, center, Vector3.forward, rotate); ltOt = ChartHelper.RotateRound(ltOt, center, Vector3.forward, rotate); rtIn = ChartHelper.RotateRound(rtIn, center, Vector3.forward, rotate); rtOt = ChartHelper.RotateRound(rtOt, center, Vector3.forward, rotate); rbIn = ChartHelper.RotateRound(rbIn, center, Vector3.forward, rotate); rbOt = ChartHelper.RotateRound(rbOt, center, Vector3.forward, rotate); } DrawPolygon(vh, lbIn, lbOt, ltOt, ltIn, color); DrawPolygon(vh, ltIn, ltOt, rtOt, rtIn, color); DrawPolygon(vh, rtIn, rtOt, rbOt, rbIn, color); DrawPolygon(vh, rbIn, rbOt, lbOt, lbIn, color); } } public static void DrawTriangle(VertexHelper vh, Vector3 p1, Vector3 p2, Vector3 p3, Color32 color) { DrawTriangle(vh, p1, p2, p3, color, color, color); } public static void DrawTriangle(VertexHelper vh, Vector3 pos, float size, Color32 color) { DrawTriangle(vh, pos, size, color, color); } public static void DrawTriangle(VertexHelper vh, Vector3 pos, float size, Color32 color, Color32 toColor) { var x = size * Mathf.Cos(30 * Mathf.PI / 180); var y = size * Mathf.Sin(30 * Mathf.PI / 180); var p1 = new Vector2(pos.x - x, pos.y - y); var p2 = new Vector2(pos.x, pos.y + size); var p3 = new Vector2(pos.x + x, pos.y - y); ChartDrawer.DrawTriangle(vh, p1, p2, p3, color, toColor, color); } public static void DrawTriangle(VertexHelper vh, Vector3 p1, Vector3 p2, Vector3 p3, Color32 color, Color32 color2, Color32 color3) { UIVertex v1 = new UIVertex(); v1.position = p1; v1.color = color; v1.uv0 = Vector3.zero; UIVertex v2 = new UIVertex(); v2.position = p2; v2.color = color2; v2.uv0 = Vector3.zero; UIVertex v3 = new UIVertex(); v3.position = p3; v3.color = color3; v3.uv0 = Vector3.zero; int startIndex = vh.currentVertCount; vh.AddVert(v1); vh.AddVert(v2); vh.AddVert(v3); vh.AddTriangle(startIndex, startIndex + 1, startIndex + 2); } public static void DrawCricle(VertexHelper vh, Vector3 p, float radius, Color32 color, float smoothness = 2f) { DrawCricle(vh, p, radius, color, color, 0, Color.clear, smoothness); } public static void DrawCricle(VertexHelper vh, Vector3 p, float radius, Color32 color, Color32 toColor, float smoothness = 2f) { DrawSector(vh, p, radius, color, toColor, 0, 360, 0, Color.clear, smoothness); } public static void DrawCricle(VertexHelper vh, Vector3 p, float radius, Color32 color, Color32 toColor, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawSector(vh, p, radius, color, toColor, 0, 360, borderWidth, borderColor, smoothness); } public static void DrawCricle(VertexHelper vh, Vector3 p, float radius, Color32 color, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawCricle(vh, p, radius, color, color, borderWidth, borderColor, smoothness); } public static void DrawEmptyCricle(VertexHelper vh, Vector3 p, float radius, float tickness, Color32 color, Color32 emptyColor, float smoothness = 2f) { DrawDoughnut(vh, p, radius - tickness, radius, color, color, emptyColor, 0, 360, 0, Color.clear, 0, smoothness); } public static void DrawEmptyCricle(VertexHelper vh, Vector3 p, float radius, float tickness, Color32 color, Color32 emptyColor, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawDoughnut(vh, p, radius - tickness, radius, color, color, emptyColor, 0, 360, borderWidth, borderColor, 0, smoothness); } public static void DrawEmptyCricle(VertexHelper vh, Vector3 p, float radius, float tickness, Color32 color, Color32 toColor, Color32 emptyColor, float smoothness = 2f) { DrawDoughnut(vh, p, radius - tickness, radius, color, toColor, emptyColor, 0, 360, 0, Color.clear, 0, smoothness); } public static void DrawEmptyCricle(VertexHelper vh, Vector3 p, float radius, float tickness, Color32 color, Color32 toColor, Color32 emptyColor, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawDoughnut(vh, p, radius - tickness, radius, color, toColor, emptyColor, 0, 360, borderWidth, borderColor, 0, smoothness); } public static void DrawSector(VertexHelper vh, Vector3 p, float radius, Color32 color, float startDegree, float toDegree, float smoothness = 2f) { DrawSector(vh, p, radius, color, color, startDegree, toDegree, 0, Color.clear, smoothness); } public static void DrawSector(VertexHelper vh, Vector3 p, float radius, Color32 color, Color32 toColor, float startDegree, float toDegree, float smoothness = 2f) { DrawSector(vh, p, radius, color, toColor, startDegree, toDegree, 0, Color.clear, smoothness); } public static void DrawSector(VertexHelper vh, Vector3 p, float radius, Color32 color, float startDegree, float toDegree, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawSector(vh, p, radius, color, color, startDegree, toDegree, borderWidth, borderColor, smoothness); } public static void DrawSector(VertexHelper vh, Vector3 p, float radius, Color32 color, Color32 toColor, float startDegree, float toDegree, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawSector(vh, p, radius, color, toColor, startDegree, toDegree, borderWidth, borderColor, 0, smoothness); } public static void DrawSector(VertexHelper vh, Vector3 p, float radius, Color32 color, Color32 toColor, float startDegree, float toDegree, float borderWidth, Color32 borderColor, float space, float smoothness = 2f) { radius -= borderWidth; smoothness = (smoothness < 0 ? 2f : smoothness); int segments = (int)((2 * Mathf.PI * radius) * (Mathf.Abs(toDegree - startDegree) / 360) / smoothness); float startAngle = startDegree * Mathf.Deg2Rad; float toAngle = toDegree * Mathf.Deg2Rad; float realStartAngle = startAngle; float realToAngle = toAngle; float halfAngle = (toAngle - startAngle) / 2; float borderAngle = 0; float spaceAngle = 0; var p2 = p + radius * GetDire(startAngle); var p3 = Vector3.zero; var spaceCenter = p; var realCenter = p; var needBorder = borderWidth != 0; var needSpace = space != 0; var lastPos = Vector3.zero; var middleDire = GetDire(startAngle + halfAngle); if (needBorder || needSpace) { float spaceDiff = 0f; float borderDiff = 0f; if (needSpace) { spaceDiff = space / Mathf.Sin(halfAngle); spaceCenter = p + spaceDiff * middleDire; realCenter = spaceCenter; spaceAngle = 2 * Mathf.Asin(space / (2 * radius)); realStartAngle = startAngle + spaceAngle; realToAngle = toAngle - spaceAngle; p2 = GetPos(p, radius, realStartAngle); } if (needBorder) { borderDiff = borderWidth / Mathf.Sin(halfAngle); realCenter += borderDiff * middleDire; borderAngle = 2 * Mathf.Asin(borderWidth / (2 * radius)); realStartAngle = realStartAngle + borderAngle; var borderX1 = GetPos(p, radius, realStartAngle); DrawPolygon(vh, realCenter, spaceCenter, p2, borderX1, borderColor); p2 = borderX1; realToAngle = realToAngle - borderAngle; var borderX2 = GetPos(p, radius, realToAngle); var pEnd = GetPos(p, radius, toAngle - spaceAngle); DrawPolygon(vh, realCenter, borderX2, pEnd, spaceCenter, borderColor); } } float segmentAngle = (realToAngle - realStartAngle) / segments; for (int i = 0; i <= segments; i++) { float currAngle = realStartAngle + i * segmentAngle; p3 = p + radius * GetDire(currAngle); DrawTriangle(vh, realCenter, p2, p3, toColor, color, color); p2 = p3; } if (needBorder || needSpace) { var borderX2 = p + radius * GetDire(realToAngle); DrawTriangle(vh, realCenter, p2, borderX2, toColor, color, color); if (needBorder) { var realStartDegree = (realStartAngle - borderAngle) * Mathf.Rad2Deg; var realToDegree = (realToAngle + borderAngle) * Mathf.Rad2Deg; DrawDoughnut(vh, p, radius, radius + borderWidth, borderColor, Color.clear, realStartDegree, realToDegree, smoothness); } } } private static Vector3 GetPos(Vector3 center, float radius, float angle, bool isDegree = false) { angle = isDegree ? angle * Mathf.Deg2Rad : angle; return new Vector3(center.x + radius * Mathf.Sin(angle), center.y + radius * Mathf.Cos(angle)); } private static Vector3 GetDire(float angle, bool isDegree = false) { angle = isDegree ? angle * Mathf.Deg2Rad : angle; return new Vector3(Mathf.Sin(angle), Mathf.Cos(angle)); } public static void DrawRoundCap(VertexHelper vh, Vector3 center, float width, float radius, float angle, bool clockwise, Color color, bool end) { var px = Mathf.Sin(angle * Mathf.Deg2Rad) * radius; var py = Mathf.Cos(angle * Mathf.Deg2Rad) * radius; var pos = new Vector3(px, py) + center; if (end) { if (clockwise) ChartDrawer.DrawSector(vh, pos, width, color, angle, angle + 180, 0, Color.clear); else ChartDrawer.DrawSector(vh, pos, width, color, angle, angle - 180, 0, Color.clear); } else { if (clockwise) ChartDrawer.DrawSector(vh, pos, width, color, angle + 180, angle + 360, 0, Color.clear); else ChartDrawer.DrawSector(vh, pos, width, color, angle - 180, angle - 360, 0, Color.clear); } } public static void DrawDoughnut(VertexHelper vh, Vector3 p, float insideRadius, float outsideRadius, Color32 color, Color emptyColor, float smoothness = 2f) { DrawDoughnut(vh, p, insideRadius, outsideRadius, color, color, emptyColor, 0, 360, 0, Color.clear, 0, smoothness); } public static void DrawDoughnut(VertexHelper vh, Vector3 p, float insideRadius, float outsideRadius, Color32 color, Color emptyColor, float startDegree, float toDegree, float smoothness = 2f) { DrawDoughnut(vh, p, insideRadius, outsideRadius, color, color, emptyColor, startDegree, toDegree, 0, Color.clear, 0, smoothness); } public static void DrawDoughnut(VertexHelper vh, Vector3 p, float insideRadius, float outsideRadius, Color32 color, Color emptyColor, float startDegree, float toDegree, float borderWidth, Color32 borderColor, float smoothness = 2f) { DrawDoughnut(vh, p, insideRadius, outsideRadius, color, color, emptyColor, startDegree, toDegree, borderWidth, borderColor, 0, smoothness); } public static void DrawDoughnut(VertexHelper vh, Vector3 p, float insideRadius, float outsideRadius, Color32 color, Color32 toColor, Color emptyColor, float smoothness = 2f) { DrawDoughnut(vh, p, insideRadius, outsideRadius, color, toColor, emptyColor, 0, 360, 0, Color.clear, 0, smoothness); } public static void DrawDoughnut(VertexHelper vh, Vector3 p, float insideRadius, float outsideRadius, Color32 color, Color32 toColor, Color emptyColor, float startDegree, float toDegree, float borderWidth, Color32 borderColor, float space, float smoothness, bool roundCap = false, bool clockwise = true) { if (toDegree - startDegree == 0) return; if (insideRadius <= 0) { DrawSector(vh, p, outsideRadius, color, toColor, startDegree, toDegree, borderWidth, borderColor, space, smoothness); return; } outsideRadius -= borderWidth; insideRadius += borderWidth; smoothness = smoothness < 0 ? 2f : smoothness; Vector3 p1, p2, p3, p4, e1, e2; var needBorder = borderWidth != 0; var needSpace = space != 0; var diffAngle = Mathf.Abs(toDegree - startDegree) * Mathf.Deg2Rad; int segments = (int)((2 * Mathf.PI * outsideRadius) * (diffAngle * Mathf.Rad2Deg / 360) / smoothness); float startAngle = startDegree * Mathf.Deg2Rad; float toAngle = toDegree * Mathf.Deg2Rad; float realStartOutAngle = startAngle; float realToOutAngle = toAngle; float realStartInAngle = startAngle; float realToInAngle = toAngle; float halfAngle = (toAngle - startAngle) / 2; float borderAngle = 0, borderInAngle = 0, borderHalfAngle = 0; float spaceAngle = 0, spaceInAngle = 0, spaceHalfAngle = 0; var spaceCenter = p; var realCenter = p; var startDire = new Vector3(Mathf.Sin(startAngle), Mathf.Cos(startAngle)).normalized; var toDire = new Vector3(Mathf.Sin(toAngle), Mathf.Cos(toAngle)).normalized; var middleDire = new Vector3(Mathf.Sin(startAngle + halfAngle), Mathf.Cos(startAngle + halfAngle)).normalized; p1 = p + insideRadius * startDire; p2 = p + outsideRadius * startDire; e1 = p + insideRadius * toDire; e2 = p + outsideRadius * toDire; if (roundCap) { var roundRadius = (outsideRadius - insideRadius) / 2; var roundAngleRadius = insideRadius + roundRadius; var roundAngle = Mathf.Atan(roundRadius / roundAngleRadius); if (diffAngle < 2 * roundAngle) { roundCap = false; } } if (needBorder || needSpace) { if (needSpace) { var spaceDiff = space / Mathf.Sin(halfAngle); spaceCenter = p + Mathf.Abs(spaceDiff) * middleDire; realCenter = spaceCenter; spaceAngle = 2 * Mathf.Asin(space / (2 * outsideRadius)); spaceInAngle = 2 * Mathf.Asin(space / (2 * insideRadius)); spaceHalfAngle = 2 * Mathf.Asin(space / (2 * (insideRadius + (outsideRadius - insideRadius) / 2))); if (clockwise) { p1 = GetPos(p, insideRadius, startAngle + spaceInAngle, false); e1 = GetPos(p, insideRadius, toAngle - spaceInAngle, false); realStartOutAngle = startAngle + spaceAngle; realToOutAngle = toAngle - spaceAngle; realStartInAngle = startAngle + spaceInAngle; realToInAngle = toAngle - spaceInAngle; } else { p1 = GetPos(p, insideRadius, startAngle - spaceInAngle, false); e1 = GetPos(p, insideRadius, toAngle + spaceInAngle, false); realStartOutAngle = startAngle - spaceAngle; realToOutAngle = toAngle + spaceAngle; realStartInAngle = startAngle - spaceInAngle; realToOutAngle = toAngle + spaceInAngle; } p2 = GetPos(p, outsideRadius, realStartOutAngle, false); e2 = GetPos(p, outsideRadius, realToOutAngle, false); } if (needBorder) { var borderDiff = borderWidth / Mathf.Sin(halfAngle); realCenter += Mathf.Abs(borderDiff) * middleDire; borderAngle = 2 * Mathf.Asin(borderWidth / (2 * outsideRadius)); borderInAngle = 2 * Mathf.Asin(borderWidth / (2 * insideRadius)); borderHalfAngle = 2 * Mathf.Asin(borderWidth / (2 * (insideRadius + (outsideRadius - insideRadius) / 2))); if (clockwise) { realStartOutAngle = realStartOutAngle + borderAngle; realToOutAngle = realToOutAngle - borderAngle; realStartInAngle = startAngle + spaceInAngle + borderInAngle; realToInAngle = toAngle - spaceInAngle - borderInAngle; var newp1 = GetPos(p, insideRadius, startAngle + spaceInAngle + borderInAngle, false); var newp2 = GetPos(p, outsideRadius, realStartOutAngle, false); if (!roundCap) DrawPolygon(vh, newp2, newp1, p1, p2, borderColor); p1 = newp1; p2 = newp2; if (toAngle - spaceInAngle - 2 * borderInAngle > realStartOutAngle) { var newe1 = GetPos(p, insideRadius, toAngle - spaceInAngle - borderInAngle, false); var newe2 = GetPos(p, outsideRadius, realToOutAngle, false); if (!roundCap) DrawPolygon(vh, newe2, e2, e1, newe1, borderColor); e1 = newe1; e2 = newe2; } } else { realStartOutAngle = realStartOutAngle - borderAngle; realToOutAngle = realToOutAngle + borderAngle; realStartInAngle = startAngle - spaceInAngle - borderInAngle; realToInAngle = toAngle + spaceInAngle + borderInAngle; var newp1 = GetPos(p, insideRadius, startAngle - spaceInAngle - borderInAngle, false); var newp2 = GetPos(p, outsideRadius, realStartOutAngle, false); if (!roundCap) DrawPolygon(vh, newp2, newp1, p1, p2, borderColor); p1 = newp1; p2 = newp2; if (toAngle + spaceInAngle + 2 * borderInAngle < realStartOutAngle) { var newe1 = GetPos(p, insideRadius, toAngle + spaceInAngle + borderInAngle, false); var newe2 = GetPos(p, outsideRadius, realToOutAngle, false); if (!roundCap) DrawPolygon(vh, newe2, e2, e1, newe1, borderColor); e1 = newe1; e2 = newe2; } } } } if (roundCap) { var roundRadius = (outsideRadius - insideRadius) / 2; var roundAngleRadius = insideRadius + roundRadius; var roundAngle = Mathf.Atan(roundRadius / roundAngleRadius); if (clockwise) { realStartOutAngle = startAngle + 2 * spaceHalfAngle + borderHalfAngle + roundAngle; realStartInAngle = startAngle + 2 * spaceHalfAngle + borderHalfAngle + roundAngle; } else { realStartOutAngle = startAngle - 2 * spaceHalfAngle - borderHalfAngle - roundAngle; realStartInAngle = startAngle - 2 * spaceHalfAngle - borderHalfAngle - roundAngle; } var roundTotalDegree = realStartOutAngle * Mathf.Rad2Deg; var roundCenter = p + roundAngleRadius * GetDire(realStartOutAngle); var sectorStartDegree = clockwise ? roundTotalDegree + 180 : roundTotalDegree; var sectorToDegree = clockwise ? roundTotalDegree + 360 : roundTotalDegree + 180; DrawSector(vh, roundCenter, roundRadius, color, sectorStartDegree, sectorToDegree, smoothness / 2); if (needBorder) { DrawDoughnut(vh, roundCenter, roundRadius, roundRadius + borderWidth, borderColor, Color.clear, sectorStartDegree, sectorToDegree, smoothness / 2); } p1 = GetPos(p, insideRadius, realStartOutAngle); p2 = GetPos(p, outsideRadius, realStartOutAngle); if (clockwise) { realToOutAngle = toAngle - 2 * spaceHalfAngle - borderHalfAngle - roundAngle; realToInAngle = toAngle - 2 * spaceHalfAngle - borderHalfAngle - roundAngle; if (realToOutAngle < realStartOutAngle) realToOutAngle = realStartOutAngle; } else { realToOutAngle = toAngle + 2 * spaceHalfAngle + borderHalfAngle + roundAngle; realToInAngle = toAngle + 2 * spaceHalfAngle + borderHalfAngle + roundAngle; if (realToOutAngle > realStartOutAngle) realToOutAngle = realStartOutAngle; } roundTotalDegree = realToOutAngle * Mathf.Rad2Deg; roundCenter = p + roundAngleRadius * GetDire(realToOutAngle); sectorStartDegree = clockwise ? roundTotalDegree : roundTotalDegree + 180; sectorToDegree = clockwise ? roundTotalDegree + 180 : roundTotalDegree + 360; DrawSector(vh, roundCenter, roundRadius, color, sectorStartDegree, sectorToDegree, smoothness / 2); if (needBorder) { DrawDoughnut(vh, roundCenter, roundRadius, roundRadius + borderWidth, borderColor, Color.clear, sectorStartDegree, sectorToDegree, smoothness / 2); } e1 = GetPos(p, insideRadius, realToOutAngle); e2 = GetPos(p, outsideRadius, realToOutAngle); } float segmentAngle = (realToInAngle - realStartInAngle) / segments; for (int i = 0; i <= segments; i++) { float currAngle = realStartInAngle + i * segmentAngle; p3 = new Vector3(p.x + outsideRadius * Mathf.Sin(currAngle), p.y + outsideRadius * Mathf.Cos(currAngle)); p4 = new Vector3(p.x + insideRadius * Mathf.Sin(currAngle), p.y + insideRadius * Mathf.Cos(currAngle)); if (emptyColor != Color.clear) DrawTriangle(vh, p, p1, p4, emptyColor); DrawPolygon(vh, p2, p3, p4, p1, color, toColor); p1 = p4; p2 = p3; } if (needBorder || needSpace || roundCap) { if (clockwise) { var isInAngleFixed = toAngle - spaceInAngle - 2 * borderInAngle > realStartOutAngle; if (isInAngleFixed) DrawPolygon(vh, p2, e2, e1, p1, color, toColor); else DrawTriangle(vh, p2, e2, p1, color, color, toColor); if (needBorder) { var realStartDegree = (realStartOutAngle - (roundCap ? 0 : borderAngle)) * Mathf.Rad2Deg; var realToDegree = (realToOutAngle + (roundCap ? 0 : borderAngle)) * Mathf.Rad2Deg; if (realToDegree < realStartOutAngle) realToDegree = realStartOutAngle; var inStartDegree = roundCap ? realStartDegree : (startAngle + spaceInAngle) * Mathf.Rad2Deg; var inToDegree = roundCap ? realToDegree : (toAngle - spaceInAngle) * Mathf.Rad2Deg; if (inToDegree < inStartDegree) inToDegree = inStartDegree; if (isInAngleFixed) DrawDoughnut(vh, p, insideRadius - borderWidth, insideRadius, borderColor, Color.clear, inStartDegree, inToDegree, smoothness); DrawDoughnut(vh, p, outsideRadius, outsideRadius + borderWidth, borderColor, Color.clear, realStartDegree, realToDegree, smoothness); } } else { var isInAngleFixed = toAngle + spaceInAngle + 2 * borderInAngle < realStartOutAngle; if (isInAngleFixed) DrawPolygon(vh, p2, e2, e1, p1, color, toColor); else DrawTriangle(vh, p2, e2, p1, color, color, toColor); if (needBorder) { var realStartDegree = (realStartOutAngle + (roundCap ? 0 : borderAngle)) * Mathf.Rad2Deg; var realToDegree = (realToOutAngle - (roundCap ? 0 : borderAngle)) * Mathf.Rad2Deg; var inStartDegree = roundCap ? realStartDegree : (startAngle - spaceInAngle) * Mathf.Rad2Deg; var inToDegree = roundCap ? realToDegree : (toAngle + spaceInAngle) * Mathf.Rad2Deg; if (inToDegree > inStartDegree) inToDegree = inStartDegree; if (isInAngleFixed) DrawDoughnut(vh, p, insideRadius - borderWidth, insideRadius, borderColor, Color.clear, inStartDegree, inToDegree, smoothness); DrawDoughnut(vh, p, outsideRadius, outsideRadius + borderWidth, borderColor, Color.clear, realStartDegree, realToDegree, smoothness); } } } } /// <summary> /// 画贝塞尔曲线 /// </summary> /// <param name="vh"></param> /// <param name="sp">起始点</param> /// <param name="ep">结束点</param> /// <param name="cp1">控制点1</param> /// <param name="cp2">控制点2</param> /// <param name="lineWidth">曲线宽</param> /// <param name="lineColor">曲线颜色</param> public static void DrawCurves(VertexHelper vh, Vector3 sp, Vector3 ep, Vector3 cp1, Vector3 cp2, float lineWidth, Color lineColor, float smoothness) { var dist = Vector3.Distance(sp, ep); var segment = (int)(dist / (smoothness <= 0 ? 2f : smoothness)); ChartHelper.GetBezierList2(ref s_CurvesPosList, sp, ep, segment, cp1, cp2); if (s_CurvesPosList.Count > 1) { var start = s_CurvesPosList[0]; var to = Vector3.zero; var dir = s_CurvesPosList[1] - start; var diff = Vector3.Cross(dir, Vector3.forward).normalized * lineWidth; var startUp = start - diff; var startDn = start + diff; for (int i = 1; i < s_CurvesPosList.Count; i++) { to = s_CurvesPosList[i]; diff = Vector3.Cross(to - start, Vector3.forward).normalized * lineWidth; var toUp = to - diff; var toDn = to + diff; DrawPolygon(vh, startUp, toUp, toDn, startDn, lineColor); startUp = toUp; startDn = toDn; start = to; } } } } }
using System.Collections.Generic; using System.Linq; using Amesc.Data.Contexts; using Amesc.Dominio.Pessoas; using Microsoft.EntityFrameworkCore; namespace Amesc.Data.Repositorios { public class PessoaRepositorio : RepositorioBase<Pessoa>, IPessoaRepositorio { public PessoaRepositorio(ApplicationDbContext context) : base(context) { } public override Pessoa ObterPorId(int id) { var query = Context.Set<Pessoa>().Include(p => p.Endereco).Where(entidade => entidade.Id == id); return query.Any() ? query.First() : null; } public IEnumerable<Pessoa> ConsultarPorNome(string nome) { var query = Context.Set<Pessoa>().Include(p => p.Endereco).Where(entidade => entidade.Nome.ToUpper().Contains(nome.ToUpper())); return query.Any() ? query.ToList() : new List<Pessoa>(); } public IEnumerable<Pessoa> ConsultarPorCpf(string cpf) { var query = Context.Set<Pessoa>().Include(p => p.Endereco).Where(entidade => entidade.Cpf == cpf); return query.Any() ? query.ToList() : new List<Pessoa>(); } } }
using Microsoft.Bot.Builder; using System.Threading; using System.Threading.Tasks; namespace PizzaBot.Bots { /// <summary> /// Bot that echos back a user's responses on each turn /// </summary> public class EchoBot : IBot { //The IBot interface is provided by the Microsoft.Bot.Builder package. //It lets us define behavior that happens on each "turn" of a bot. public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken)) { var activity = turnContext.Activity; if(activity.Type == "message") { var userInput = activity.Text; await turnContext.SendActivityAsync($"You said: {userInput}"); } } } }
using UnityEngine; namespace UnityUIPlayables { public class RectTransformAnimationMixer : AnimationMixer<RectTransform, RectTransformAnimationBehaviour> { private readonly RectTransformPositionMixer _positionMixer = new RectTransformPositionMixer(); private readonly RectTransformRotationMixer _rotationMixer = new RectTransformRotationMixer(); private readonly RectTransformScaleMixer _scaleMixer = new RectTransformScaleMixer(); private readonly RectTransformSizeDeltaMixer _sizeDeltaMixer = new RectTransformSizeDeltaMixer(); public override void SetupFrame(RectTransform binding) { base.SetupFrame(binding); _positionMixer.SetupFrame(); _sizeDeltaMixer.SetupFrame(); _rotationMixer.SetupFrame(); _scaleMixer.SetupFrame(); } public override void Blend(RectTransformAnimationBehaviour behaviour, float inputWeight, float progress) { if (behaviour.ControlPosition) { _positionMixer.Blend(behaviour.StartValue.AnchoredPosition, behaviour.EndValue.AnchoredPosition, inputWeight, progress); } if (behaviour.ControlSize) { _sizeDeltaMixer.Blend(behaviour.StartValue.SizeDelta, behaviour.EndValue.SizeDelta, inputWeight, progress); } if (behaviour.ControlRotation) { _rotationMixer.Blend(behaviour.StartValue.LocalRotation, behaviour.EndValue.LocalRotation, inputWeight, progress); } if (behaviour.ControlScale) { _scaleMixer.Blend(behaviour.StartValue.LocalScale, behaviour.EndValue.LocalScale, inputWeight, progress); } } public override void ApplyFrame() { _positionMixer.ApplyFrame(Binding); _sizeDeltaMixer.ApplyFrame(Binding); _rotationMixer.ApplyFrame(Binding); _scaleMixer.ApplyFrame(Binding); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualBasic; using System.IO; using System.Data.SqlClient; namespace Student_Management.DAL { class DataAccess { private OleDbConnection cnn = new OleDbConnection(); private DataSet dsHS = new DataSet(); public DataAccess() { cnn.ConnectionString = "Provider=SQLNCLI11;Server=DESKTOP-NGVBILI\\SQLEXPRESS;Database=University;Trusted_Connection=yes"; } public bool Check_User_Password(string username, string password, out string type, out string Password, out string Username) { cnn.Open(); OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Users", cnn); DataSet dsUser = new DataSet(); da.Fill(dsUser, "Users"); for (int i = 0; i < dsUser.Tables["Users"].Rows.Count; i++) { if (username == dsUser.Tables["Users"].Rows[i][0].ToString() && password == dsUser.Tables["Users"].Rows[i][1].ToString()) { Username = dsUser.Tables["Users"].Rows[i][0].ToString(); Password = dsUser.Tables["Users"].Rows[i][1].ToString(); type = dsUser.Tables["Users"].Rows[i][2].ToString(); cnn.Close(); return true; } } Password = null; type = null; Username = null; cnn.Close(); return false; } public bool Update_User(string username, string password, string type) { cnn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = cnn; cmd.CommandText = "UPDATE Users SET Password = ? WHERE Username = ?"; cmd.Parameters.Add("@password", OleDbType.VarWChar).Value = password; cmd.Parameters.Add("@Username", OleDbType.VarWChar).Value = username; cmd.ExecuteNonQuery(); cnn.Close(); return true; } public void Update_dsHS(string table) { cnn.Open(); string command = "SELECT * FROM " + table; OleDbDataAdapter da = new OleDbDataAdapter(command, cnn); if (dsHS.Tables[table] != null) { dsHS.Tables[table].Clear(); } da.Fill(dsHS, table); cnn.Close(); } //------------------------------------------------------------------------------------------------------------------------ public List<string> Get_Class() { List<string> result = new List<string>(); for (int i = 0; i < dsHS.Tables["Students"].Rows.Count; i++) { DataRow current = dsHS.Tables["Students"].Rows[i]; if (!result.Contains(current[5])) result.Add(current[5].ToString()); } return result; } public bool Import_CSV_into_System(string filename, string table) { DataTable importedData = new DataTable(); string header = null; using (StreamReader sr = new StreamReader(filename)) { string Class = sr.ReadLine(); string CourseID = ""; if (string.IsNullOrEmpty(header)) { header = sr.ReadLine(); } string[] headerColumns = header.Split(','); if (table == "Students" && headerColumns.Length != 5) return false; else if (table == "Courses" && headerColumns.Length != 4) return false; else if (table == "Scores" && headerColumns.Length != 7) return false; if (table == "Scores") { string[] temp = Class.Split('-'); Class = temp[0]; CourseID = temp[1]; } foreach (string headerColumn in headerColumns) { if (headerColumn == "STT") continue; importedData.Columns.Add(headerColumn); } if (table == "Scores") { importedData.Columns.Add("MãMôn"); } importedData.Columns.Add("Class"); while (!sr.EndOfStream) { sr.Read(new char[2], 0, 2); string line; if (table != "Scores") line = sr.ReadLine() + ',' + Class; else line = sr.ReadLine() + ',' + CourseID + ',' + Class; if (string.IsNullOrEmpty(line)) continue; string[] fields = line.Split(','); DataRow importedRow = importedData.NewRow(); for (int i = 0; i < fields.Count(); i++) { importedRow[i] = fields[i]; } importedData.Rows.Add(importedRow); } } using (SqlConnection dbConnection = new SqlConnection("Data Source=DESKTOP-NGVBILI\\SQLEXPRESS;Initial Catalog=University;Integrated Security=SSPI;")) { dbConnection.Open(); using (SqlBulkCopy s = new SqlBulkCopy(dbConnection)) { s.DestinationTableName = table; foreach (var column in importedData.Columns) s.ColumnMappings.Add(column.ToString(), column.ToString()); s.WriteToServer(importedData); } dbConnection.Close(); } Update_dsHS(table); if (table == "Courses") Update_ClassCourses(); return true; } public void Add_Student(string MSSV, string Name, string Gender, string CMND, string Class) { cnn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = cnn; cmd.CommandText = "INSERT INTO Students VALUES (?,?,?,?,?)"; cmd.Parameters.Add("@MSSV", OleDbType.VarWChar).Value = MSSV; cmd.Parameters.Add("@Name", OleDbType.VarWChar).Value = Name; cmd.Parameters.Add("@Gender", OleDbType.VarWChar).Value = Gender; cmd.Parameters.Add("@CMND", OleDbType.VarWChar).Value = CMND; cmd.Parameters.Add("@Class", OleDbType.VarWChar).Value = Class; cmd.ExecuteNonQuery(); cnn.Close(); DataRow row = dsHS.Tables["Students"].NewRow(); row[1] = MSSV; row[2] = Name; row[3] = Gender; row[4] = CMND; row[5] = Class; dsHS.Tables["Students"].Rows.Add(row); Update_ClassCourses(MSSV,Class); } public List<List<string>> Get_Student_of_a_class(string Class) { List<List<string>> student = new List<List<string>>(); for (int i = 0; i < dsHS.Tables["Students"].Rows.Count; i++) { List<string> temp0 = new List<string>(); DataRow temp = dsHS.Tables["Students"].Rows[i]; if (temp[5].ToString() == Class) { temp0.Add(temp[0].ToString()); temp0.Add(temp[1].ToString()); temp0.Add(temp[2].ToString()); temp0.Add(temp[3].ToString()); temp0.Add(temp[4].ToString()); temp0.Add(temp[5].ToString()); student.Add(temp0); } } return student; } //------------------------------------------------------------------------------------------------------------------------ public List<List<string>> Get_Courses_of_a_class(string Class) { List<List<string>> course = new List<List<string>>(); for (int i = 0; i < dsHS.Tables["Courses"].Rows.Count; i++) { List<string> temp0 = new List<string>(); DataRow temp = dsHS.Tables["Courses"].Rows[i]; if (temp[4].ToString() == Class) { temp0.Add(temp[0].ToString()); temp0.Add(temp[1].ToString()); temp0.Add(temp[2].ToString()); temp0.Add(temp[3].ToString()); temp0.Add(temp[4].ToString()); course.Add(temp0); } } return course; } public List<string> Get_Class_course() { List<string> result = new List<string>(); for (int i = 0; i < dsHS.Tables["Courses"].Rows.Count; i++) { DataRow current = dsHS.Tables["Courses"].Rows[i]; if (!result.Contains(current[4])) result.Add(current[4].ToString()); } return result; } //------------------------------------------------------------------------------------------------------------------------ private void Update_ClassCourses() { cnn.Open(); OleDbDataAdapter da = new OleDbDataAdapter("SELECT e.MSSV,f.MãMôn,f.Class FROM Students e JOIN Courses f ON e.Class = f.Class", cnn); da.Fill(dsHS, "ClassCourses"); cnn.Close(); using (SqlConnection dbConnection = new SqlConnection("Data Source=DESKTOP-NGVBILI\\SQLEXPRESS;Initial Catalog=University;Integrated Security=SSPI;")) { dbConnection.Open(); using (SqlBulkCopy s = new SqlBulkCopy(dbConnection)) { s.DestinationTableName = "ClassCourses"; foreach (var column in dsHS.Tables["ClassCourses"].Columns) s.ColumnMappings.Add(column.ToString(), column.ToString()); s.WriteToServer(dsHS.Tables["ClassCourses"]); } dbConnection.Close(); }; } private void Update_ClassCourses(string MSSV, string Class) { cnn.Open(); foreach (DataRow row in dsHS.Tables["Courses"].Rows) { if (row[4].ToString() == Class) { OleDbCommand cmd = new OleDbCommand(); cmd.Connection = cnn; cmd.CommandText = "INSERT INTO ClassCourses VALUES (?,?,?)"; cmd.Parameters.Add("@MSSV", OleDbType.VarWChar).Value = MSSV; cmd.Parameters.Add("@MãMôn", OleDbType.VarWChar).Value = row[1].ToString(); cmd.Parameters.Add("@Class", OleDbType.VarWChar).Value = Class; cmd.ExecuteNonQuery(); DataRow rows = dsHS.Tables["ClassCourses"].NewRow(); rows[1] = MSSV; rows[2] = row[1].ToString(); rows[3] = Class; dsHS.Tables["ClassCourses"].Rows.Add(rows); } } cnn.Close(); } public bool Remove_a_student_from_ClassCourses(string MSSV,string Class,string Courses) { foreach (DataRow s in dsHS.Tables["ClassCourses"].Rows) { if (s.RowState == DataRowState.Deleted) continue; if (s[1].ToString() == MSSV && s[2].ToString() == Courses && s[3].ToString() == Class && s.RowState != DataRowState.Deleted) { s.Delete(); cnn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = cnn; cmd.CommandText = "DELETE FROM ClassCourses WHERE MSSV = ? AND MãMôn = ? AND Class = ?"; cmd.Parameters.Add("@MSSV", OleDbType.VarWChar).Value = MSSV; cmd.Parameters.Add("@MãMôn", OleDbType.VarWChar).Value = Courses; cmd.Parameters.Add("@Class", OleDbType.VarWChar).Value = Class; cmd.ExecuteNonQuery(); cnn.Close(); return true; } } return false; } public bool Add_student_to_ClassCourses (string MSSV, string Class, string Courses) { bool t = false; foreach (DataRow s in dsHS.Tables["ClassCourses"].Rows) { if (s.RowState == DataRowState.Deleted) continue; if (s[1].ToString() == MSSV && s[2].ToString() == Courses && s[3].ToString() == Class) return false; } foreach (DataRow s in dsHS.Tables["Students"].Rows) { if (s[1].ToString() == MSSV) { t = true; break; } } if (t == true) { DataRow student = dsHS.Tables["ClassCourses"].NewRow(); student[1] = MSSV; student[2] = Courses; student[3] = Class; dsHS.Tables["ClassCourses"].Rows.Add(student); cnn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = cnn; cmd.CommandText = "INSERT INTO ClassCourses VALUES (?,?,?)"; cmd.Parameters.Add("@MSSV", OleDbType.VarWChar).Value = MSSV; cmd.Parameters.Add("@MãMôn", OleDbType.VarWChar).Value = Courses; cmd.Parameters.Add("@Class", OleDbType.VarWChar).Value = Class; cmd.ExecuteNonQuery(); cnn.Close(); return true; } return t; } public List<string> Get_Course_Class() { List<string> result = new List<string>(); for (int i = 0; i < dsHS.Tables["ClassCourses"].Rows.Count; i++) { StringBuilder s = new StringBuilder(); DataRow current = dsHS.Tables["ClassCourses"].Rows[i]; if (current.RowState != DataRowState.Deleted) { s.Insert(0, current[3].ToString() + "-" + current[2].ToString()); if (!result.Contains(s.ToString())) { result.Add(s.ToString()); } } } return result; } public List<List<string>> Get_Student_of_a_Course_class(string Class, string Course) { List<List<string>> student = new List<List<string>>(); for (int i = 0; i < dsHS.Tables["ClassCourses"].Rows.Count; i++) { List<string> temp0 = new List<string>(); DataRow temp = dsHS.Tables["ClassCourses"].Rows[i]; if (temp.RowState != DataRowState.Deleted) { if (temp[3].ToString() == Class && temp[2].ToString() == Course) { for (int j = 0; j < dsHS.Tables["Students"].Rows.Count; j++) { DataRow temp1 = dsHS.Tables["Students"].Rows[j]; if (temp1[1].ToString() == temp[1].ToString()) { temp0.Add(temp1[1].ToString()); temp0.Add(temp1[2].ToString()); temp0.Add(temp1[3].ToString()); temp0.Add(temp1[4].ToString()); student.Add(temp0); break; } } } } } return student; } //------------------------------------------------------------------------------------------------------------------------- public List<string> Get_Score_Class() { List<string> result = new List<string>(); for (int i = 0; i < dsHS.Tables["Scores"].Rows.Count; i++) { StringBuilder s = new StringBuilder(); DataRow current = dsHS.Tables["Scores"].Rows[i]; s.Insert(0, current[8].ToString() + "-" + current[7].ToString()); if (!result.Contains(s.ToString())) { result.Add(s.ToString()); } } return result; } public List<List<string>> Get_Student_of_a_Score_class(string Class, string Course) { List<List<string>> score = new List<List<string>>(); for (int i = 0; i < dsHS.Tables["Scores"].Rows.Count; i++) { List<string> temp0 = new List<string>(); DataRow temp = dsHS.Tables["Scores"].Rows[i]; if (temp[8].ToString() == Class && temp[7].ToString() == Course) { temp0.Add(temp[0].ToString()); temp0.Add(temp[1].ToString()); temp0.Add(temp[2].ToString()); temp0.Add(temp[3].ToString()); temp0.Add(temp[4].ToString()); temp0.Add(temp[5].ToString()); temp0.Add(temp[6].ToString()); score.Add(temp0); } } return score; } public bool Update_Score(string MSSV,float score, string column, string Class, string Courses) { DataRow student = null; foreach (DataRow s in dsHS.Tables["Scores"].Rows) { if (s[1].ToString() == MSSV && s[7].ToString() == Courses && s[8].ToString() == Class) { student = s; break; } } if (student == null) return false; student.BeginEdit(); student[column] = score; student.EndEdit(); cnn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = cnn; cmd.CommandText = "UPDATE Scores SET "+column+" = "+ score+ " WHERE MSSV = ? AND MãMôn = ? AND Class = ?"; cmd.Parameters.Add("@MSSV", OleDbType.VarWChar).Value = MSSV; cmd.Parameters.Add("@MãMôn", OleDbType.VarWChar).Value = Courses; cmd.Parameters.Add("@Class", OleDbType.VarWChar).Value = Class; cmd.ExecuteNonQuery(); cnn.Close(); return true; } //------------------------------------------------------------------------------------------------------------------------------ public List<List<string>> Get_Score_of_a_student(string MSSV) { List<List<string>> score = new List<List<string>>(); for (int i = 0; i < dsHS.Tables["Scores"].Rows.Count; i++) { List<string> temp0 = new List<string>(); DataRow temp = dsHS.Tables["Scores"].Rows[i]; if (temp[1].ToString() == MSSV) { temp0.Add(temp[3].ToString()); temp0.Add(temp[4].ToString()); temp0.Add(temp[5].ToString()); temp0.Add(temp[6].ToString()); temp0.Add(temp[7].ToString()); for (int j = 0; j < dsHS.Tables["Courses"].Rows.Count; j++) { DataRow course = dsHS.Tables["Courses"].Rows[j]; if (temp[7].ToString() == course[1].ToString()) { temp0.Add(course[2].ToString()); break; } } score.Add(temp0); } } return score; } } }
using KRF.Core.Entities.Product; using KRF.Core.Entities.Sales; using KRF.Core.Entities.ValueList; using System.Collections.Generic; namespace KRF.Core.DTO.Sales { /// <summary> /// This class does not have database table. This class acts as a container for below products classes /// </summary> public class EstimateDTO { /// <summary> /// Holds the esitmate List /// </summary> public IList<Estimate> Estimates { get; set; } /// <summary> /// Holds estimate items List /// </summary> public IList<EstimateItem> EstimateItems { get; set; } /// <summary> /// Required for Estimate lead lookup /// </summary> public IList<Lead> Leads { get; set; } /// <summary> /// Required for Estimate customer lookup /// </summary> public IList<Lead> Customers { get; set; } /// <summary> /// Required for Estimate customer address lookup /// </summary> public IList<CustomerAddress> CustomerAddress { get; set; } /// <summary> /// Required for Estimate status lookup /// </summary> public IList<Status> Status { get; set; } /// <summary> /// Holds RoofType List /// </summary> public IList<RoofType> RoofTypes { get; set; } /// <summary> /// Required for EstimateItem for Item lookuup /// </summary> public IList<Item> Items { get; set; } /// <summary> /// Required for EstimateItem for Assebly lookyup /// </summary> public IList<Assembly> Assemblies { get; set; } /// <summary> /// Unit of measure /// </summary> public IList<UnitOfMeasure> UnitOfMeasure { get; set; } public IList<EstimateDocument> EstimateDocuments { get; set; } public IList<AssemblyItem> AssemblyItems { get; set; } } }
using System.Collections.Generic; using System.Linq; using AutoMapper; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.Models.Mapping { internal class PropertyGroupDisplayResolver<TSource, TPropertyTypeSource, TPropertyTypeDestination> where TSource : ContentTypeSave<TPropertyTypeSource> where TPropertyTypeDestination : PropertyTypeDisplay where TPropertyTypeSource : PropertyTypeBasic { public IEnumerable<PropertyGroupDisplay<TPropertyTypeDestination>> Resolve(TSource source) { return source.Groups.Select(Mapper.Map<PropertyGroupDisplay<TPropertyTypeDestination>>); } } }
using System.Collections.Generic; namespace HangmanGame.App.Options { public class GameOptions { public string WordAssociationsUrlTemplate { get; set; } public string WordAssociationsApiKey { get; set; } public IReadOnlyCollection<string> Categories { get; set; } public int MinimalWordLength { get; set; } } }
// Copyright 2020 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace NtApiDotNet.Win32.Debugger { /// <summary> /// Structure for a debug string event. /// </summary> public struct Win32DebugString { /// <summary> /// The process ID. /// </summary> public int ProcessId { get; } /// <summary> /// The output string. /// </summary> public string Output { get; } internal Win32DebugString(int pid, string output) { ProcessId = pid; Output = output; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Thoughtworks_BattleShip.Interface; namespace Thoughtworks_Battleship { public sealed class ConsoleLogger : ILogger { private static ConsoleLogger _instace; private ConsoleLogger() { } public static ConsoleLogger Intance { get { return _instace ?? (_instace = new ConsoleLogger()); } } public void Log(string message) { Console.WriteLine(message); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; //General MenuControl public class MenuControl : MonoBehaviour { public GameObject Mainmenu; public GameObject Practicemenu; public GameObject TestMenu; public void ButtonScene1() { SceneManager.LoadScene(1); } public void ButtonScene2() { SceneManager.LoadScene(2); } public void ButtonScene3() { SceneManager.LoadScene(3); } public void ButtonScene4() { SceneManager.LoadScene(4); } public void ButtonScene5() { SceneManager.LoadScene(5); } public void ButtonScene6() { SceneManager.LoadScene(6); } public void ButtonScene7() { SceneManager.LoadScene(7); } public void ButtonScene8() { SceneManager.LoadScene(8); } public void ButtonScene9() { SceneManager.LoadScene(9); } public void ButtonScene10() { SceneManager.LoadScene(10); } public void ButtonScene11() { SceneManager.LoadScene(11); } public void ButtonScene12() { SceneManager.LoadScene(12); } public void ButtonScene13() { SceneManager.LoadScene(13); } public void ButtonScene14() { SceneManager.LoadScene(14); } public void QuitButton() { Application.Quit(); } public void mainmenu() { Mainmenu.SetActive(true); Practicemenu.SetActive(false); TestMenu.SetActive(false); } public void pracmenu() { Mainmenu.SetActive(false); Practicemenu.SetActive(true); TestMenu.SetActive(false); } public void testmenu() { Mainmenu.SetActive(false); Practicemenu.SetActive(false); TestMenu.SetActive(true); } }
using log4net; using log4net.Config; using log4net.Repository; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using MySql.Data.MySqlClient; using System; using System.Data; using System.Data.SqlClient; using System.IO; using Zhouli.Common.Middleware; using Zhouli.DbEntity.ModelDto; using Zhouli.DI; using Zhouli.Enum; using ZhouliSystem.Data; using ZhouliSystem.Filters; using ZhouliSystem.Models; namespace ZhouliSystem { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // 数据库连接字符串 var srtdataBaseType = Configuration.GetConnectionString("DataBaseType"); var strConnection = Configuration.GetConnectionString("ConnectionString"); #region 框架的配置关系 //注入数据访问对象 switch (Enum.Parse(typeof(DataBaseType), srtdataBaseType)) { case DataBaseType.SqlServer: services.AddDbContext<Zhouli.DbEntity.Models.ZhouLiContext>(options => options.UseSqlServer(strConnection, b => b.UseRowNumberForPaging()), ServiceLifetime.Scoped); services.AddTransient<IDbConnection, SqlConnection>(t => new SqlConnection(strConnection)); break; case DataBaseType.MySql: services.AddDbContext<Zhouli.DbEntity.Models.ZhouLiContext>(options => options.UseMySql(strConnection), ServiceLifetime.Scoped); services.AddTransient<IDbConnection, MySqlConnection>(t => new MySqlConnection(strConnection)); break; } //添加session依赖 services.AddSession(); //.net core 2.1时默认不注入HttpContextAccessor依赖注入关系,所以再此手动注册 services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); //注入gzip压缩依赖 services.AddResponseCompression(); //注入Response 缓存依赖 services.AddResponseCaching(); //重置区域匹配路径规则 services.Configure<RazorViewEngineOptions>(options => { options.AreaViewLocationFormats.Clear(); options.AreaViewLocationFormats.Add("/Areas/{2}Manager/Views/{1}/{0}.cshtml"); options.AreaViewLocationFormats.Add("/Areas/{2}Manager/Views/Shared/{0}.cshtml"); options.AreaViewLocationFormats.Add("/Views/Shared/{0}.cshtml"); }); //MemoryCache缓存 services.AddMemoryCache(); services.AddHttpClient(); //mvc框架 services.AddMvc(o => { //注册全局异常过滤器 o.Filters.Add<HttpGlobalExceptionFilter>(); //配置缓存信息 o.CacheProfiles.Add("default", new Microsoft.AspNetCore.Mvc.CacheProfile { Duration = 60 * 10, // 10 分钟 }); o.CacheProfiles.Add("Hourly", new Microsoft.AspNetCore.Mvc.CacheProfile { Duration = 60 * 60, // 1 hour //Location = Microsoft.AspNetCore.Mvc.ResponseCacheLocation.Any, //NoStore = true, //VaryByHeader = "User-Agent", //VaryByQueryKeys = new string[] { "aaa" } }); }).AddJsonOptions(o => { o.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); o.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; }); #endregion #region 自定义的配置关系 //注入全局依赖注入提供者类 // services.AddScoped(typeof(WholeInjection)); services.AddScoped<UserAccount>(); services.AddResolveAllTypes(new string[] { "Zhouli.DAL", "Zhouli.BLL" }); //初始化Dto与实体映射关系 ZhouliDtoMapper.Initialize(); //注入配置文件类 services.AddOptions().Configure<CustomConfiguration>(Configuration.GetSection("CustomConfiguration")); #endregion } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseRealIp(); if (env.IsDevelopment())//开发环境 { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error/Index"); } app.UseStatusCodePages(); app.UseStaticFiles(); app.UseSession(); //gzip压缩中间件 app.UseResponseCompression(); //Response 缓存中间件 app.UseResponseCaching(); app.UseMvc(routes => { routes.MapRoute( name: "areas", template: "{area:exists}/{controller}/{action=Index}/{id?}" ); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); //初始化数据库 InitSystem.InitDB(app.ApplicationServices); } } }
using UnityEngine; using Minigame5; using System.Collections; using System.Collections.Generic; public class MiniGame5_Manager : MiniGameSingleton<MiniGame5_Manager> { #region variables /// <summary> /// Лэйбл для отображения оставшегося времени /// </summary> public UILabel labelTime; public List<ButtonToggle> listButtons; /// <summary> /// Время до окончания игры /// </summary> private float _time = 0f; private int _errorCount = 0; private bool _isCoroutine = false; private ButtonToggle _currentButton; #endregion void Awake() { // Для синглтона if (_instance == null) _instance = this; else Destroy(this.gameObject); } void Update() { if (_isPlay) CheckTime(); } public void CloseMenu() { if (!_isCoroutine) Hide(); } /// <summary> /// Инициализация /// </summary> protected override void Init() { _errorCount = 0; _isCoroutine = false; _currentButton = null; if (listButtons == null) listButtons = new List<ButtonToggle>(); foreach (ButtonToggle bt in listButtons) if (bt != null) bt.Reset(); if (listButtons.Count > 0) _currentButton = listButtons[0]; } /// <summary> /// Инициализация новой игры /// </summary> /// <param name="time">Время для прохождения</param> public void NewGame(float time) { Init(); Show(); _time = time; _isPlay = true; } public void ClickButtonToggle(ButtonToggle bt) { if (!isPlay || bt == null) return; if (bt != _currentButton) { bt.SetToggleValue(false); _errorCount++; return; } StartCoroutine(bt.Set()); int index = listButtons.IndexOf(_currentButton); if (index >= 0) { if (index < listButtons.Count - 1) _currentButton = listButtons[index + 1]; else Win(); } } protected override void Win() { _isPlay = false; StartCoroutine(WinCoroutine(3f)); } protected IEnumerator WinCoroutine(float delay) { _isCoroutine = true; yield return new WaitForSeconds(delay); base.Win(); _isCoroutine = false; } /// <summary> /// Проверка оставшегося времени до конца игры /// </summary> private void CheckTime() { if (_isPlay) { _time -= Time.deltaTime; if (labelTime != null) labelTime.text = (((int)_time / 60)).ToString("00") + ":" + ((int)_time % 60).ToString("00"); if (_time <= 0) { Debug.Log("Time is out!"); Win(); } } } protected override MiniGameResult GetResult() { if (_time <= 0) return MiniGameResult.Bronze; return (_errorCount == 0) ? MiniGameResult.Gold : (_errorCount > 0 && _errorCount < 3) ? MiniGameResult.Silver : MiniGameResult.Bronze; } }
using System; using TestProject.Data; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using TestProject.Models.Ratings; namespace TestProject.Controllers { public class RatingsController : Controller { private readonly RatingsContext _dbContext; public RatingsController(RatingsContext dbContext) { _dbContext = dbContext; } public async Task<IActionResult> Index() { var ratings = await _dbContext.Ratings.ToListAsync(); return View(ratings); } [HttpGet] public IActionResult Add() { return View(); } [HttpPost] public async Task<IActionResult> Add(Rating rating) { _dbContext.Ratings.Add(rating); await _dbContext.SaveChangesAsync(); var ratings = await _dbContext.Ratings.ToListAsync(); return View("Index", ratings); } } }
using UnityEngine; using System.Collections; public class playbuttonhandler : MonoBehaviour { bool allowed;//specifies when the player's touch input will be allowed float mytimer=1.52f;//it will be allowed after 1.52 seconds bool touchallowed;//this is used to allow only 1 raycast per touch (to increase performance) // Use this for initialization void Start () { //variable intialization touchallowed = false; allowed = false; //end of initialization } // Update is called once per frame void Update () { //check for input and cast a ray if(Input.touchCount==1&&allowed&&touchallowed){ touchallowed=false;//means that ray is already casted for this input Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if(Physics.Raycast(ray,out hit,Mathf.Infinity)&&hit.collider.gameObject==this.gameObject){ Application.LoadLevel("scene2");//if casted ray hits this object, load scene 2 } } //allow input and raycast when there is no input if(Input.touchCount==0){ touchallowed=true; } //timer for when the player input will start if(mytimer<=0f){ allowed=true; } else{ mytimer-=Time.deltaTime; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using nagp.sample.library; using nagp.sample.library.DTO; namespace nagp.console.app { class Program { static void Main(string[] args) { Console.WriteLine("Getting all students from student library...."); List<StudentDTO> allStudents = new StudentDetails().GetStudentList(); foreach (StudentDTO student in allStudents) { Console.WriteLine("Student Id: " + student.StudentId + ", Student Name: " + student.StudentName + ", Class: " + student.Standard + ", Age: " + student.Age); } Console.WriteLine("Got all students"); Console.ReadLine(); } } }
using System.Text.Json.Serialization; using PlatformRacing3.Server.Game.Communication.Messages.Incoming.Json; namespace PlatformRacing3.Server.Game.Communication.Messages.Outgoing.Json; internal sealed class JsonMatchOwnerOutgoingMessage : JsonPacket { private protected override string InternalType => "matchOwner"; [JsonPropertyName("matchName")] public string Name { get; set; } [JsonPropertyName("play")] public bool Play { get; set; } [JsonPropertyName("kick")] public bool Kick { get; set; } [JsonPropertyName("ban")] public bool Ban { get; set; } internal JsonMatchOwnerOutgoingMessage(string name, bool play, bool kick, bool ban) { this.Name = name; this.Play = play; this.Kick = kick; this.Ban = ban; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Registration_File { class Program { static void Main(string[] args) { while(true) { Login login = new Login(); Registration registration = new Registration(); int choiceNumber = 0; Console.WriteLine("|-----------------|"); Console.WriteLine("|1. Регистрация |"); Console.WriteLine("|-----------------|"); Console.WriteLine("|2. Вход |"); Console.WriteLine("|-----------------|"); Console.WriteLine("|3. Выход |"); Console.WriteLine("|-----------------|"); Console.WriteLine(); Console.Write("Выберите цифру: "); choiceNumber = int.Parse(Console.ReadLine()); Console.Clear(); if (choiceNumber == 1) { /* EMAIL */ Console.Write("Введите e-mail : "); registration.Email = Console.ReadLine(); try { if (!registration.Email.Contains('@') | !registration.Email.Contains('.')) { throw new ArgumentException(); } } catch (ArgumentException) { Console.WriteLine("E-mail не соответствует требованиям(@ and .)"); Console.ReadKey(); break; } /* Password */ int minimalLengthOfPassword = 6; Console.Write("Введите пароль : "); registration.Password = ReadPassword(); try { if (registration.Password.Length < minimalLengthOfPassword) { throw new ArgumentException("Пароль не соответствует требованиям (не меньше 6 символов)"); } } catch (ArgumentException) { Console.WriteLine("Пароль не соответствует требованиям (не меньше 6 символов)"); Console.ReadKey(); break; } /* FullName */ Console.Write("Введите имя : "); registration.FullName = Console.ReadLine(); /* Age */ Console.Write("Введите возраст : "); registration.Age = int.Parse(Console.ReadLine()); /* phoneNumber */ Console.Write("Введите номер телефона: "); registration.PhoneNumber = Console.ReadLine(); try { if (string.IsNullOrEmpty(registration.PhoneNumber) || registration.PhoneNumber.Length > 12 || registration.PhoneNumber.Contains('-') || registration.PhoneNumber.Contains(' ')) { throw new ArgumentException(); } } catch (ArgumentException) { throw new ArgumentException("Мобильный телефон неверный"); } Console.WriteLine("----------------------"); Console.WriteLine( "Логин : " + registration.Email); Console.WriteLine( "Пароль : " + registration.Password); Console.WriteLine( "Имя : " + registration.FullName); Console.WriteLine( "Возраст : " + registration.Age); Console.WriteLine( "Номер телефона : " + registration.PhoneNumber); Console.WriteLine("----------------------"); Console.WriteLine("Регистрация успешно пройдена"); Console.ReadKey(); Console.Clear(); } else if (choiceNumber == 2) { Console.Write("Login : "); login.Email = Console.ReadLine(); Console.Write("Password: "); login.Password = ReadPassword(); if (registration.Email == login.Email || registration.Password == login.Password) { Console.WriteLine("Вы успешно вошли в свой аккаунт"); Console.ReadKey(); Console.Clear(); } else { Console.WriteLine("Логин или пароль заданы неправильно"); Console.ReadKey(); Console.Clear(); } } else if (choiceNumber == 3) { break; } } } public static string ReadPassword() { string password = ""; ConsoleKeyInfo info = Console.ReadKey(true); while (info.Key != ConsoleKey.Enter) { if (info.Key != ConsoleKey.Backspace) { Console.Write("*"); password += info.KeyChar; } else if (info.Key == ConsoleKey.Backspace) { if (!string.IsNullOrEmpty(password)) { password = password.Substring(0, password.Length - 1); int pos = Console.CursorLeft; Console.SetCursorPosition(pos - 1, Console.CursorTop); Console.Write(" "); Console.SetCursorPosition(pos - 1, Console.CursorTop); } } info = Console.ReadKey(true); } Console.WriteLine(); return password; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Shooter : MonoBehaviour { [SerializeField] Projectile projectile; [SerializeField] GameObject gun; AttackerSpawner myLaneSpawner; Animator animator; void Start() { SetLaneSpawner(); animator = GetComponent<Animator>(); } private void SetLaneSpawner() { AttackerSpawner[] attackerSpawners = FindObjectsOfType<AttackerSpawner>(); foreach (AttackerSpawner spawner in attackerSpawners) { bool isCloseEnough = Mathf.Abs(spawner.transform.position.y - transform.position.y) <= Mathf.Epsilon; if (isCloseEnough) { myLaneSpawner = spawner; } } } void Update() { animator.SetBool("IsAttacking", IsAttackerInLane()); } private bool IsAttackerInLane() { return myLaneSpawner.transform.childCount > 0; } public void Fire() { Projectile newProjectile = Instantiate(projectile, gun.transform.position, Quaternion.identity) as Projectile; newProjectile.transform.parent = transform; } }
using Core.Base; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Data.Infrastructure { public abstract class EntityConfiguration<TEntity> : IEntityTypeConfiguration<TEntity> where TEntity : BaseEntity { public abstract void Configure(EntityTypeBuilder<TEntity> builder); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using RetailClientApp.Models.ViewModel; using RetailClientApp.Models; using Microsoft.AspNetCore.Http; using RetailClientApp.Provider; namespace RetailClientApp.Controllers { public class CustomerController : Controller { private readonly ICustomerProvider _provider; private log4net.ILog _logger = log4net.LogManager.GetLogger(typeof(AccountController)); public CustomerController(ICustomerProvider provider) { this._provider = provider; } /// <summary> /// returns default view for customer's welcome /// </summary> /// <returns></returns> public IActionResult Index() { return View(); } /// <summary> /// view for new customer creation /// </summary> /// <returns></returns> [HttpGet] public IActionResult Create() { if (HttpContext.Session.GetString("IsEmployee") == null) { return RedirectToAction("Login", "Authentication"); }else if (HttpContext.Session.GetString("IsEmployee") == "False") { return RedirectToAction("UnAuthorized", "Authentication"); } else { return View(); } } /// <summary> /// this actually creates the customer /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost,ValidateAntiForgeryToken] public async Task<IActionResult> Create(CreateCutomerViewModel model) { if (HttpContext.Session.GetString("IsEmployee") == null) { return RedirectToAction("Login", "Authentication"); } else { if (!ModelState.IsValid) return View(model); CreateCustomerSuccessViewModel createSuccess = new CreateCustomerSuccessViewModel(); try { var response = await _provider.CreateCustomer(model); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var jsoncontent = await response.Content.ReadAsStringAsync(); createSuccess = JsonConvert.DeserializeObject<CreateCustomerSuccessViewModel>(jsoncontent); return View("CreateSuccess", createSuccess); } else if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError) { ModelState.AddModelError("", "Having server issue while adding record"); return View(model); } else if (response.StatusCode == System.Net.HttpStatusCode.Conflict) { ModelState.AddModelError("", "Username already present with ID :" + model.CustomerId); return View(model); } else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) { ModelState.AddModelError("", "Invalid model states"); return View(model); } }catch(Exception ex) { _logger.Error("Exception Occured as : " + ex.Message); } return View(model); } } /// <summary> /// Shows success view when customer is created /// </summary> /// <returns></returns> [HttpGet] public IActionResult CreateSuccess() { CreateCustomerSuccessViewModel model = new CreateCustomerSuccessViewModel(); return View(model); } /// <summary> /// Get soecific customer details by ID /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpGet] public async Task<IActionResult> GetCustomerDetails(int id) { if (HttpContext.Session.GetString("IsEmployee") == null) { return RedirectToAction("Login", "Authentication"); } else { Customer customer = new Customer(); try { var response = await _provider.GetCustomerDetails(id); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var JsonContent = await response.Content.ReadAsStringAsync(); customer = JsonConvert.DeserializeObject<Customer>(JsonContent); return View(customer); } else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) { ViewBag.Message = "No any record Found! Bad Request"; return View(customer); } else if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError) { ViewBag.Message = "Having server issue while adding record"; return View(customer); } else if (response.StatusCode == System.Net.HttpStatusCode.NotFound) { ViewBag.Message = "No record found in DB for ID :"+id; return View(customer); } }catch(Exception ex) { _logger.Warn("Exception occured as :"+ex.Message); } return View(customer); } } /// <summary> /// get All customers from the Customer API /// </summary> /// <returns></returns> [HttpGet] public async Task<IActionResult> GetCustomer() { if (HttpContext.Session.GetString("IsEmployee") == null) { return RedirectToAction("Login", "Authentication"); } else { List<Customer> customers = new List<Customer>(); try { var response =await _provider.GetCustomers(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var JsonContent = await response.Content.ReadAsStringAsync(); customers = JsonConvert.DeserializeObject<List<Customer>>(JsonContent); return View(customers); } else if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError) { ViewBag.Message = "Having server issue while adding record"; return View(customers); } }catch(Exception ex) { _logger.Error("Exceptions Occured as :" + ex.Message); } return View(customers); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Projectile : MonoBehaviour { public bool enemy; public GameObject impactEffect; public Vector3 aimAt; public float flySpeed; public float impactDamage; public Rigidbody theRB; // Start is called before the first frame update void Start() { transform.LookAt(aimAt); } // Update is called once per frame void Update() { theRB.velocity = transform.forward * flySpeed; } private void OnTriggerEnter(Collider other) { if(other.transform.tag == "Mine") { other.transform.GetComponent<Mine>().explode(); //Instantiate(impactEffect, transform.position, transform.rotation); Destroy(gameObject); } if (!enemy) { if (other.transform.tag == "Enemy") { other.transform.parent.GetComponent<Enemy>().takeDamage(impactDamage); //Instantiate(impactEffect, transform.position, transform.rotation); Destroy(gameObject); } else if (other.transform.tag == "EnemyCrit") { other.transform.parent.GetComponent<Enemy>().takeDamage(impactDamage * 2f); //Instantiate(impactEffect, transform.position, transform.rotation); Destroy(gameObject); } else if (other.transform.tag != "Player") { //Instantiate(impactEffect, transform.position, transform.rotation); Destroy(gameObject); } } else { if (other.transform.tag == "Player") { other.transform.GetComponent<PlayerControl>().hit(impactDamage); //Instantiate(impactEffect, transform.position, transform.rotation); Destroy(gameObject); } else if (other.transform.tag != "Enemy" && other.transform.tag != "EnemyCrit") { Destroy(gameObject); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Business.Helper; using eIVOGo.Module.Base; using Model.DataEntity; using Model.InvoiceManagement; using Model.Locale; using Model.Security.MembershipManagement; using Utility; using Uxnet.Web.Module.Common; namespace eIVOGo.Module.Inquiry.ForOP { public partial class InquireAllowanceCancellation : InquireInvoiceItem { protected override void buildQueryItem() { Expression<Func<InvoiceAllowanceCancellation, bool>> queryExpr = i => true; if (DateFrom.HasValue) { queryExpr = queryExpr.And(i => i.CancelDate >= DateFrom.DateTimeValue); } if (DateTo.HasValue) { queryExpr = queryExpr.And(i => i.CancelDate < DateTo.DateTimeValue.AddDays(1)); } String cancelNo = this.txtAllowanceCancelNO.Text.Trim(); if (!string.IsNullOrEmpty(cancelNo)) { queryExpr = queryExpr.And(i => i.InvoiceAllowance.AllowanceNumber == cancelNo); } if (!String.IsNullOrEmpty(this.txtReceiptNo.Text)) { queryExpr = queryExpr.And(i => i.InvoiceAllowance.InvoiceAllowanceBuyer.ReceiptNo.Equals(this.txtReceiptNo.Text.Trim())); } if (!String.IsNullOrEmpty(this.ddlAttach.SelectedValue)) { if (this.ddlAttach.SelectedValue.Equals("0")) { queryExpr = queryExpr.And(i => i.InvoiceAllowance.CDS_Document.Attachment.Count() > 0); } else { queryExpr = queryExpr.And(i => i.InvoiceAllowance.CDS_Document.Attachment.Count() <= 0); } } itemList.BuildQuery = table => { var allowance = table.Context.GetTable<InvoiceAllowance>() .Join(table.Context.GetTable<InvoiceAllowanceCancellation>().OrderByDescending(ac=>ac.CancelDate).Where(queryExpr), a => a.AllowanceID, c => c.AllowanceID, (a, c) => a); if (!String.IsNullOrEmpty(CompanyID.SelectedValue)) { int companyID = int.Parse(CompanyID.SelectedValue); if (!String.IsNullOrEmpty(BusinessID.SelectedValue)) { if (Naming.InvoiceCenterBusinessType.進項 == (Naming.InvoiceCenterBusinessType)int.Parse(BusinessID.SelectedValue)) { allowance = allowance.Join(table.Context.GetTable<InvoiceAllowanceBuyer>() .Join(table.Context.GetTable<BusinessRelationship>().Where(r => r.MasterID == companyID).Select(r => r.MasterID).Distinct(), b => b.BuyerID, r => r, (b, r) => b) , i => i.AllowanceID, s => s.AllowanceID, (i, s) => i); } else { allowance = allowance.Join(table.Context.GetTable<InvoiceAllowanceSeller>() .Join(table.Context.GetTable<BusinessRelationship>().Where(r => r.MasterID == companyID).Select(r => r.MasterID).Distinct(), b => b.SellerID, r => r, (b, r) => b) , i => i.AllowanceID, s => s.AllowanceID, (i, s) => i); } } else { allowance = allowance.Join(table.Context.GetTable<InvoiceAllowanceSeller>().Where(i => i.SellerID == companyID), i => i.AllowanceID, s => s.AllowanceID, (i, s) => i) .Concat(allowance.Join(table.Context.GetTable<InvoiceAllowanceBuyer>().Where(i => i.BuyerID == companyID), i => i.AllowanceID, s => s.AllowanceID, (i, s) => i)); } } else { if (!String.IsNullOrEmpty(BusinessID.SelectedValue)) { if (Naming.InvoiceCenterBusinessType.進項 == (Naming.InvoiceCenterBusinessType)int.Parse(BusinessID.SelectedValue)) { allowance = allowance.Join(table.Context.GetTable<InvoiceAllowanceBuyer>() .Join(table.Context.GetTable<BusinessRelationship>().Select(r => r.MasterID).Distinct(), b => b.BuyerID, r => r, (b, r) => b) , i => i.AllowanceID, s => s.AllowanceID, (i, s) => i); } else { allowance = allowance.Join(table.Context.GetTable<InvoiceAllowanceSeller>() .Join(table.Context.GetTable<BusinessRelationship>().Select(r => r.MasterID).Distinct(), b => b.SellerID, r => r, (b, r) => b) , i => i.AllowanceID, s => s.AllowanceID, (i, s) => i); } } } if (!String.IsNullOrEmpty(LevelID.SelectedValue)) { if (!setdayrange) return table.Where(d => d.DocType == (int)Naming.DocumentTypeDefinition.E_AllowanceCancellation && d.CurrentStep == int.Parse(LevelID.SelectedValue)) .Join(table.Context.GetTable<DerivedDocument>() .Join(allowance.Where(i => i.InvoiceAllowanceCancellation.CancelDate <= DateTime.Today & i.InvoiceAllowanceCancellation.CancelDate >= DateTime.Today.AddMonths(-5)) , d => d.SourceID, i => i.AllowanceID, (d, i) => d) , d => d.DocID, r => r.DocID, (d, r) => d).OrderByDescending(d => d.DocID); else return table.Where(d => d.DocType == (int)Naming.DocumentTypeDefinition.E_AllowanceCancellation && d.CurrentStep == int.Parse(LevelID.SelectedValue)) .Join(table.Context.GetTable<DerivedDocument>() .Join(allowance, d => d.SourceID, i => i.AllowanceID, (d, i) => d) , d => d.DocID, r => r.DocID, (d, r) => d).OrderByDescending(d => d.DocID); ; } else { if (!setdayrange) return table.Where(d => d.DocType == (int)Naming.DocumentTypeDefinition.E_AllowanceCancellation) .Join(table.Context.GetTable<DerivedDocument>() .Join(allowance.Where(i => i.InvoiceAllowanceCancellation.CancelDate <= DateTime.Today & i.InvoiceAllowanceCancellation.CancelDate >= DateTime.Today.AddMonths(-5)) , d => d.SourceID, i => i.AllowanceID, (d, i) => d) , d => d.DocID, r => r.DocID, (d, r) => d).OrderByDescending(d => d.DocID); else return table.Where(d => d.DocType == (int)Naming.DocumentTypeDefinition.E_AllowanceCancellation) .Join(table.Context.GetTable<DerivedDocument>() .Join(allowance, d => d.SourceID, i => i.AllowanceID, (d, i) => d) , d => d.DocID, r => r.DocID, (d, r) => d).OrderByDescending(d => d.DocID); ; } }; if (itemList.Select().Count() > 0) { tblAction.Visible = true; } } } }
using System; using Grpc.Core; using Grpc.Reflection; using Grpc.Reflection.V1Alpha; namespace ProtoHub { class Program { static void Main(string[] args) { try { var reflectionServiceImpl = new ReflectionServiceImpl(ProtoHubService.Descriptor, ServerReflection.Descriptor); Server server = new Server { Services = { ServerReflection.BindService(reflectionServiceImpl), ProtoHubService.BindService(new ProtoHubImpl()) }, Ports = { new ServerPort("localhost", 5000, ServerCredentials.Insecure) } }; server.Start(); Console.WriteLine("Server listening on port " + 5000); Console.WriteLine("Press any key to stop the server..."); Console.ReadKey(); server.ShutdownAsync().Wait(); } catch(Exception ex) { Console.WriteLine($"Exception encountered: {ex}"); } } } }
using System; using System.Collections.Generic; using System.Text; namespace CLI.FileTypeSession { static class FileValidator { public static bool IsNullOrEmptyPath(string path) => String.IsNullOrEmpty(path) ? true : false; public static bool IsValid(string path) => System.IO.File.Exists(path) ? true : false; } }
/* * Bungie.Net API * * These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. * * OpenAPI spec version: 2.1.1 * Contact: support@bungie.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using NUnit.Framework; using System; using System.Linq; using System.IO; using System.Collections.Generic; using BungieNetPlatform.Api; using BungieNetPlatform.Model; using BungieNetPlatform.Client; using System.Reflection; using Newtonsoft.Json; namespace BungieNetPlatform.Test { /// <summary> /// Class for testing DestinyDefinitionsDestinyVendorCategoryEntryDefinition /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the model. /// </remarks> [TestFixture] public class DestinyDefinitionsDestinyVendorCategoryEntryDefinitionTests { // TODO uncomment below to declare an instance variable for DestinyDefinitionsDestinyVendorCategoryEntryDefinition //private DestinyDefinitionsDestinyVendorCategoryEntryDefinition instance; /// <summary> /// Setup before each test /// </summary> [SetUp] public void Init() { // TODO uncomment below to create an instance of DestinyDefinitionsDestinyVendorCategoryEntryDefinition //instance = new DestinyDefinitionsDestinyVendorCategoryEntryDefinition(); } /// <summary> /// Clean up after each test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of DestinyDefinitionsDestinyVendorCategoryEntryDefinition /// </summary> [Test] public void DestinyDefinitionsDestinyVendorCategoryEntryDefinitionInstanceTest() { // TODO uncomment below to test "IsInstanceOfType" DestinyDefinitionsDestinyVendorCategoryEntryDefinition //Assert.IsInstanceOfType<DestinyDefinitionsDestinyVendorCategoryEntryDefinition> (instance, "variable 'instance' is a DestinyDefinitionsDestinyVendorCategoryEntryDefinition"); } /// <summary> /// Test the property 'CategoryIndex' /// </summary> [Test] public void CategoryIndexTest() { // TODO unit test for the property 'CategoryIndex' } /// <summary> /// Test the property 'CategoryId' /// </summary> [Test] public void CategoryIdTest() { // TODO unit test for the property 'CategoryId' } /// <summary> /// Test the property 'CategoryHash' /// </summary> [Test] public void CategoryHashTest() { // TODO unit test for the property 'CategoryHash' } /// <summary> /// Test the property 'QuantityAvailable' /// </summary> [Test] public void QuantityAvailableTest() { // TODO unit test for the property 'QuantityAvailable' } /// <summary> /// Test the property 'ShowUnavailableItems' /// </summary> [Test] public void ShowUnavailableItemsTest() { // TODO unit test for the property 'ShowUnavailableItems' } /// <summary> /// Test the property 'HideIfNoCurrency' /// </summary> [Test] public void HideIfNoCurrencyTest() { // TODO unit test for the property 'HideIfNoCurrency' } /// <summary> /// Test the property 'HideFromRegularPurchase' /// </summary> [Test] public void HideFromRegularPurchaseTest() { // TODO unit test for the property 'HideFromRegularPurchase' } /// <summary> /// Test the property 'BuyStringOverride' /// </summary> [Test] public void BuyStringOverrideTest() { // TODO unit test for the property 'BuyStringOverride' } /// <summary> /// Test the property 'DisabledDescription' /// </summary> [Test] public void DisabledDescriptionTest() { // TODO unit test for the property 'DisabledDescription' } /// <summary> /// Test the property 'DisplayTitle' /// </summary> [Test] public void DisplayTitleTest() { // TODO unit test for the property 'DisplayTitle' } /// <summary> /// Test the property 'Overlay' /// </summary> [Test] public void OverlayTest() { // TODO unit test for the property 'Overlay' } } }
using NUnit.Framework; using P10Gen.Core.Model; namespace G10Gen.Core.Tests { public class CombinationColorTest { [Test] public void Ctor_Aufgabe_Get() { Assert.AreEqual(Aufgabe.Color, new CombinationColor(0).Aufgabe); } [TestCase(0, ExpectedResult = 0)] [TestCase(2, ExpectedResult = 2)] [TestCase(15, ExpectedResult = 15)] public int Ctor_Aufgabe_Get(int count) { return new CombinationColor(count).Count; } [Test] public void Ctor_SameColor_Get() { Assert.IsFalse(new CombinationColor(1).SameColor); } [TestCase(3)] [TestCase(7)] public void CalculateComplexity_Cards_Result(int value) { Assert.AreEqual(value, new CombinationColor(value).CalculateComplexity()); } } }
using System; using System.Text.RegularExpressions; namespace LabSeven { class Program { static void Main(string[] args) { Console.WriteLine("Welcome to the Grand Circus Data Entry Terminal!"); Console.WriteLine("#################################################"); Console.WriteLine(); // Checks name, email, phone number and date nameCheck(); mailCheck(); numCheck(); dateCheck(); // Checks html tags tagCheck(); } public static void nameCheck() { bool checker = false; string yourName; while (checker == false) { Console.WriteLine("Please enter your name: "); yourName = Console.ReadLine(); if (Regex.IsMatch(yourName, @"^([A-Z]{1})(['A-Za-z]{0,29})")) { Console.WriteLine("Valid input!"); checker = true; Console.WriteLine(); } else { Console.WriteLine("Sorry, that is not a valid name!"); Console.WriteLine(); } } } public static void mailCheck() { bool checker = false; string yourEmail; while (checker == false) { Console.WriteLine("Please enter your email: (example: person@mail.net)"); yourEmail = Console.ReadLine(); if (Regex.IsMatch(yourEmail, @"^([A-Z]|[a-z]|[0-9]){5,30}@([A-Z]|[a-z]|[0-9]){5,10}.\w{2,3}")) { Console.WriteLine("Valid input!"); checker = true; Console.WriteLine(); } else { Console.WriteLine("Sorry, that is not a valid email!"); Console.WriteLine(); } } } public static void numCheck() { bool checker = false; string yourNum; while (checker == false) { Console.WriteLine("Please enter your phone number: (example: XXX-XXX-XXXX) "); yourNum = Console.ReadLine(); if (Regex.IsMatch(yourNum, @"^\d{3}-\d{3}-\d{4}$")) { Console.WriteLine("Valid input!"); checker = true; Console.WriteLine(); } else { Console.WriteLine("Sorry, that is not a valid phone number!"); Console.WriteLine(); } } } public static void dateCheck() { bool checker = false; string yourDate; while (checker == false) { Console.WriteLine("Please enter today's date: (example: DD/MM/YYYY)"); yourDate = Console.ReadLine(); if (Regex.IsMatch(yourDate, @"^([0][1-9]|[1][0-9]|[2][0-9]|[3][0-1])/([0][1-9]|[1][0-2])/([0][0-9][0-9][0-9]|[1][0-9][0-9][0-9]|[2][0-9][0-9][0-9])$")) { Console.WriteLine("Valid input!"); checker = true; Console.WriteLine(); } else { Console.WriteLine("Sorry, that is not a valid date!"); Console.WriteLine(); } } } public static void tagCheck() { bool checker = false; string yourCode; while (checker == false) { Console.WriteLine("Please enter your code containing html tags: "); yourCode = Console.ReadLine(); if (Regex.IsMatch(yourCode, @"(\<(\/)?(\w)*(\d)?\>)")) { Console.WriteLine("Valid input!"); checker = true; Console.WriteLine(); } else { Console.WriteLine("Sorry, that is not valid code!"); Console.WriteLine(); } } } } }
// Accord Statistics Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Statistics.Testing { using System; using Accord.Statistics.Distributions.Univariate; using Accord.Statistics.Testing.Power; using AForge; /// <summary> /// One-sample Student's T test. /// </summary> /// /// <remarks> /// <para> /// The one-sample t-test assesses whether the mean of a sample is /// statistically different from a hypothesized value.</para> /// /// <para> /// This test supports creating <see cref="TTestPowerAnalysis">power analyses</see> /// through its <see cref="TTest.Analysis"/> property.</para> /// /// <para> /// References: /// <list type="bullet"> /// <item><description><a href="http://en.wikipedia.org/wiki/Student's_t-test"> /// Wikipedia, The Free Encyclopedia. Student's T-Test. </a></description></item> /// <item><description><a href="http://www.le.ac.uk/bl/gat/virtualfc/Stats/ttest.html"> /// William M.K. Trochim. The T-Test. Research methods Knowledge Base, 2009. /// Available on: http://www.le.ac.uk/bl/gat/virtualfc/Stats/ttest.html </a></description></item> /// <item><description><a href="http://en.wikipedia.org/wiki/One-way_ANOVA"> /// Graeme D. Ruxton. The unequal variance t-test is an underused alternative to Student's /// t-test and the Mann–Whitney U test. Oxford Journals, Behavioral Ecology Volume 17, Issue 4, pp. /// 688-690. 2006. Available on: http://beheco.oxfordjournals.org/content/17/4/688.full </a></description></item> /// </list></para> /// </remarks> /// /// <example> /// <code> /// // Consider a sample generated from a Gaussian /// // distribution with mean 0.5 and unit variance. /// /// double[] sample = /// { /// -0.849886940156521, 3.53492346633185, 1.22540422494611, 0.436945126810344, 1.21474290382610, /// 0.295033941700225, 0.375855651783688, 1.98969760778547, 1.90903448980048, 1.91719241342961 /// }; /// /// // One may rise the hypothesis that the mean of the sample is not /// // significantly different from zero. In other words, the fact that /// // this particular sample has mean 0.5 may be attributed to chance. /// /// double hypothesizedMean = 0; /// /// // Create a T-Test to check this hypothesis /// TTest test = new TTest(sample, hypothesizedMean, /// OneSampleHypothesis.ValueIsDifferentFromHypothesis); /// /// // Check if the mean is significantly different /// test.Significant should be true /// /// // Now, we would like to test if the sample mean is /// // significantly greater than the hypothesized zero. /// /// // Create a T-Test to check this hypothesis /// TTest greater = new TTest(sample, hypothesizedMean, /// OneSampleHypothesis.ValueIsGreaterThanHypothesis); /// /// // Check if the mean is significantly larger /// greater.Significant should be true /// /// // Now, we would like to test if the sample mean is /// // significantly smaller than the hypothesized zero. /// /// // Create a T-Test to check this hypothesis /// TTest smaller = new TTest(sample, hypothesizedMean, /// OneSampleHypothesis.ValueIsSmallerThanHypothesis); /// /// // Check if the mean is significantly smaller /// smaller.Significant should be false /// </code> /// </example> /// /// <seealso cref="ZTest"/> /// <seealso cref="NormalDistribution"/> /// <seealso cref="TwoSampleTTest"/> /// <seealso cref="TwoSampleZTest"/> /// <seealso cref="PairedTTest"/> /// /// <seealso cref="Accord.Statistics.Distributions.Univariate.TDistribution"/> /// [Serializable] public class TTest : HypothesisTest<TDistribution> { private TTestPowerAnalysis powerAnalysis; /// <summary> /// Gets the power analysis for the test, if available. /// </summary> /// public IPowerAnalysis Analysis { get { return powerAnalysis; } } /// <summary> /// Gets the standard error of the estimated value. /// </summary> /// public double StandardError { get; private set; } /// <summary> /// Gets the estimated parameter value, such as the sample's mean value. /// </summary> /// public double EstimatedValue { get; private set; } /// <summary> /// Gets the hypothesized parameter value. /// </summary> /// public double HypothesizedValue { get; private set; } /// <summary> /// Gets the 95% confidence interval for the <see cref="EstimatedValue"/>. /// </summary> /// public DoubleRange Confidence { get; protected set; } /// <summary> /// Gets the alternative hypothesis under test. If the test is /// <see cref="IHypothesisTest.Significant"/>, the null hypothesis can be rejected /// in favor of this alternative hypothesis. /// </summary> /// public OneSampleHypothesis Hypothesis { get; protected set; } /// <summary> /// Gets a confidence interval for the estimated value /// within the given confidence level percentage. /// </summary> /// /// <param name="percent">The confidence level. Default is 0.95.</param> /// /// <returns>A confidence interval for the estimated value.</returns> /// public DoubleRange GetConfidenceInterval(double percent = 0.95) { double u = PValueToStatistic(1.0 - percent); return new DoubleRange( EstimatedValue - u * StandardError, EstimatedValue + u * StandardError); } /// <summary> /// Tests the null hypothesis that the population mean is equal to a specified value. /// </summary> /// /// <param name="statistic">The test statistic.</param> /// <param name="degreesOfFreedom">The degrees of freedom for the test distribution.</param> /// <param name="hypothesis">The alternative hypothesis (research hypothesis) to test.</param> /// public TTest(double statistic, double degreesOfFreedom, OneSampleHypothesis hypothesis = OneSampleHypothesis.ValueIsDifferentFromHypothesis) { Compute(statistic, degreesOfFreedom, hypothesis); } /// <summary> /// Tests the null hypothesis that the population mean is equal to a specified value. /// </summary> /// /// <param name="estimatedValue">The estimated value (θ).</param> /// <param name="standardError">The standard error of the estimation (SE).</param> /// <param name="hypothesizedValue">The hypothesized value (θ').</param> /// <param name="degreesOfFreedom">The degrees of freedom for the test distribution.</param> /// <param name="alternate">The alternative hypothesis (research hypothesis) to test.</param> /// public TTest(double estimatedValue, double standardError, double degreesOfFreedom, double hypothesizedValue = 0, OneSampleHypothesis alternate = OneSampleHypothesis.ValueIsDifferentFromHypothesis) { Compute(estimatedValue, standardError, degreesOfFreedom, hypothesizedValue, alternate); } /// <summary> /// Tests the null hypothesis that the population mean is equal to a specified value. /// </summary> /// /// <param name="sample">The data samples from which the test will be performed.</param> /// <param name="hypothesizedMean">The constant to be compared with the samples.</param> /// <param name="alternate">The alternative hypothesis (research hypothesis) to test.</param> /// public TTest(double[] sample, double hypothesizedMean = 0, OneSampleHypothesis alternate = OneSampleHypothesis.ValueIsDifferentFromHypothesis) { int n = sample.Length; double mean = Measures.Mean(sample); double stdDev = Measures.StandardDeviation(sample, mean); double stdError = Measures.StandardError(n, stdDev); Compute(n, mean, hypothesizedMean, stdError, alternate); power(stdDev, n); } /// <summary> /// Creates a T-Test. /// </summary> /// protected TTest() { } /// <summary> /// Tests the null hypothesis that the population mean is equal to a specified value. /// </summary> /// /// <param name="mean">The sample's mean value.</param> /// <param name="stdDev">The standard deviation for the samples.</param> /// <param name="samples">The number of observations in the sample.</param> /// <param name="hypothesizedMean">The constant to be compared with the samples.</param> /// <param name="alternate">The alternative hypothesis (research hypothesis) to test.</param> /// public TTest(double mean, double stdDev, int samples, double hypothesizedMean = 0, OneSampleHypothesis alternate = OneSampleHypothesis.ValueIsDifferentFromHypothesis) { double stdError = Measures.StandardError(samples, stdDev); Compute(samples, mean, hypothesizedMean, stdError, alternate); power(stdDev, samples); } /// <summary> /// Computes the T-Test. /// </summary> /// protected void Compute(int n, double mean, double hypothesizedMean, double stdError, OneSampleHypothesis hypothesis) { this.EstimatedValue = mean; this.StandardError = stdError; this.HypothesizedValue = hypothesizedMean; double df = n - 1; double t = (EstimatedValue - hypothesizedMean) / StandardError; Compute(t, df, hypothesis); } /// <summary> /// Computes the T-test. /// </summary> /// protected void Compute(double statistic, double df, OneSampleHypothesis alternate) { this.Statistic = statistic; this.StatisticDistribution = new TDistribution(df); this.Hypothesis = alternate; this.Tail = (DistributionTail)alternate; this.PValue = StatisticToPValue(Statistic); this.OnSizeChanged(); } /// <summary> /// Computes the T-test. /// </summary> /// private void Compute(double estimatedValue, double stdError, double degreesOfFreedom, double hypothesizedValue, OneSampleHypothesis alternate) { this.EstimatedValue = estimatedValue; this.StandardError = stdError; this.HypothesizedValue = hypothesizedValue; double df = degreesOfFreedom; double t = (EstimatedValue - hypothesizedValue) / StandardError; Compute(t, df, alternate); } private void power(double stdDev, int samples) { this.powerAnalysis = new TTestPowerAnalysis(Hypothesis) { Samples = samples, Effect = (EstimatedValue - HypothesizedValue) / stdDev, Size = Size, }; powerAnalysis.ComputePower(); } /// <summary>Update event.</summary> protected override void OnSizeChanged() { this.Confidence = GetConfidenceInterval(1.0 - Size); if (Analysis != null) { powerAnalysis.Size = Size; powerAnalysis.ComputePower(); } } /// <summary> /// Converts a given p-value to a test statistic. /// </summary> /// /// <param name="p">The p-value.</param> /// /// <returns>The test statistic which would generate the given p-value.</returns> /// public override double PValueToStatistic(double p) { return PValueToStatistic(p, StatisticDistribution, Tail); } /// <summary> /// Converts a given test statistic to a p-value. /// </summary> /// /// <param name="x">The value of the test statistic.</param> /// /// <returns>The p-value for the given statistic.</returns> /// public override double StatisticToPValue(double x) { return StatisticToPValue(x, StatisticDistribution, Tail); } /// <summary> /// Converts a given test statistic to a p-value. /// </summary> /// /// <param name="t">The value of the test statistic.</param> /// <param name="type">The tail of the test distribution.</param> /// <param name="distribution">The test distribution.</param> /// /// <returns>The p-value for the given statistic.</returns> /// public static double StatisticToPValue(double t, TDistribution distribution, DistributionTail type) { double p; switch (type) { case DistributionTail.TwoTail: p = 2.0 * distribution.ComplementaryDistributionFunction(Math.Abs(t)); break; case DistributionTail.OneUpper: p = distribution.ComplementaryDistributionFunction(t); break; case DistributionTail.OneLower: p = distribution.DistributionFunction(t); break; default: throw new InvalidOperationException(); } return p; } /// <summary> /// Converts a given p-value to a test statistic. /// </summary> /// /// <param name="p">The p-value.</param> /// <param name="type">The tail of the test distribution.</param> /// <param name="distribution">The test distribution.</param> /// /// <returns>The test statistic which would generate the given p-value.</returns> /// public static double PValueToStatistic(double p, TDistribution distribution, DistributionTail type) { double t; switch (type) { case DistributionTail.OneLower: t = distribution.InverseDistributionFunction(p); break; case DistributionTail.OneUpper: t = distribution.InverseDistributionFunction(1.0 - p); break; case DistributionTail.TwoTail: t = distribution.InverseDistributionFunction(1.0 - p / 2.0); break; default: throw new InvalidOperationException(); } return t; } } }
using UnityEngine; namespace UnityExtensions.AI.Sensors { [RequireComponent(typeof(SphereCollider))] public abstract class ASensor : MonoBehaviour { #region Attributes protected bool m_otherDetected; protected SphereCollider m_collider; #endregion Attributes #region Methods #region Accessors and Mutators //_____________________________________________________________________ ACCESSORS AND MUTATORS _____________________________________________________________________ #endregion Accessors and Mutators #region Inherited Methods //_______________________________________________________________________ INHERITED METHODS _______________________________________________________________________ // Use this for initialization protected void Start() { m_collider = GetComponent<SphereCollider>(); } #endregion Inherited Methods #region Events //_____________________________________________________________________________ EVENTS _____________________________________________________________________________ public delegate void SensorEventHandler(GameObject detectedObject); #endregion Events #region Other Methods //__________________________________________________________________________ OTHER METHODS _________________________________________________________________________ #endregion Other Methods #endregion Methods } }
 namespace KRF.Core.Entities.MISC { public enum ValueListType { Territory = 1, JobType = 2, AddressType = 3, LeadSource = 4, CustomerType = 5, RoofType = 6, RoofPitch = 7, UnitOfMeasure = 8, Manufacturer = 9, Category = 10, Division = 11, Style = 12, Color = 13, JobStatus = 14, LeadStatus = 15 } }
using System; using ComputerBuilderClasses.Contracts; using ComputerBuilderClasses.SystemComponents; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputerBuilderTests.CPUTests { [TestClass] public class SquareNumberTests { [TestMethod] public void SquareNumberShouldReturnPositiveNumberWhenPositiveParamPassedIn() { ICentralProcessingUnit cpu = new Cpu128Bit(2); int dataToPass = 16; int resultData = cpu.SquareNumber(dataToPass); Assert.IsTrue(resultData > 0); } [TestMethod] public void SquareNumberShouldReturnCorectNumberWhenPositiveParamPassedIn() { ICentralProcessingUnit cpu = new Cpu128Bit(2); int dataToPass = 16; int resultData = cpu.SquareNumber(dataToPass); Assert.AreEqual(256, resultData); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void SquareNumberShouldThrowExceptionWhenNegativeParameterPassed() { ICentralProcessingUnit cpu = new Cpu128Bit(2); int dataToPass = -10; cpu.SquareNumber(dataToPass); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void SquareNumberShouldThrowExceptionWhenOverflowingParameterPassed() { ICentralProcessingUnit cpu = new Cpu128Bit(2); int dataToPass = 2001; cpu.SquareNumber(dataToPass); } } }
using LuaInterface; using SLua; using System; using System.Collections; using UnityEngine; public class Lua_UnityEngine_MonoBehaviour : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { MonoBehaviour o = new MonoBehaviour(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int Invoke(IntPtr l) { int result; try { MonoBehaviour monoBehaviour = (MonoBehaviour)LuaObject.checkSelf(l); string text; LuaObject.checkType(l, 2, out text); float num; LuaObject.checkType(l, 3, out num); monoBehaviour.Invoke(text, num); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int InvokeRepeating(IntPtr l) { int result; try { MonoBehaviour monoBehaviour = (MonoBehaviour)LuaObject.checkSelf(l); string text; LuaObject.checkType(l, 2, out text); float num; LuaObject.checkType(l, 3, out num); float num2; LuaObject.checkType(l, 4, out num2); monoBehaviour.InvokeRepeating(text, num, num2); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int CancelInvoke(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 1) { MonoBehaviour monoBehaviour = (MonoBehaviour)LuaObject.checkSelf(l); monoBehaviour.CancelInvoke(); LuaObject.pushValue(l, true); result = 1; } else if (num == 2) { MonoBehaviour monoBehaviour2 = (MonoBehaviour)LuaObject.checkSelf(l); string text; LuaObject.checkType(l, 2, out text); monoBehaviour2.CancelInvoke(text); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int IsInvoking(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (num == 1) { MonoBehaviour monoBehaviour = (MonoBehaviour)LuaObject.checkSelf(l); bool b = monoBehaviour.IsInvoking(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b); result = 2; } else if (num == 2) { MonoBehaviour monoBehaviour2 = (MonoBehaviour)LuaObject.checkSelf(l); string text; LuaObject.checkType(l, 2, out text); bool b2 = monoBehaviour2.IsInvoking(text); LuaObject.pushValue(l, true); LuaObject.pushValue(l, b2); result = 2; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int StartCoroutine(IntPtr l) { int result; try { int num = LuaDLL.lua_gettop(l); if (LuaObject.matchType(l, num, 2, typeof(string))) { MonoBehaviour monoBehaviour = (MonoBehaviour)LuaObject.checkSelf(l); string text; LuaObject.checkType(l, 2, out text); Coroutine o = monoBehaviour.StartCoroutine(text); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } else if (LuaObject.matchType(l, num, 2, typeof(IEnumerator))) { MonoBehaviour monoBehaviour2 = (MonoBehaviour)LuaObject.checkSelf(l); IEnumerator enumerator; LuaObject.checkType<IEnumerator>(l, 2, out enumerator); Coroutine o2 = monoBehaviour2.StartCoroutine(enumerator); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o2); result = 2; } else if (num == 3) { MonoBehaviour monoBehaviour3 = (MonoBehaviour)LuaObject.checkSelf(l); string text2; LuaObject.checkType(l, 2, out text2); object obj; LuaObject.checkType<object>(l, 3, out obj); Coroutine o3 = monoBehaviour3.StartCoroutine(text2, obj); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o3); result = 2; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int StartCoroutine_Auto(IntPtr l) { int result; try { MonoBehaviour monoBehaviour = (MonoBehaviour)LuaObject.checkSelf(l); IEnumerator enumerator; LuaObject.checkType<IEnumerator>(l, 2, out enumerator); Coroutine o = monoBehaviour.StartCoroutine_Auto(enumerator); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int StopCoroutine(IntPtr l) { int result; try { int total = LuaDLL.lua_gettop(l); if (LuaObject.matchType(l, total, 2, typeof(Coroutine))) { MonoBehaviour monoBehaviour = (MonoBehaviour)LuaObject.checkSelf(l); Coroutine coroutine; LuaObject.checkType<Coroutine>(l, 2, out coroutine); monoBehaviour.StopCoroutine(coroutine); LuaObject.pushValue(l, true); result = 1; } else if (LuaObject.matchType(l, total, 2, typeof(IEnumerator))) { MonoBehaviour monoBehaviour2 = (MonoBehaviour)LuaObject.checkSelf(l); IEnumerator enumerator; LuaObject.checkType<IEnumerator>(l, 2, out enumerator); monoBehaviour2.StopCoroutine(enumerator); LuaObject.pushValue(l, true); result = 1; } else if (LuaObject.matchType(l, total, 2, typeof(string))) { MonoBehaviour monoBehaviour3 = (MonoBehaviour)LuaObject.checkSelf(l); string text; LuaObject.checkType(l, 2, out text); monoBehaviour3.StopCoroutine(text); LuaObject.pushValue(l, true); result = 1; } else { LuaObject.pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function to call"); result = 2; } } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int StopAllCoroutines(IntPtr l) { int result; try { MonoBehaviour monoBehaviour = (MonoBehaviour)LuaObject.checkSelf(l); monoBehaviour.StopAllCoroutines(); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int print_s(IntPtr l) { int result; try { object obj; LuaObject.checkType<object>(l, 1, out obj); MonoBehaviour.print(obj); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_useGUILayout(IntPtr l) { int result; try { MonoBehaviour monoBehaviour = (MonoBehaviour)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, monoBehaviour.get_useGUILayout()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_useGUILayout(IntPtr l) { int result; try { MonoBehaviour monoBehaviour = (MonoBehaviour)LuaObject.checkSelf(l); bool useGUILayout; LuaObject.checkType(l, 2, out useGUILayout); monoBehaviour.set_useGUILayout(useGUILayout); LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.MonoBehaviour"); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MonoBehaviour.Invoke)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MonoBehaviour.InvokeRepeating)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MonoBehaviour.CancelInvoke)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MonoBehaviour.IsInvoking)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MonoBehaviour.StartCoroutine)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MonoBehaviour.StartCoroutine_Auto)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MonoBehaviour.StopCoroutine)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MonoBehaviour.StopAllCoroutines)); LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MonoBehaviour.print_s)); LuaObject.addMember(l, "useGUILayout", new LuaCSFunction(Lua_UnityEngine_MonoBehaviour.get_useGUILayout), new LuaCSFunction(Lua_UnityEngine_MonoBehaviour.set_useGUILayout), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_MonoBehaviour.constructor), typeof(MonoBehaviour), typeof(Behaviour)); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Playables; using UnityEngine.EventSystems; using Spine.Unity; public class Cajas : MonoBehaviour { public GameObject Cofre; public int abiertas; public GameObject otra; public int deb1; public int deb2; public int deb3; bool listo1; bool listo2; bool listo3; public GameObject card1; public GameObject card2; public GameObject card3; //CANTIDAD DE CARTAS int carta1; int carta2; int carta3; //DE QUE A QUE CARTA PUEDE DESTAPAR public int minima; public int maxima;//1,2,7,8,9,11,15 int cajas; public UnityEngine.UI.Text cajasT; bool esconder; // Use this for initialization void Start () { abiertas = 0; deb1 = Random.Range(minima,maxima); deb2 = Random.Range(minima,maxima); deb3 = Random.Range(minima,maxima); listo1 = true; cajas = PlayerPrefs.GetInt("caja1"); } // Update is called once per frame void Update () { cajasT.text = cajas.ToString(); PlayerPrefs.SetInt("caja1", cajas); if(listo1) { print("TODOS DEBERIAN SER DIFERENTES"); card1.GetComponent<skinCarta>().skinsToCombine[0] = deb1.ToString(); card2.GetComponent<skinCarta>().skinsToCombine[0] = deb2.ToString(); card3.GetComponent<skinCarta>().skinsToCombine[0] = deb3.ToString(); PlayerPrefs.SetInt("card"+deb1, 1); PlayerPrefs.SetInt("card"+deb2, 1); PlayerPrefs.SetInt("card"+deb3, 1); //CANTIDAD DE CARTAS carta1 = PlayerPrefs.GetInt("card"+deb1+"cantidad"); PlayerPrefs.SetInt("card"+deb1+"cantidad", carta1+1); carta2 = PlayerPrefs.GetInt("card"+deb2+"cantidad"); PlayerPrefs.SetInt("card"+deb2+"cantidad", carta2+1); carta3 = PlayerPrefs.GetInt("card"+deb3+"cantidad"); PlayerPrefs.SetInt("card"+deb3+"cantidad", carta3+1); listo1 = false; } if(abiertas >= 3 && cajas <= 0 && !esconder) { //otra.SetActive(true); StartCoroutine(cerrar()); esconder = true; } if(abiertas >= 3 && cajas >= 1 && !esconder) { StartCoroutine(cerrarNuevo()); esconder = true; } } public GameObject menu; IEnumerator cerrar() { yield return new WaitForSeconds(2); card1.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "salida", false); card2.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "salida", false); card3.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "salida", false); abiertas = 0; esconder = false; Cofre.GetComponent<Animator>().SetBool("cerrar", true); menu.GetComponent<Animator>().SetBool("sale", false); menu.GetComponent<Animator>().SetBool("entra", true); } IEnumerator cerrarNuevo() { yield return new WaitForSeconds(2); card1.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "salida", false); card2.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "salida", false); card3.GetComponent<SkeletonGraphic>().AnimationState.SetAnimation(0, "salida", false); Cofre.GetComponent<Animator>().SetBool("cerrar", true); menu.GetComponent<Animator>().SetBool("sale", false); StartCoroutine(abreNuevo()); } IEnumerator abreNuevo() { yield return new WaitForSeconds(2); abiertas = 0; esconder = false; Cofre.GetComponent<Animator>().SetBool("reiniciar", true); } public void Reopen() { if(cajas >= 1) { //otra.SetActive(false); cajas -= 1; loading.nombre = "cajas"; Application.LoadLevel("Load"); } } /*public void salir () { CamMenu.segundo = true; Application.LoadLevel("Menu"); }*/ }
using System; using System.Collections.Generic; namespace API_GiangVien.Models { public partial class Lichlamviec { public int MaLlv { get; set; } public int MaGv { get; set; } public DateTime? NgayBd { get; set; } public DateTime? NgayKt { get; set; } public string CongViec { get; set; } public string Thu { get; set; } public string Tuan { get; set; } public string DiaChi { get; set; } public virtual Giangvien MaGvNavigation { get; set; } } }
using System; using UnityEngine; [System.Serializable] [CreateAssetMenu] public class CurrencyItemData : BaseItemData { }
using UnityEngine; using UnityEngine.UI; using System.Collections; using System; public class CountdownDisplayManager : IDisplayManager { public Text conferenceTitleText; public Text speakerNameText; public RawImage userImageContainer; public string conferenceTitle; public string speakerName; public Sprite userImage; public DateTime conferenceTime; public Text textHours; public Text textMins; public Text textSecs; public Text textHoursTitle; public Text textMinsTitle; public Text textSecsTitle; public string daysTitle; public string dayTitle; public string hoursTitle; public string minutesTitle; public string secondsTitle; public override void InitializeDisplay (int displayId) { _displayId = displayId; conferenceTitleText.text = Preloader.instance.GetString (Preloader.instance.GetRunningDisplay(), "title"); speakerNameText.text = Preloader.instance.GetString (Preloader.instance.GetRunningDisplay(), "subtitle"); userImageContainer.texture = Preloader.instance.GetImage (Preloader.instance.GetRunningDisplay(), "image"); conferenceTime = DateTime.Parse (Preloader.instance.GetString (Preloader.instance.GetRunningDisplay(), "time")); //Debug.Log (Preloader.instance.GetString (Preloader.instance.GetRunningDisplay(), "time")); //Debug.Log (conferenceTime); //Debug.Log (DateTime.UtcNow); } public override void FinalizeDisplay () { Destroy (userImageContainer.texture); System.GC.Collect (); } // Update is called once per frame void Update () { TimeSpan timeUntilConference = conferenceTime - DateTime.UtcNow; int days = timeUntilConference.Days; Debug.Log (days); string hours = "0"; string minutes = "0"; string seconds = "0"; if (timeUntilConference.Days > 0) { if(timeUntilConference.Days > 1) { textHoursTitle.text = daysTitle; } else { textHoursTitle.text = dayTitle; } textMinsTitle.text = hoursTitle; textSecsTitle.text = minutesTitle; hours = timeUntilConference.Days.ToString (); minutes = timeUntilConference.Hours.ToString (); seconds = timeUntilConference.Minutes.ToString (); } else { textHoursTitle.text = hoursTitle; textMinsTitle.text = minutesTitle; textSecsTitle.text = secondsTitle; // The -1 is a hack to be revised since for some reason time is coming with an extra hour from the backend hours = (Mathf.FloorToInt ((float)timeUntilConference.TotalHours)).ToString (); minutes = timeUntilConference.Minutes.ToString (); seconds = timeUntilConference.Seconds.ToString (); if(int.Parse(hours) < 0) { hours = minutes = seconds = "00"; } } textHours.text = hours.Length == 1 ? "0" + hours : hours; textMins.text = minutes.Length == 1 ? "0" + minutes : minutes; textSecs.text = seconds.Length == 1 ? "0" + seconds : seconds; } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using API.Dtos; namespace API.Services { public interface IUserService { Task<UserToReturn> GetAsync(int id); Task<IEnumerable<UserToReturn>> GetAllAsync(); Task<IEnumerable<UserToReturn>> GetAllUsersAsync(); Task<IEnumerable<UserToReturn>> GetAllAdminsAsync(); Task<IAsyncResult> DeleteAsync(int id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using PowerShapeDotNet.Enums; using PowerShapeDotNet.Macros; namespace PowerShapeDotNet.Objects { /// <summary> /// class for PCurve Type Objects /// </summary> public class PSDNObjectPCurve : PSDNObjectBase { #region PROPIERTIES /// <summary> /// Gets a value indicating whether if the pcurve is closed /// </summary> /// <value> /// <c>true</c> if the pcurve is closed; otherwise, <c>false</c>. /// </value> public bool IsClosed { get { return psMacros.PCurve_Closed(ObjectName); } set { this.Select(true); psMacros.SendMacro(((value) ? "CLOSE" : "OPEN")); } } /// <summary> /// Gets a value indicating whether if the pcurve is on the edge of a surface /// </summary> /// <value> /// <c>true</c> if the pcurve is on the edge of a surface; otherwise, <c>false</c>. /// </value> public bool IsEdge { get { return psMacros.PCurve_Edge(ObjectName); } } /// <summary> /// Gets the surface on which the pcurve lies /// </summary> /// <value> /// The surface on which the pcurve lies /// </value> public PSDNObjectBase Parent { get { return new PSDNObjectBase(psMacros.Find_Type_ByName(psMacros.PCurve_Parent_Name(ObjectName)), psMacros.PCurve_Parent_Name(ObjectName)); } } /// <summary> /// Gets a value indicating whether if the pcurve exists in any boundary /// </summary> /// <value> /// <c>true</c> if the pcurve exists in any boundary; otherwise, <c>false</c>. /// </value> public bool InBoundary { get { return psMacros.PCurve_InBoundary(ObjectName); } } /// <summary> /// Gets a value indicating whether if start the coordinates of the pcurve exists /// </summary> /// <value> /// <c>true</c> if start the coordinates of the pcurve exists; otherwise, <c>false</c>. /// </value> public bool StartExists { get { return psMacros.PCurve_Start_Exists(ObjectName); } } /// <summary> /// Gets the start coordinates [x,y,z] of the PCurve /// </summary> /// <value> /// The start coordinates [x,y,z] of the PCurve /// </value> public PSDNPoint3D Start { get { return ((StartExists) ? new PSDNPoint3D(psMacros.PCurve_Start(ObjectName)) : null); } } /// <summary> /// Gets the start coordinates [x,y,z] of the PCurve /// </summary> /// <value> /// The start coordinates [x,y,z] of the PCurve /// </value> public PSDNPoint3D StartXYZ { get { return ((StartExists) ? new PSDNPoint3D(psMacros.PCurve_Start_XYZ(ObjectName)) : null); } } /// <summary> /// Gets tu coordinates [t,u,0] of the start position in the PCurve /// </summary> /// <value> /// The tu coordinates [t,u,0] of the start position in the PCurve /// </value> public PSDNPoint3D StartTU { get { return ((StartExists) ? new PSDNPoint3D(psMacros.PCurve_Start_TU(ObjectName)) : null); } } /// <summary> /// Gets a value indicating whether if end the coordinates of the pcurve exists /// </summary> /// <value> /// <c>true</c> if end the coordinates of the pcurve exists; otherwise, <c>false</c>. /// </value> public bool EndExists { get { return psMacros.PCurve_End_Exists(ObjectName); } } /// <summary> /// Gets the end coordinates [x,y,z] of the PCurve /// </summary> /// <value> /// The end coordinates [x,y,z] of the PCurve /// </value> public PSDNPoint3D End { get { return ((EndExists) ? new PSDNPoint3D(psMacros.PCurve_End(ObjectName)) : null); } } /// <summary> /// Gets the end coordinates [x,y,z] of the PCurve /// </summary> /// <value> /// The end coordinates [x,y,z] of the PCurve /// </value> public PSDNPoint3D EndXYZ { get { return ((EndExists) ? new PSDNPoint3D(psMacros.PCurve_End_XYZ(ObjectName)) : null); } } /// <summary> /// Gets tu coordinates [t,u,0] of the end position in the PCurve /// </summary> /// <value> /// The tu coordinates [t,u,0] of the end position in the PCurve /// </value> public PSDNPoint3D EndTU { get { return ((EndExists) ? new PSDNPoint3D(psMacros.PCurve_End_TU(ObjectName)) : null); } } /// <summary> /// Gets number of points in the pcurve /// </summary> /// <value> /// Thenumber of points in the pcurve /// </value> public int PCurvePointsNumber { get { return psMacros.PCurve_Number(ObjectName); } } /// <summary> /// Gets the point list. /// </summary> /// <value> /// The point list. /// </value> public List<PSDNPCurvePoint> PointList { get { if(PCurvePointsNumber > 0) { List<PSDNPCurvePoint> pointList = new List<PSDNPCurvePoint>(); for(int cont = 1; cont <= PCurvePointsNumber; cont++) { pointList.Add(new PSDNPCurvePoint(psMacros, ObjectName, cont, Parent)); } return pointList; } return null; } } #endregion #region CONSTRUCTORS /// <summary> /// Initializes a new instance of the <see cref="PSDNObjectPCurve"/> class. /// </summary> /// <param name="state">The state.</param> /// <param name="index">The index.</param> public PSDNObjectPCurve(ObjectState state, int index) : base(state, index) { } /// <summary> /// Initializes a new instance of the <see cref="PSDNObjectPCurve"/> class. /// </summary> /// <param name="typeObject">The type object.</param> /// <param name="nameObject">The name object.</param> public PSDNObjectPCurve(TypeObject typeObject, string nameObject) : base (typeObject, nameObject) { } /// <summary> /// Initializes a new instance of the <see cref="PSDNObjectPCurve"/> class. /// </summary> /// <param name="typeObject">The type object.</param> /// <param name="idObject">The identifier object.</param> public PSDNObjectPCurve(TypeObject typeObject, int idObject) : base (typeObject, idObject) { } #endregion } }
using System.Collections.Generic; using System.Linq; using Plus.HabboHotel.Achievements; using Plus.HabboHotel.GameClients; using Plus.HabboHotel.Users; namespace Plus.Communication.Packets.Outgoing.GameCenter { internal class GameAchievementListComposer : MessageComposer { public Habbo Habbo { get; } public ICollection<Achievement> Achievements { get; } public int GameId { get; } public GameAchievementListComposer(GameClient session, ICollection<Achievement> achievements, int gameId) : base(ServerPacketHeader.GameAchievementListMessageComposer) { Habbo = session.GetHabbo(); Achievements = achievements; GameId = gameId; } public override void Compose(ServerPacket packet) { packet.WriteInteger(GameId); packet.WriteInteger(Achievements.Count); foreach (Achievement ach in Achievements.ToList()) { UserAchievement userData = Habbo.GetAchievementData(ach.GroupName); int targetLevel = (userData != null ? userData.Level + 1 : 1); AchievementLevel targetLevelData = ach.Levels[targetLevel]; packet.WriteInteger(ach.Id); // ach id packet.WriteInteger(targetLevel); // target level packet.WriteString(ach.GroupName + targetLevel); // badge packet.WriteInteger(targetLevelData.Requirement); // requirement packet.WriteInteger(targetLevelData.Requirement); // requirement packet.WriteInteger(targetLevelData.RewardPixels); // pixels packet.WriteInteger(0); // ach score packet.WriteInteger(userData != null ? userData.Progress : 0); // Current progress packet.WriteBoolean(userData != null ? (userData.Level >= ach.Levels.Count) : false); // Set 100% completed(??) packet.WriteString(ach.Category); packet.WriteString("basejump"); packet.WriteInteger(0); // total levels packet.WriteInteger(0); } packet.WriteString(""); } } }
/** * Created 25/11/2020 * By: Omer Farkhand * Last Modified DD/MM/YYYY * By: Aswad Mirza * * Contributors: Aswad Mirza, Omer Farkand */ using System.Collections.Generic; using UnityEngine; /* * EnemyGenerator instantiates enemies on the spawn point objects placed in the level. * Also handles trap room enemies to spawn in. */ public class EnemyGenerator : MonoBehaviour { public GameObject Myoviridae; public GameObject Cancer; public GameObject EnemyContainer; public GameObject[] spawnPoints; public GameObject spawnEffect; //public AudioSource audioSource; public GameObject Door; Vector3 objectPos; public float maxXPos; public float minXPos; public float maxZPos; public float minZPos; private List<GameObject> enemiesSpawned = new List<GameObject>(); private bool spawned = false; // Start is called before the first frame update void Start() { // Assigns the min and max values objectPos = this.gameObject.transform.position; minXPos = objectPos.x - 10f; maxXPos = minXPos + 10f; minZPos = objectPos.z - 10f; maxZPos = minZPos + 10f; } // Update is called once per frame void Update() { //destroys the game obect if all the enemies are dead and disables the door if (Door != null && AreEnemiesDead()) { Door.SetActive(false); Destroy(gameObject); } } // OnTriggerEnter detects all trigger collisions on entry private void OnTriggerEnter(Collider other) { // Condition checks if the colliding object has a Player tag if (other.gameObject.tag == "Player") { Spawn(); if (Door != null) { Door.SetActive(true); } else { Destroy(this.gameObject); } } } // Spawn instantiates Enemies at their spawn point positions void Spawn() { // If we havnt spawned enemies, then spawn them if (!spawned) { if (spawnPoints.Length >= 4) { for (int i = 0; i < spawnPoints.Length; i++) { if (spawnPoints.Length == 10) { if (spawnPoints.Length - i <= 4) { GameObject effect = Instantiate(spawnEffect, spawnPoints[i].transform.position, spawnEffect.transform.rotation); //audioSource.transform.position = spawnPoints[i].transform.position; //audioSource.Play(); GameObject virus = Instantiate(Cancer, spawnPoints[i].transform.position, Quaternion.identity); //spawnPoints[i].Equals(virus); //spawnPoints[i].transform.parent = EnemyContainer.transform; virus.transform.parent = EnemyContainer.transform; enemiesSpawned.Add(virus); Debug.Log("Spawned"); //Destroy(effect); } else { GameObject effect = Instantiate(spawnEffect, spawnPoints[i].transform.position, spawnEffect.transform.rotation); //audioSource.transform.position = spawnPoints[i].transform.position; //audioSource.Play(); GameObject virus = Instantiate(Myoviridae, spawnPoints[i].transform.position, Quaternion.identity); //spawnPoints[i].Equals(virus); //spawnPoints[i].transform.parent = EnemyContainer.transform; virus.transform.parent = EnemyContainer.transform; enemiesSpawned.Add(virus); Debug.Log("Spawned"); //Destroy(effect); } } else { if (spawnPoints.Length - i <= 2) { GameObject effect = Instantiate(spawnEffect, spawnPoints[i].transform.position, spawnEffect.transform.rotation); //audioSource.transform.position = spawnPoints[i].transform.position; //audioSource.Play(); GameObject virus = Instantiate(Cancer, spawnPoints[i].transform.position, Quaternion.identity); //spawnPoints[i].Equals(virus); //spawnPoints[i].transform.parent = EnemyContainer.transform; virus.transform.parent = EnemyContainer.transform; enemiesSpawned.Add(virus); Debug.Log("Spawned"); //Destroy(effect); } else { GameObject effect = Instantiate(spawnEffect, spawnPoints[i].transform.position, spawnEffect.transform.rotation); //audioSource.transform.position = spawnPoints[i].transform.position; //audioSource.Play(); GameObject virus = Instantiate(Myoviridae, spawnPoints[i].transform.position, Quaternion.identity); //spawnPoints[i].Equals(virus); //spawnPoints[i].transform.parent = EnemyContainer.transform; virus.transform.parent = EnemyContainer.transform; enemiesSpawned.Add(virus); Debug.Log("Spawned"); //Destroy(effect); } } } spawned = true; Debug.Log("Spawn " + enemiesSpawned.Count); } else { for (int i = 0; i < spawnPoints.Length; i++) { GameObject effect = Instantiate(spawnEffect, spawnPoints[i].transform.position, spawnEffect.transform.rotation); //audioSource.transform.position = spawnPoints[i].transform.position; //audioSource.Play(); GameObject virus = Instantiate(Myoviridae, spawnPoints[i].transform.position, Quaternion.identity); //spawnPoints[i].Equals(virus); //spawnPoints[i].transform.parent = EnemyContainer.transform; virus.transform.parent = EnemyContainer.transform; enemiesSpawned.Add(virus); Debug.Log("Spawned"); //Destroy(effect); } spawned = true; Debug.Log("Spawn " + enemiesSpawned.Count); } } } // [Returns whether or not all enemies spawned by this script been killed or not, return false if there is still and enemy alive // or if it has not spawned enemies yet, will return true if all enemies spawned are dead or null since they are Destroyed on death] bool AreEnemiesDead() { bool check = true; if (spawned) { foreach (GameObject virus in enemiesSpawned) { // if the virus is destroyed this will be null if (virus != null) { check = false; break; } } } else { check = false; } return check; } }
 using System; namespace ContactManager.Business { public class Persoon : Contact { public DateTime? GeboorteDatum { get; set; } public override string ToString() { return $"{GeboorteDatum:MM/dd/yyyy}"; } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using System; using System.Threading; #endregion namespace DotNetNuke.Collections.Internal { internal class ReaderWriterSlimLock : ISharedCollectionLock { private bool _disposed; private ReaderWriterLockSlim _lock; public ReaderWriterSlimLock(ReaderWriterLockSlim @lock) { _lock = @lock; } #region ISharedCollectionLock Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion private void EnsureNotDisposed() { if (_disposed) { throw new ObjectDisposedException("ReaderWriterSlimLock"); } } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { //free managed resources here } //free unmanaged resrources here if (_lock.IsReadLockHeld) { _lock.ExitReadLock(); } else if (_lock.IsWriteLockHeld) { _lock.ExitWriteLock(); } else if (_lock.IsUpgradeableReadLockHeld) { _lock.ExitUpgradeableReadLock(); } _lock = null; _disposed = true; } } ~ReaderWriterSlimLock() { Dispose(false); } } }
using UnityEngine; namespace syscrawl.Common.Utils { public static class RandomUtils { public static Vector3 RandomVectorBetweenRange( Vector3 minimum, Vector3 maximum) { var x = Random.Range(minimum.x, maximum.x + 1); var y = Random.Range(minimum.y, maximum.y + 1); var z = Random.Range(minimum.z, maximum.z + 1); return new Vector3(x, y, z); } public static bool RandomBool() { return Random.Range(0, 2) == 0; } } }
namespace Timesheet.DataAccess.csv { public class CsvSettings { public CsvSettings(char delimeter, string path) { Delimeter = delimeter; Path = path; } public char Delimeter { get; } public string Path { get; } } }
using System; using Server.Items; namespace Server.Items { public class PhoenixCasterLantern : MetalKiteShield { public override SetItem SetID{ get{ return SetItem.PhoenixCaster; } } public override int Pieces{ get{ return 14; } } [Constructable] public PhoenixCasterLantern() : base() { ItemID = 2597; Name = "Blinding Light"; SetHue = 43; Attributes.NightSight = 1; Attributes.DefendChance = 25; Attributes.SpellChanneling = 1; Attributes.BonusHits = 15; PhysicalBonus = 15; EnergyBonus = 9; SetAttributes.LowerRegCost = 100; SetAttributes.LowerManaCost = 50; SetAttributes.Luck = 2500; SetAttributes.BonusInt = 10; SetSkillBonuses.SetValues( 0, SkillName.Meditation, 120 ); SetSelfRepair = 5; SetPhysicalBonus = 10; SetFireBonus = 10; SetColdBonus = 10; SetPoisonBonus = 10; SetEnergyBonus = 10; } public PhoenixCasterLantern( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
using UnityEngine; public class AudioRPC : MonoBehaviour { public AudioClip marco; public AudioClip polo; [PunRPC] void Marco() { Debug.Log("Marco"); this.GetComponent<AudioSource>().clip = marco; this.GetComponent<AudioSource>().Play(); } [PunRPC] void Polo() { // As RPC are not disabled even when the script is, we manually check it and return nothing if this is the case if (!this.enabled) { return; } Debug.Log("Polo"); this.GetComponent<AudioSource>().clip = polo; this.GetComponent<AudioSource>().Play(); } // Allow to disable the audio script when the app loses focus. But RPC are not disabled ! void OnApplicationFocus(bool focus) { this.enabled = focus; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQ_operations { public class Apple { public int Id { get; set; } public string SortName { get; set; } public double Size { get; set; } } public class Sort { public int Id { get; set; } public string SortName { get; set; } public string Color { get; set; } public double Price { get; set; } } class Program { static List<Apple> apples = new List<Apple> { new Apple{Id=1, SortName = "White", Size = 12}, new Apple{Id=2, SortName = "White", Size = 4}, new Apple{Id=3, SortName = "White", Size = 3}, new Apple{Id=4, SortName = "Red Green", Size = 22}, new Apple{Id=5, SortName = "Red Green", Size = 18}, new Apple{Id=6, SortName = "Red Green", Size = 5}, new Apple{Id=7, SortName = "Red", Size = 15}, new Apple{Id=8, SortName = "Red", Size = 15}, new Apple{Id=9, SortName = "Delicious grape", Size = 15}, }; static List<Sort> sorts = new List<Sort> { new Sort{Id=1, SortName = "Black melon", Color = "DarkRed", Price = 123.5}, new Sort{Id=2, SortName = "White", Color = "WhiteGreen", Price = 100.8}, new Sort{Id=2, SortName = "Red Crown", Color = "WhiteGreen", Price = 100.8}, new Sort{Id=3, SortName = "Red Green", Color = "RedGreen", Price = 99.9}, new Sort{Id=4, SortName = "Red", Color = "RedInDote", Price = 109.9}, new Sort{Id=5, SortName = "Delicious grape", Color = "DrakRed", Price = 89.9}, }; static void Main(string[] args) { //AallApplesJoinBySort(); AllApplesGroupBySort(); //AllApplesSizeMoreFive(); //AllSortsHaveAnyApple(); //AllSortsContainsSubString(); //AllApplesOrderBySize(); Console.ReadKey(); } private static void AllApplesOrderBySize() { ///summary ///Вывести все яблоки, предварительно отсортировав их по размеру (Order by) /// var query = apples.Select(a => new { Name = a.SortName, Size = a.Size }).OrderBy(x => x.Size).Distinct(); foreach (var q in query) { Console.WriteLine(q); } } private static void AllSortsContainsSubString() { //Вывести все сорта, название котрыx содержит определенную подстроку(Contains) var query = sorts.Where(s => s.SortName.Contains("Red")).Select(s => s.SortName); foreach (var q in query) { Console.WriteLine(q); } } private static void AllSortsHaveAnyApple() { ///summary ///Все сорта, по которым есть яблоки (any) /// var query = (from a in apples from s in sorts where a.SortName == s.SortName select new { Sort = a.SortName }).Distinct(); foreach (var q in query) { Console.WriteLine(q); } } private static void AllApplesSizeMoreFive() { ///summary ///Все яблоки, вес(или размер и т.д.) больше 5 (Where) ///summary var query = from a in apples where a.Size > 5 select new { Id = a.Id, Sort = a.SortName, Size = a.Size }; foreach (var q in query) { Console.WriteLine(q); } } private static void AllApplesGroupBySort() { var query = from a in apples //join s in sorts //on a.SortName equals s.SortName group a by a.SortName into g select new { Sort = g.Key, Count = g.Count() }; foreach (var q in query) { Console.WriteLine(q); } } private static void AallApplesJoinBySort() { ///summary ///Все яблоки с названием сорта (join) ///summary var query = from apple in apples join sort in sorts on apple.SortName equals sort.SortName select new { Id = apple.Id, Sort = sort.SortName, Size = apple.Size, Color = sort.Color, Price = sort.Price }; foreach (var q in query) { Console.WriteLine(q); } } } }
 using System.Collections.Generic; using System.Data; using System.Linq; using Dapper; using DataStore.Dal.Pager; using DataStore.Entity; using DataStore.Pager; namespace DataStore.Dal { public partial interface IRoleService { void Delete(List<long> idList); void Delete(long id); void Insert(List<Role> roleList); void Insert(Role role); void Update(List<Role> roleList); void Update(Role role); IEnumerable<Role> GetRoles(); IEnumerable<Role> GetRoles(string where, DynamicParameters parameters); Role GetSingleRole(string where, DynamicParameters parameters); Role GetRoleByPk(long id); PageDataView<Role> GetList(int page, int pageSize = 10); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CannonBallManager : MonoBehaviour { public IsACannonBall[] cannonBalls; // store all the game cannonballs public IsABigFucknFish[] fishs; // store all the fishes (see you and thanks for the fishes!) public static CannonBallManager Instance; // Use this for initialization void Start () { Instance = this; cannonBalls = FindObjectsOfType<IsACannonBall>(); fishs = FindObjectsOfType<IsABigFucknFish>(); } // Update is called once per frame void Update () { } public IsACannonBall GetCannonBall() { IsACannonBall cb = null; for (int i = 0; i < cannonBalls.Length; i++) { if (!cannonBalls[i].GetComponent<IAttackAux>().GetActive()) cb = cannonBalls[i]; } return cb; } public IsABigFucknFish GetBigFucknFish() { IsABigFucknFish fish = null; for (int i = 0; i < cannonBalls.Length; i++) { if (!cannonBalls[i].GetComponent<IAttackAux>().GetActive()) fish = fishs[i]; } return fish; } }
namespace Plus.Communication.Packets.Outgoing.Handshake { internal class SetUniqueIdComposer : MessageComposer { public string UniqueId { get; } public SetUniqueIdComposer(string id) : base(ServerPacketHeader.SetUniqueIdMessageComposer) { UniqueId = id; } public override void Compose(ServerPacket packet) { packet.WriteString(UniqueId); } } }
namespace LinkedList { using System; class LinkedList<T> : ICloneable { public T Value { get; set; } public LinkedList<T> NextNode { get; set; } public LinkedList(T value, LinkedList<T> nextNode = null) { this.Value = value; this.NextNode = nextNode; } object ICloneable.Clone() // Implicit implementation { return this.Clone(); } public LinkedList<T> Clone() // our method Clone() { // Copy the first element LinkedList<T> firstElement = new LinkedList<T>(this.Value); LinkedList<T> currentElement = firstElement; LinkedList<T> nextElement = this.NextNode; // Copy the rest of the elements while (nextElement != null) { currentElement.NextNode = new LinkedList<T>(nextElement.Value); nextElement = nextElement.NextNode; currentElement = currentElement.NextNode; } return firstElement; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawn : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } private void OnTriggerEnter(Collider other) { if(other.gameObject.tag == "Player") { Debug.Log("triggered"); } } private void OnTriggerExit(Collider other) { if (other.gameObject.tag == "Player") { Debug.Log("trigger left"); } } }
//------------------------------------------------------------------------------ // The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx. // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the License for the specific language governing rights and limitations under the License. // // The Original Code is nopCommerce. // The Initial Developer of the Original Code is NopSolutions. // All Rights Reserved. // // Contributor(s): _______. //------------------------------------------------------------------------------ using NopSolutions.NopCommerce.DataAccess; using NopSolutions.NopCommerce.DataAccess.Promo.Affiliates; namespace NopSolutions.NopCommerce.BusinessLogic.Promo.Affiliates { /// <summary> /// Affiliate manager /// </summary> public partial class AffiliateManager { #region Utilities private static AffiliateCollection DBMapping(DBAffiliateCollection dbCollection) { if (dbCollection == null) return null; AffiliateCollection collection = new AffiliateCollection(); foreach (DBAffiliate dbItem in dbCollection) { Affiliate item = DBMapping(dbItem); collection.Add(item); } return collection; } private static Affiliate DBMapping(DBAffiliate dbItem) { if (dbItem == null) return null; Affiliate item = new Affiliate(); item.AffiliateID = dbItem.AffiliateID; item.FirstName = dbItem.FirstName; item.LastName = dbItem.LastName; item.MiddleName = dbItem.MiddleName; item.PhoneNumber = dbItem.PhoneNumber; item.Email = dbItem.Email; item.FaxNumber = dbItem.FaxNumber; item.Company = dbItem.Company; item.Address1 = dbItem.Address1; item.Address2 = dbItem.Address2; item.City = dbItem.City; item.StateProvince = dbItem.StateProvince; item.ZipPostalCode = dbItem.ZipPostalCode; item.CountryID = dbItem.CountryID; item.Deleted = dbItem.Deleted; item.Active = dbItem.Active; return item; } #endregion #region Methods /// <summary> /// Gets an affiliate by affiliate identifier /// </summary> /// <param name="AffiliateID">Affiliate identifier</param> /// <returns>Affiliate</returns> public static Affiliate GetAffiliateByID(int AffiliateID) { if (AffiliateID == 0) return null; DBAffiliate dbItem = DBProviderManager<DBAffiliateProvider>.Provider.GetAffiliateByID(AffiliateID); Affiliate affiliate = DBMapping(dbItem); return affiliate; } /// <summary> /// Marks affiliate as deleted /// </summary> /// <param name="AffiliateID">Affiliate identifier</param> public static void MarkAffiliateAsDeleted(int AffiliateID) { Affiliate affiliate = GetAffiliateByID(AffiliateID); if (affiliate != null) { affiliate = UpdateAffiliate(affiliate.AffiliateID, affiliate.FirstName, affiliate.LastName, affiliate.MiddleName, affiliate.PhoneNumber, affiliate.Email, affiliate.FaxNumber, affiliate.Company, affiliate.Address1, affiliate.Address2, affiliate.City, affiliate.StateProvince, affiliate.ZipPostalCode, affiliate.CountryID, true, affiliate.Active); } } /// <summary> /// Gets all affiliates /// </summary> /// <returns>Affiliate collection</returns> public static AffiliateCollection GetAllAffiliates() { DBAffiliateCollection dbCollection = DBProviderManager<DBAffiliateProvider>.Provider.GetAllAffiliates(); AffiliateCollection affiliates = DBMapping(dbCollection); return affiliates; } /// <summary> /// Inserts an affiliate /// </summary> /// <param name="FirstName">The first name</param> /// <param name="LastName">The last name</param> /// <param name="MiddleName">The middle name</param> /// <param name="PhoneNumber">The phone number</param> /// <param name="Email">The email</param> /// <param name="FaxNumber">The fax number</param> /// <param name="Company">The company</param> /// <param name="Address1">The address 1</param> /// <param name="Address2">The address 2</param> /// <param name="City">The city</param> /// <param name="StateProvince">The state/province</param> /// <param name="ZipPostalCode">The zip/postal code</param> /// <param name="CountryID">The country identifier</param> /// <param name="Deleted">A value indicating whether the entity has been deleted</param> /// <param name="Active">A value indicating whether the entity is active</param> /// <returns>An affiliate</returns> public static Affiliate InsertAffiliate(string FirstName, string LastName, string MiddleName, string PhoneNumber, string Email, string FaxNumber, string Company, string Address1, string Address2, string City, string StateProvince, string ZipPostalCode, int CountryID, bool Deleted, bool Active) { DBAffiliate dbItem = DBProviderManager<DBAffiliateProvider>.Provider.InsertAffiliate(FirstName, LastName, MiddleName, PhoneNumber, Email, FaxNumber, Company, Address1, Address2, City, StateProvince, ZipPostalCode, CountryID, Deleted, Active); Affiliate affiliate = DBMapping(dbItem); return affiliate; } /// <summary> /// Updates the affiliate /// </summary> /// <param name="AffiliateID">The affiliate identifier</param> /// <param name="FirstName">The first name</param> /// <param name="LastName">The last name</param> /// <param name="MiddleName">The middle name</param> /// <param name="PhoneNumber">The phone number</param> /// <param name="Email">The email</param> /// <param name="FaxNumber">The fax number</param> /// <param name="Company">The company</param> /// <param name="Address1">The address 1</param> /// <param name="Address2">The address 2</param> /// <param name="City">The city</param> /// <param name="StateProvince">The state/province</param> /// <param name="ZipPostalCode">The zip/postal code</param> /// <param name="CountryID">The country identifier</param> /// <param name="Deleted">A value indicating whether the entity has been deleted</param> /// <param name="Active">A value indicating whether the entity is active</param> /// <returns>An affiliate</returns> public static Affiliate UpdateAffiliate(int AffiliateID, string FirstName, string LastName, string MiddleName, string PhoneNumber, string Email, string FaxNumber, string Company, string Address1, string Address2, string City, string StateProvince, string ZipPostalCode, int CountryID, bool Deleted, bool Active) { DBAffiliate dbItem = DBProviderManager<DBAffiliateProvider>.Provider.UpdateAffiliate(AffiliateID, FirstName, LastName, MiddleName, PhoneNumber, Email, FaxNumber, Company, Address1, Address2, City, StateProvince, ZipPostalCode, CountryID, Deleted, Active); Affiliate affiliate = DBMapping(dbItem); return affiliate; } #endregion } }
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.Threading; using System.Diagnostics; using System.Net; using System.IO; using System.Reflection; namespace UpLauncher { public partial class main : Form { private Thread scan; private WebClient client = new WebClient(); private bool locked = false; public main() { InitializeComponent(); } private void loading(object sender, EventArgs e) { this.MouseDown += new MouseEventHandler(utils.mouse_down); this.MouseMove += new MouseEventHandler(utils.mouse_move); this.FormClosing += new FormClosingEventHandler(this.closing); this.SizeChanged += new EventHandler(this.resize); client.DownloadFileCompleted += new AsyncCompletedEventHandler(this.download_finish); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.download_progress); bubble.DoubleClick += new EventHandler(this.open_upl); scan = new Thread(new ThreadStart(scanning)); scan.Start(); //Thread pour pas bloquer l'uplauncher sur la maj } private void open_upl(object sender, EventArgs e) { if (this.WindowState != FormWindowState.Normal) { this.WindowState = FormWindowState.Normal; } } private void download_progress(object sender, DownloadProgressChangedEventArgs e) { utils.set_width(this.pb2, (int)((double)e.ProgressPercentage / (double)100 * 689)); } private void download_finish(object sender, AsyncCompletedEventArgs e) { locked = false; } private void closing(object sender, EventArgs e) { bubble.Dispose(); Process p = Process.GetCurrentProcess(); p.Kill(); } private void scanning() { try { utils.set_width(this.pb1, 0); utils.set_width(this.pb2, 0); utils.set_text(this.files, ""); utils.set_text(this.infos, "Téléchargement des informations..."); utils.center_text(this.infos, this.Size.Width); string args = client.DownloadString(config.download_url + "files.php").Replace("client/", "").Replace('/', '\\'); utils.set_text(this.infos, "Vérification du/des fichier(s)..."); utils.center_text(this.infos, this.Size.Width); string[] web = args.Split(';'); int index = 0; double percent = 689 / (double)web.Length; foreach (string value in web) { index++; string[] arg = value.Split(','); if (!(File.Exists(arg[0]) && utils.CrypteFile_md5(arg[0]).Equals(arg[1]))) { utils.set_text(this.infos, "Téléchargement du fichier : " + arg[0]); utils.center_text(this.infos, this.Size.Width); locked = true; if (arg[0].Contains('\\')) { string dir = arg[0].Substring(0, arg[0].LastIndexOf('\\')); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); } client.DownloadFileAsync(new Uri(config.download_url + "client/" + arg[0].Replace('\\', '/')), arg[0]); while (locked) Thread.Sleep(10); } utils.set_text(this.files, "Fichier(s) : " + index + "/" + web.Length); utils.set_width(this.pb1, (int)(percent * index)); } utils.set_text(this.infos, "Vous pouvez maintenant jouer."); utils.center_text(this.infos, this.Size.Width); Process.Start("Dofus.exe"); if (this.WindowState == FormWindowState.Minimized) { bubble.BalloonTipText = "Vous pouvez maintenant jouer."; bubble.ShowBalloonTip(2500); } }catch(Exception ex) { MessageBox.Show(ex.Message); } } private void b_close_Click(object sender, EventArgs e) { this.Close(); } private void resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { bubble.BalloonTipText = "L'uplauncher est toujours ouvert."; bubble.ShowBalloonTip(2500); } } private void b_min_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } private void rst_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (scan != null && scan.IsAlive) scan.Suspend(); scan = new Thread(new ThreadStart(scanning)); scan.Start(); } } }
#region Copyright Syncfusion Inc. 2001-2015. // Copyright Syncfusion Inc. 2001-2015. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // licensing@syncfusion.com. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.Views; using System.Globalization; namespace SampleBrowser { public class Grouping:SamplePage { SfDataGrid sfGrid; GroupingViewModel viewModel; public override Android.Views.View GetSampleContent (Android.Content.Context context) { sfGrid = new SfDataGrid (context); viewModel = new GroupingViewModel (); sfGrid.ItemsSource = viewModel.ProductDetails; sfGrid.GroupColumnDescriptions.Add (new GroupColumnDescription (){ ColumnName = "Product" }); sfGrid.AutoGeneratingColumn += OnAutoGenerateColumn; sfGrid.QueryRowHeight += SfGrid_QueryRowHeight; return sfGrid; } void SfGrid_QueryRowHeight (object sender, QueryRowHeightEventArgs e) { if (SfDataGridHelpers.IsCaptionSummaryRow (this.sfGrid, e.RowIndex)) { e.Height = 40; e.Handled = true; } } void OnAutoGenerateColumn (object sender, AutoGeneratingColumnArgs e) { if (e.Column.MappingName == "ProductID") { e.Column.HeaderText = "Product ID"; } else if (e.Column.MappingName == "UserRating") { e.Column.HeaderText = "User Rating"; } else if (e.Column.MappingName == "ProductModel") { e.Column.HeaderText = "Product Model"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Price") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo ("en-US"); } else if (e.Column.MappingName == "ShippingDays") { e.Column.HeaderText = "Shipping Days"; } else if (e.Column.MappingName == "ProductType") { e.Column.HeaderText = "Product Type"; e.Column.TextAlignment = GravityFlags.CenterVertical; e.Column.TextMargin = 15; } else if (e.Column.MappingName == "Availability") { e.Column.TextAlignment = GravityFlags.CenterVertical; e.Column.TextMargin = 25; } } public override void Destroy () { this.sfGrid.AutoGeneratingColumn -= OnAutoGenerateColumn; this.sfGrid.QueryRowHeight -= SfGrid_QueryRowHeight; this.sfGrid.Dispose (); this.sfGrid = null; this.viewModel = null; } } }
using UnityEngine; using System.Collections; using UnityEditor; public class SOPixelPerfectMenu : ScriptableObject { [MenuItem ("Tools/SO/Add SOPixelPerfect scripts")] static void AddSOPixelPerfectTextMesh() { GameObject go = Selection.activeGameObject; if(go!=null){ ClearSelection(); go.AddComponent<SOPixelPerfectTextMesh>(); Object[] textMesheObjects = Selection.GetFiltered(typeof(TextMesh), SelectionMode.Deep); for(int i=0;i<textMesheObjects.Length;i++){ TextMesh tm = textMesheObjects[i] as TextMesh; float curHeight = tm.GetComponent<Renderer>().bounds.extents.y*2/tm.transform.localScale.y; if(curHeight==0){ curHeight = SOPixelPerfectTextSettings.DEFAULT_FONT_HEIGHT/tm.transform.localScale.y; } SOPixelPerfectTargetFontHeight sOPixelPerfectTargetFontHeight = tm.gameObject.AddComponent<SOPixelPerfectTargetFontHeight>(); float characterSize = curHeight*SOPixelPerfectTextSettings.UNITS_TO_CHARACTER_SIZE/tm.fontSize; sOPixelPerfectTargetFontHeight.fontHeightInUnits = curHeight*tm.characterSize/characterSize; } }else{ EditorUtility.DisplayDialog("Error", "Use on GameObjects!", "Ok" ); } } [MenuItem ("Tools/SO/Remove SOPixelPerfect scripts")] static void RemoveSOPixelPerfectTextMesh() { GameObject go = Selection.activeGameObject; if(go!=null){ ClearSelection(); }else{ EditorUtility.DisplayDialog("Error", "Use on GameObjects!", "Ok" ); } } private static void ClearSelection(){ SOPixelPerfectTextMesh[] sOPixelPerfectTextMeshs = Selection.activeGameObject.GetComponentsInChildren<SOPixelPerfectTextMesh>(); foreach(SOPixelPerfectTextMesh del in sOPixelPerfectTextMeshs){ DestroyImmediate (del); } SOPixelPerfectEditor[] sOPixelPerfectEditors = Selection.activeGameObject.GetComponentsInChildren<SOPixelPerfectEditor>(); foreach(SOPixelPerfectEditor del in sOPixelPerfectEditors){ DestroyImmediate (del); } SOPixelPerfectTargetFontHeight[] oldSOPixelPerfectTargetFontHeight = Selection.activeGameObject.GetComponentsInChildren<SOPixelPerfectTargetFontHeight>(); foreach(SOPixelPerfectTargetFontHeight del in oldSOPixelPerfectTargetFontHeight){ DestroyImmediate (del); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace N2_Estrutura { class VendasPorData { public DateTime Data { get; set; } public double Total { get; set; } } }
using Newtonsoft.Json; using RabbitMQ.Client; using RabbitMQ.Client.Events; using RabbitMQ.Client.Exceptions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ServicoDeRecebimentoDeEntregas.RabbitMQ { public class Consumer { ConnectionFactory connf; IConnection connection; IModel canal; AsyncEventingBasicConsumer asyncConsumer; EventingBasicConsumer basicConsumer; DataConsumer _DataConsumer; Configuracoes config; public Consumer(Configuracoes config, DataConsumer DataConsumer) { this._DataConsumer = DataConsumer; connf = new ConnectionFactory(); connf.HostName = config.Host; connf.UserName = config.User; connf.Password = config.Password; connf.Port = config.Port; connf.AutomaticRecoveryEnabled = true; connf.NetworkRecoveryInterval = System.TimeSpan.FromMinutes(1); this.config = config; } public void Subscribe() { try { connection = connf.CreateConnection(); canal = connection.CreateModel(); canal.QueueDeclare( queue: config.Fila , durable: true , exclusive: false , autoDelete: false , arguments: null ); basicConsumer = new EventingBasicConsumer(canal); basicConsumer.Received += (model, ea) => { var message = Encoding.UTF8.GetString(ea.Body); //_DataConsumer(new Mensa(Encoding.UTF8.GetString(ea.Body))); Mensagem mensagem = JsonConvert.DeserializeObject<Mensagem>(message); _DataConsumer(mensagem); }; canal.BasicConsume(config.Fila, true, basicConsumer); canal.CallbackException += canal_CallbackException; } catch (BrokerUnreachableException ex) { } catch { throw; } } void canal_CallbackException(object sender, CallbackExceptionEventArgs e) { throw new NotImplementedException(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DropExplosion : MonoBehaviour { float destroyTime = 1.4f; void Update() { destroyTime -= Time.deltaTime; if (destroyTime < 0) Destroy(gameObject); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class healthBarScript : MonoBehaviour { private playerHealth healthScript; // Start is called before the first frame update void Start() { healthScript = GameObject.FindGameObjectWithTag("player").GetComponent<playerHealth>(); } // Update is called once per frame void Update() { transform.localScale = new Vector3((healthScript.currentHealth / healthScript.maxHealth) * 1, 1, 1); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Touch_Movement : MonoBehaviour { private static bool _useTouch; public static bool UseTouch { get { return _useTouch; } set { _useTouch = value; SetObject(); } } public LayerMask Mask; [SerializeField] private GameObject ValidPress; [SerializeField] private GameObject InvalidPress; [SerializeField] private GameObject _touchControlsOption; private static GameObject _touchEnabledGameObject; void Awake() { _touchEnabledGameObject = _touchControlsOption.transform.Find("Toggle/On").gameObject; var touchOptionAvailable = Application.platform != RuntimePlatform.Android && Application.platform != RuntimePlatform.IPhonePlayer; _touchControlsOption.SetActive(touchOptionAvailable); if (!touchOptionAvailable) { UseTouch = true; } } // Update is called once per frame void Update () { var sp = SP_Manager.Instance.IsSinglePlayer(); if (sp && _touchControlsOption.activeSelf) { _touchControlsOption.SetActive(false); _useTouch = true; } // TODO check if touch movemoent is enabled if (UseTouch || (sp && SP_Manager.Instance.Get<SP_GameManager>().GameSetup())) { if (!UseTouch && _touchControlsOption.activeSelf) { // Touch controls can be toggled, but have not been activated so dont allow touch movements return; } if (Input.GetMouseButtonDown(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)) { var ray = new Ray(); if (Input.touchCount > 0) { ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position); } else { ray = Camera.main.ScreenPointToRay(Input.mousePosition); } RaycastHit hit; if (Physics.Raycast(ray, out hit, Mask)) { //Debug.Log(hit.collider.name); // Check if hit a player track if (hit.collider.CompareTag("MovementTrack")) { var track = hit.collider.GetComponent<SP_MovementTrack>(); if (track == null) { return; } var pressPos = hit.point + (Vector3.up * track.DistanceToGround); Player player; if (sp) { player = track.GetPlayer(pressPos.x); } else { // Find the player to move player = GameObject.Find("GameManager").GetComponent<GameManager>().GetLocalPlayer(); } if (player == null || !player.CanMove || player.OnPlatform) { return; } pressPos = player.PlayerRole == Player.Role.Floater ? new Vector3(pressPos.x, pressPos.y, player.transform.position.z) : new Vector3(player.transform.position.x, pressPos.y, pressPos.z); var press = ShowPress(true, pressPos); player.MoveToAndUse(pressPos, press); } else if (hit.collider.CompareTag("Player")) { var player = hit.collider.gameObject; var p = player.GetComponent<Player>(); if (sp || (!sp && p == GameObject.Find("GameManager").GetComponent<GameManager>().GetLocalPlayer())) { p.Interact(); } } else { ShowPress(false, hit.point + (Vector3.up * 0.25f)); } } } } } private GameObject ShowPress(bool valid, Vector3 position) { var pressObject = valid ? ValidPress : InvalidPress; var go = Instantiate(pressObject, position, Quaternion.Euler(0, -90, 0)); return go; } public void ToggleEnabled() { UseTouch = !UseTouch; } public static void SetObject() { if (_touchEnabledGameObject != null) { _touchEnabledGameObject.SetActive(UseTouch); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="InvertBooleanConverter.cs" company="Soloplan GmbH"> // Copyright (c) Soloplan GmbH. All rights reserved. // Licensed under the MIT License. See License-file in the project root for license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Soloplan.WhatsON.GUI.Common.Converters { using System; using System.Globalization; using System.Windows.Data; public class InvertBooleanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return Negate(value); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return Negate(value); } private static object Negate(object value) { if (value is bool boolean) { return !boolean; } return false; } } }
namespace CarDealer.Services.Interfaces { using Models.Cars; using System.Collections.Generic; public interface ICarServices { ICollection<CarByMake> AllCarsByMakes(string make); ICollection<CarByMake> All(); void Create(string make, string model, long travelledDistance, IEnumerable<int> parts); ICollection<CarsWithPartsModel> CarWithParts(string id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; //Biblioteca de conexão com SQLServer namespace Persistencia { class Conexao { public SqlConnection cn = new SqlConnection(); //Construtor da Classe public Conexao(String banco) { cn.ConnectionString = "Data Source=localhost;" + "Integrated Security=SSPI;" + "Initial Catalog=BDLP2015"; cn.Open(); } //Não retorna nenhum tipo de dado, apenas o número de células afetadas public int executeNoQuery(String SQL){ SqlCommand cmd = cn.CreateCommand(); cmd.CommandText = SQL; return cmd.ExecuteNonQuery(); } //Retorna um único valor (object) escalar public object executeScalar(String SQL) { SqlCommand cmd = cn.CreateCommand(); cmd.CommandText = SQL; return cmd.ExecuteScalar(); } //Retorna um objeto DataReader, com o resultado da consulta public SqlDataReader executeReader(String SQL) { SqlCommand cmd = cn.CreateCommand(); cmd.CommandText = SQL; return cmd.ExecuteReader(); } //Fecha a Conexao public void fechaConexao() { cn.Close(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Dice_random { public partial class Form1 : Form { Random randon = new Random(); public Form1() { InitializeComponent(); } //every time this btn is click should roll the dice private void btnRoll_Click(object sender, EventArgs e) { //you need two inputs: the number of dice and the number of pipe int number_roll = numericUpDown_diceRoll; int number_of_pipe; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PassingArgumentsSDK { // ******************************************* // Passing Reference-Type Arguments // ******************************************* public class ObjectWithProp { public string PropTextValue { get; set; } } public class ObjectUsingObjectProp { public ObjectWithProp ObjProperty { get; set; } public void DisplayPropValue(ObjectWithProp owp) { Console.WriteLine(owp.PropTextValue); } } // ******************************************* // Passing Arguments by Reference with ref/out Keywords // ******************************************* // Example A class RefExample { public void Method(ref int i) { i = i + 44; } } // Example B public class Item { public String ItemName { get; set; } } public class PopulateItems { public void Populate(out Item[] items) { items = new Item[5]; for (int i = 0; i < 5; i++) { items[i] = new Item(); items[i].ItemName = "Item" + i.ToString(); } } } // ******************************************* // Passing typeof(Type) as Method Argument // ******************************************* public class Sample { public void PassTypeArg(Type myType) { Console.Out.WriteLine(myType.ToString()); } } }