Datasets:

blob_id
large_stringlengths
40
40
language
large_stringclasses
1 value
repo_name
large_stringlengths
5
119
path
large_stringlengths
4
271
score
float64
2.52
4.84
int_score
int64
3
5
text
stringlengths
26
4.09M
7bcfeedded5f738d56888d71429206f5e667d636
C#
muhyilmaz/CSharpFullCourse
/CSharpCourse/CA.TypesVariables/Program.cs
3.453125
3
using System; namespace CA.TypesVariables { class Program { enum Days { Pazartesi,Salı,Çarşamba,Perşembe,Cuma,Cumartesi,Pazar } static void Main(string[] args) { //Value Types int number_1 = 10; if ((int)Days.Pazar == 6) { Console.WriteLine("ADAMMM"); } Console.WriteLine("Hello World {0}", number_1); Console.ReadLine(); } } }
7eac6b2ab945ec6251a4259ae7d04215be241b90
C#
NeatCrown/PaperMarioBattleSystem
/PaperMarioBattleSystem/PaperMarioBattleSystem/Classes/Global/Debug.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Console; using System.Diagnostics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace PaperMarioBattleSystem { /// <summary> /// Static class for debugging /// </summary> public static class Debug { public static bool DebugEnabled { get; private set; } = false; public static bool LogsEnabled { get; private set; } = false; public static bool DebugPaused { get; private set; } = false; public static bool AdvanceNextFrame { get; private set; } = false; private static KeyboardState DebugKeyboard = default(KeyboardState); static Debug() { #if DEBUG DebugEnabled = true; LogsEnabled = true; #else DebugEnabled = false; #endif } private static void ToggleDebug() { #if DEBUG DebugEnabled = !DebugEnabled; //Failsafe #else DebugEnabled = false; #endif } private static void ToggleLogs() { LogsEnabled = !LogsEnabled; } private static string GetStackInfo(int skipFrames) { StackFrame trace = new StackFrame(skipFrames, true); int line = 0; string method = ""; string traceFileName = trace.GetFileName(); if (string.IsNullOrEmpty(traceFileName) == true) traceFileName = "N/A"; string[] file = traceFileName.Split('\\'); string fileName = file?[file.Length - 1]; if (string.IsNullOrEmpty(fileName) == true) fileName = "N/A FileName"; line = trace.GetFileLineNumber(); method = trace.GetMethod()?.Name; if (string.IsNullOrEmpty(method) == true) method = "N/A MethodName"; return $"{fileName}->{method}({line}):"; } private static string GetStackInfo() { return GetStackInfo(3); } public static void Log(object value) { if (LogsEnabled == false) return; WriteLine($"Information: {GetStackInfo()} {value}"); } public static void LogWarning(object value) { if (LogsEnabled == false) return; WriteLine($"Warning: {GetStackInfo()} {value}"); } public static void LogError(object value) { if (LogsEnabled == false) return; WriteLine($"Error: {GetStackInfo()} {value}"); } private static void LogAssert() { if (LogsEnabled == false) return; string stackInfo = GetStackInfo(3); stackInfo = stackInfo.Remove(stackInfo.Length - 1); WriteLine($"ASSERT FAILURE AT: {stackInfo}"); } public static void Assert(bool condition) { if (condition == false) LogAssert(); } public static void DebugUpdate() { #if DEBUG //Toggle debug if (Input.GetKey(Keys.LeftControl, DebugKeyboard) && Input.GetKeyDown(Keys.D, DebugKeyboard)) { ToggleDebug(); } #endif //Return if debug isn't enabled if (DebugEnabled == false) { if (Time.InGameTimeEnabled == false) Time.ToggleInGameTime(true); return; } //Reset frame advance AdvanceNextFrame = false; //Debug controls if (Input.GetKey(Keys.LeftControl, DebugKeyboard)) { //Toggle pause if (Input.GetKeyDown(Keys.P, DebugKeyboard)) { DebugPaused = !DebugPaused; } //Toggle frame advance else if (Input.GetKeyDown(Keys.OemSemicolon, DebugKeyboard)) { AdvanceNextFrame = true; } //Toggle logs else if (Input.GetKeyDown(Keys.L, DebugKeyboard)) { ToggleLogs(); } } //Camera controls if (Input.GetKey(Keys.LeftShift, DebugKeyboard)) { if (Input.GetKeyDown(Keys.Space, DebugKeyboard)) { //Reset camera coordinates Camera.Instance.SetTranslation(Vector2.Zero); Camera.Instance.SetRotation(0f); Camera.Instance.SetZoom(1f); } else { Vector2 translation = Vector2.Zero; float rotation = 0f; float zoom = 0f; //Translation if (Input.GetKey(Keys.Left, DebugKeyboard)) translation.X -= 2; if (Input.GetKey(Keys.Right, DebugKeyboard)) translation.X += 2; if (Input.GetKey(Keys.Down, DebugKeyboard)) translation.Y += 2; if (Input.GetKey(Keys.Up, DebugKeyboard)) translation.Y -= 2; //Rotation if (Input.GetKey(Keys.OemComma, DebugKeyboard)) rotation -= .1f; if (Input.GetKey(Keys.OemPeriod, DebugKeyboard)) rotation += .1f; //Scale if (Input.GetKey(Keys.OemMinus, DebugKeyboard)) zoom -= .1f; if (Input.GetKey(Keys.OemPlus, DebugKeyboard)) zoom += .1f; if (translation != Vector2.Zero) Camera.Instance.Translate(translation); if (rotation != 0f) Camera.Instance.Rotate(rotation); if (zoom != 0f) Camera.Instance.Zoom(zoom); } } //Battle Debug if (Input.GetKey(Keys.RightShift, DebugKeyboard) == true) { DebugBattle(); } //Unit Tests if (Input.GetKey(Keys.U, DebugKeyboard) == true) { DebugUnitTests(); } //If a pause is eventually added that can be performed normally, put a check for it in here to //prevent the in-game timer from turning on when it shouldn't Time.ToggleInGameTime(DebugPaused == false || AdvanceNextFrame == true); FPSCounter.Update(); Input.UpdateInputState(ref DebugKeyboard); } public static void DebugBattle() { //Default to Players - if holding 0, switch to Enemies Enumerations.EntityTypes entityType = Enumerations.EntityTypes.Player; if (Input.GetKey(Keys.D0, DebugKeyboard) == true) entityType = Enumerations.EntityTypes.Enemy; int turnCount = 3; //Inflict Poison, Payback, or Paralyzed if (Input.GetKeyDown(Keys.P, DebugKeyboard) == true) { StatusEffect status = new PoisonStatus(turnCount); //Inflict Payback if (Input.GetKey(Keys.B, DebugKeyboard) == true) status = new PaybackStatus(turnCount); //Inflict Paralyzed else if (Input.GetKey(Keys.Z, DebugKeyboard) == true) status = new ParalyzedStatus(turnCount); DebugInflictStatus(status, entityType); } //Inflict Invisible or Immobilized else if (Input.GetKeyDown(Keys.I, DebugKeyboard) == true) { StatusEffect status = new InvisibleStatus(turnCount); //Inflict Immobilized if (Input.GetKey(Keys.M, DebugKeyboard) == true) status = new ImmobilizedStatus(turnCount); DebugInflictStatus(status, entityType); } //Inflict Electrified else if (Input.GetKeyDown(Keys.E, DebugKeyboard) == true) { DebugInflictStatus(new ElectrifiedStatus(turnCount), entityType); } //Inflict Fast, Frozen, or FPRegen else if (Input.GetKeyDown(Keys.F, DebugKeyboard) == true) { StatusEffect status = new FastStatus(turnCount); //Inflict Frozen if (Input.GetKey(Keys.R, DebugKeyboard) == true) status = new FrozenStatus(turnCount); //Inflict FPRegen else if (Input.GetKey(Keys.P, DebugKeyboard) == true) status = new FPRegenStatus(2, turnCount); DebugInflictStatus(status, entityType); } //Inflict Dizzy or Dodgy else if (Input.GetKeyDown(Keys.D, DebugKeyboard) == true) { StatusEffect status = new DizzyStatus(turnCount); //Inflict Dodgy if (Input.GetKey(Keys.O, DebugKeyboard) == true) status = new DodgyStatus(turnCount); DebugInflictStatus(status, entityType); } //Inflict Sleep, Stone, or Slow else if (Input.GetKeyDown(Keys.S, DebugKeyboard) == true) { StatusEffect status = new SleepStatus(turnCount); //Inflict Stone if (Input.GetKey(Keys.T, DebugKeyboard) == true) status = new StoneStatus(turnCount); //Inflict Slow else if (Input.GetKey(Keys.L, DebugKeyboard) == true) status = new SlowStatus(turnCount); DebugInflictStatus(status, entityType); } //Inflict Confused else if (Input.GetKeyDown(Keys.C, DebugKeyboard) == true) { StatusEffect status = new ConfusedStatus(turnCount); DebugInflictStatus(status, entityType); } //Inflict Burn else if (Input.GetKeyDown(Keys.B, DebugKeyboard) == true) { StatusEffect status = new BurnStatus(turnCount); DebugInflictStatus(status, entityType); } //Inflict Tiny else if (Input.GetKeyDown(Keys.T, DebugKeyboard) == true) { StatusEffect status = new TinyStatus(turnCount); DebugInflictStatus(status, entityType); } //Inflict Huge or HPRegen else if (Input.GetKeyDown(Keys.H, DebugKeyboard) == true) { StatusEffect status = new HugeStatus(turnCount); //Inflict HPRegen if (Input.GetKey(Keys.P, DebugKeyboard) == true) status = new HPRegenStatus(2, turnCount); DebugInflictStatus(status, entityType); } //Inflict Allergic else if (Input.GetKeyDown(Keys.A, DebugKeyboard) == true) { StatusEffect status = new AllergicStatus(turnCount); DebugInflictStatus(status, entityType); } } private static void DebugInflictStatus(StatusEffect status, Enumerations.EntityTypes entityType) { BattleEntity[] entities = BattleManager.Instance.GetEntities(entityType, null); for (int i = 0; i < entities.Length; i++) { entities[i].EntityProperties.AfflictStatus(status, true); } } #region Debug Unit Tests private static void DebugUnitTests() { if (Input.GetKeyDown(Keys.D1, DebugKeyboard)) { UnitTests.InteractionUnitTests.NewInteractionUT1(); } else if (Input.GetKeyDown(Keys.D2, DebugKeyboard)) { UnitTests.InteractionUnitTests.NewInteractionUT2(); } else if (Input.GetKeyDown(Keys.D3, DebugKeyboard)) { UnitTests.InteractionUnitTests.NewInteractionUT3(); } else if (Input.GetKeyDown(Keys.D4, DebugKeyboard)) { UnitTests.InteractionUnitTests.NewInteractionUT4(); } else if (Input.GetKeyDown(Keys.D5, DebugKeyboard)) { UnitTests.InteractionUnitTests.NewInteractionUT5(); } else if (Input.GetKeyDown(Keys.D6, DebugKeyboard)) { UnitTests.InteractionUnitTests.NewInteractionUT6(); } else if (Input.GetKeyDown(Keys.D7, DebugKeyboard)) { UnitTests.InteractionUnitTests.NewInteractionUT7(); } else if (Input.GetKeyDown(Keys.D8, DebugKeyboard)) { UnitTests.InteractionUnitTests.NewInteractionUT8(); } else if (Input.GetKeyDown(Keys.D9, DebugKeyboard)) { UnitTests.InteractionUnitTests.NewInteractionUT9(); } else if (Input.GetKeyDown(Keys.D0, DebugKeyboard)) { if (Input.GetKey(Keys.LeftShift)) { UnitTests.InteractionUnitTests.ElementOverrideInteractionUT1(); } else { UnitTests.InteractionUnitTests.NewInteractionUT10(); } } } #endregion public static void DebugDraw() { if (DebugEnabled == false) return; //FPS counter FPSCounter.Draw(); //Camera info Vector2 cameraBasePos = new Vector2(0, 510); SpriteRenderer.Instance.DrawText(AssetManager.Instance.TTYDFont, "Camera:", cameraBasePos, Color.White, 0f, Vector2.Zero, 1.2f, .1f); SpriteRenderer.Instance.DrawText(AssetManager.Instance.TTYDFont, $"Pos: {Camera.Instance.Position}", cameraBasePos + new Vector2(0, 20), Color.White, 0f, Vector2.Zero, 1.2f, .1f); SpriteRenderer.Instance.DrawText(AssetManager.Instance.TTYDFont, $"Rot: {Camera.Instance.Rotation}", cameraBasePos + new Vector2(0, 40), Color.White, 0f, Vector2.Zero, 1.2f, .1f); SpriteRenderer.Instance.DrawText(AssetManager.Instance.TTYDFont, $"Zoom: {Camera.Instance.Scale}", cameraBasePos + new Vector2(0, 60), Color.White, 0f, Vector2.Zero, 1.2f, .1f); } } }
bb985ba559e1c9efd1a6a8b77e7550d462a24c33
C#
Zokatt/PirateCardGame
/Cards/Empty.cs
2.765625
3
using System; using System.Collections.Generic; using System.Text; namespace PriateCardGame.Cards { /// <summary> /// Empty card is used for card check /// <para>this is has no health,damage and 0 coins</para> /// </summary> ///<remarks> /// Nikolaj /// </remarks> class Empty : CardBase { public Empty() { this.Coin = 0; } public override void AdditionalCardEffect(List<CardSpace> enemySpaces, List<CardSpace> playerSpaces) { throw new NotImplementedException(); } } }
5798af1d94c639241debf2b2e73923efce595b9a
C#
dmitry-ui/c_nordic
/Lesson24/ASP.NET Core/L22_C01_empty_asp_net_core_app/DataValidation/OtherValueAttribute.cs
2.875
3
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace L22_C01_empty_asp_net_core_app.DataValidation { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class OtherValueAttribute: ValidationAttribute { public OtherValueAttribute(string otherProperty) // : base(DataAnnotationsResources.CompareAttribute_MustMatch) { if (otherProperty == null) { throw new ArgumentNullException("otherProperty"); } OtherProperty = otherProperty; } public string OtherProperty { get; private set; } //public override bool RequiresValidationContext //{ // get // { // return true; // } //} protected override ValidationResult IsValid(object value, ValidationContext validationContext) { PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(OtherProperty); if (otherPropertyInfo == null) { return new ValidationResult($"Cannot find property having name \"{OtherProperty}\""); } object otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null); if (Equals(value, otherPropertyValue)) { return new ValidationResult( $"{validationContext.MemberName} should not be the same as {OtherProperty}"); } return null; } } }
f927d028f8a49d5c5900964c20056097cb9cca12
C#
EarthShaping/com.earthshaping.third-person-controller
/Runtime/Scripts/Character/States/AIJumpingCharacterState.cs
2.546875
3
namespace com.earthshaping.thirdperson.controller { /// <summary> /// The character is in the air, and he jumped to achieve that /// </summary> public class AIJumpingCharacterState : AICharacterStateBase { public override void Update(Character character) { base.Update(character); if (character.IsGrounded) { this.ToState(character, AICharacterStateBase.GROUNDED_STATE); } } } }
a70951e1f91809e60e5e14f4977d29763b28aa59
C#
shendongnian/download4
/code3/575145-13429752-31958484-2.cs
2.765625
3
public class instance : INotifyPropertyChanged { private int progress; public int Progress { get { return progress; } set { if (progress != value) { progress = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Progress")); } } } } public event PropertyChangedEventHandler PropertyChanged; /* Do the same with the remaining properties */ public string User { get; set; } public string File { get; set; } }
4eb7bdbfa70e5ce01e8fb4f90ce73ab7bf88eada
C#
resatkrky/Bitirme-Projem
/Assets/Scripts/EnemyAI.cs
2.59375
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public enum AIState //AI'ın durumlarını numaralandr variable olarak kullan { Guarding, Aert, Attacking } public class EnemyAI : MonoBehaviour { public AIState enemyState; public float speed; //animasyon geçiş hızı public bool isDieing; //AI öldü mü ? public float currentHealth; //AI mevcut canı public float scanRange; //taranacak aralık public float turnSpeed; //AI Dönme hızı bool isHit, isCrouching; //AI vuruldu mu ve eğildi mi ? float maxHealth = 100; //AI max can NavMeshAgent navAgent; //AI kendine nesneleri gözönüne alarak yol çizmesi Animator animator; //animasyonları ayarlamak Transform target; //AI nereye gidecek Transform Player; //AI nerede takip etmek CapsuleCollider bodyCol; //AI collider vererek nesnelere çarpmasını ve vurulmasını sağlamak void Start() { navAgent = GetComponent<NavMeshAgent>(); animator = GetComponent<Animator>(); target = null; Player = GameObject.FindGameObjectWithTag("Player").transform; currentHealth = 100f; bodyCol = GetComponent<CapsuleCollider>(); } void Update() { if(currentHealth >= 1) { switch (enemyState) //AI durumunu seçecek ve fonk'a göre işlem yapacak { case AIState.Guarding: Guarding(); break; case AIState.Aert: Alert(); break; case AIState.Attacking: Attacking(); break; } navAgent.speed = speed; UpdateAnimations(); } else { currentHealth = 0f; isDieing = true; animator.SetBool("isDieing",isDieing); } } void Guarding() // durma yani bölgeyi koruma durumu { speed = 0;//hareket veya anim geçişi yok target = null; //burada ateş edecek hedef yok } void Alert() { isCrouching = true; FindCover(); } void Attacking() { target = Player; //animator.SetTrigger("isFiring"); navAgent.SetDestination(Player.transform.position); navAgent.stoppingDistance = 5f; //cover yoksa durma ve ateş etme mesafesi speed = 5f; isCrouching = false; if (navAgent.pathPending) //AI kendine yol daha önce buldu şuan bulmasına gerek yoksa { if (navAgent.remainingDistance <= navAgent.stoppingDistance) //AI'ın önünde nesne var mı { if (!navAgent.hasPath || navAgent.velocity.sqrMagnitude == 0f && currentHealth > 0) //AI'ın canı varsa ve yola sahipse { animator.SetTrigger("isFiring"); //AI ateş etsin } } } TurnPlayer(); } void FindCover() { GameObject[] Covers = GameObject.FindGameObjectsWithTag("Cover"); //cover taglı objeleri bulur ve gameobject dizisine ekler float shortestDistance = Mathf.Infinity; //AI'a en kısa mesafe GameObject nearstCover = null; //AI'a en yakın cover foreach (GameObject cover in Covers) { float distanceToCover = Vector3.Distance(transform.position, cover.transform.position); //AI covera olan uzaklığı if(distanceToCover < shortestDistance) //AI covera uzaklığı en kısa mesafeden az mı { shortestDistance = distanceToCover; //yeni en yakın mesafe nearstCover = cover; //AI'a en yakın cover speed = 5; //AI hareket etmesi için hız artmalı } } if(nearstCover != null && shortestDistance <= scanRange) //nearstcover varsa ve arama aralığndaysa { target = nearstCover.transform; //AI'ın gideceği yer yani cover navAgent.SetDestination(target.transform.position); //target setlendi //AI'ın kendine yol bulduktan oraya gidip ateş etmesi if (!navAgent.pathPending) //AI kendine yol daha önce buldu şuan bulmasına gerek yoksa { if(navAgent.remainingDistance <= navAgent.stoppingDistance) //AI'ın önünde nesne var mı { if(!navAgent.hasPath || navAgent.velocity.sqrMagnitude == 0f && !isDieing) //AI'ın canı varsa ve yola sahipse { enemyState = AIState.Attacking; //AI saldırı durumuna geçsin } } } } else //cover yoksa { enemyState = AIState.Attacking; //direk saldırı durumuna geçsin } } void TurnPlayer() { Vector3 dir = target.transform.position - transform.position;//target ile mesafe Quaternion lookRotation = Quaternion.LookRotation(dir); //Target yönüne dönmek Vector3 rotation = Quaternion.Lerp(transform.rotation, lookRotation, Time.deltaTime * turnSpeed).eulerAngles; //eulerAngles sayesinde rotation değeri yavaş döner transform.rotation = Quaternion.Euler(rotation.x, rotation.y, rotation.z); animator.SetFloat("isTurning", turnSpeed); turnSpeed = 5f; } void UpdateAnimations() { animator.SetFloat("Speed", speed); animator.SetBool("isCrouching" ,isCrouching); //if (isDieing) //{ // animator.SetTrigger("isDieing"); // animator.SetFloat("health", currentHealth); //} if (isHit) { animator.SetTrigger("isHit"); isHit = false; } } void OnTriggerEnter(Collider other) //AI'ın bizim karakterimizi algılaması { if(other.tag == "Player") { enemyState = AIState.Aert; } } void OnTriggerExit(Collider other) { if (other.tag == "Player") { enemyState = AIState.Guarding; } } }
73d412af4e8fde3fba02ef7f0b943d1598da24e7
C#
dani5636/Registration
/VideoMenuUI/VideoUI.cs
3.03125
3
using System.Collections.Generic; using VideoMenuBLL; using VideoMenuBLL.BusinessObjects; using static System.Console; namespace VideoMenuUI { class VideoUI { static BLLFacade bllFacade = new BLLFacade(); public static void VideoMenu() { #region Menu Items string[] menuItems = { "Add a video", "Add multiple videos", "List all videos", "Update a video", "Delete a video", "Search in all videos", "Back" }; #endregion #region Menu Switch var selection = ExtraUI.ShowMenu(menuItems); while (selection != 7) { switch (selection) { case 1: CreateVideo(); break; case 2: CreateMultipleVideos(); break; case 3: ListAllVideos(); break; case 4: UpdateVideo(); break; case 5: DeleteVideo(); break; case 6: SearchVideos(); break; } WriteLine("Press Enter to go back to the menu"); ReadLine(); selection = ExtraUI.ShowMenu(menuItems); } #endregion WriteLine("Press Enter to return to the main menu"); ReadLine(); } private static void CreateVideo() { WriteLine("Genre: "); var genre = GenreExistCheck(); WriteLine("Name: "); var name = ReadLine(); WriteLine("You have inputted the following info:"); WriteLine($"Genre: {genre.Name} |Name: {name}"); if (ExtraUI.ConfirmInfo()) { bllFacade.VideoService.CreateVideo(new VideoBO() { Genre = genre.Name, Name = name }); WriteLine("Video is now in information"); } else { WriteLine("The video was not added"); } } private static void CreateMultipleVideos() { WriteLine("How many videos do you wish to add?"); int times; while (!int.TryParse(ReadLine(), out times)) { WriteLine("Please input a number"); } WriteLine("What is the genre for all of these videos?:"); WriteLine("Genre: "); var genre = GenreExistCheck(); List<VideoBO> videos = new List<VideoBO>(); WriteLine("C to cancel and A to Accept enter all inputted info"); bool save = true; for (int i = 0; i < times; i++) { WriteLine("Name: "); var name = ReadLine(); if (name.ToLower().Equals("c")) { save = false; break; } else if(name.ToLower().Equals("a")) WriteLine("You have inputted the following info:"); WriteLine($"Genre: {genre.Name} |Name: {name}"); if (ExtraUI.ConfirmInfo()) { videos.Add(new VideoBO { Genre = genre.Name, Name = name }); } else { WriteLine("The video was not added"); i--; } } if (save) { bllFacade.VideoService.CreateMultipleVideos(videos); } } private static void ListAllVideos() { foreach (var video in bllFacade.VideoService.GetAllVideos()) { WriteLine($"ID: {video.Id} |Genre: {video.Genre} |Name: {video.Name}"); } } private static void UpdateVideo() { WriteLine("Which Video would you like to update? (ID)"); var video = FindVideoById(); if (video != null) { WriteLine("You are updating the following video:"); WriteLine($"Genre: {video.Genre} |Name: {video.Name}"); WriteLine("Genre: "); var genre = GenreExistCheck(); WriteLine("Name: "); var name = ReadLine(); WriteLine("You have inputted the following info:"); WriteLine($"Genre: {genre.Name} |Name: {name}"); if (ExtraUI.ConfirmInfo()) { video.Genre = genre.Name; video.Name = name; bllFacade.VideoService.UpdateVideo(video); WriteLine("Video has been updated"); } else { WriteLine("The video was not updated"); } } } private static void DeleteVideo() { int id; WriteLine("Input the id of the video you would like to delete:(ID)"); if (int.TryParse(ReadLine(), out id)) { var result = bllFacade.VideoService.DeleteVideo(id)== true ? "Video was succesfully deleted" : "Video was not found"; WriteLine(result); } else { WriteLine("Please input an id"); } } private static void SearchVideos() { WriteLine("Search for videos"); var searchedVideos = bllFacade.VideoService.SearchVideos(ReadLine()); WriteLine("Search Result"); foreach (var video in searchedVideos) { WriteLine($"ID: {video.Id}|Genre: {video.Genre}|Name: {video.Name}"); } } private static VideoBO FindVideoById() { WriteLine("Enter Q to go back to the menu"); VideoBO video = null; while (video == null) { int idSearch; string input = ReadLine(); if (int.TryParse(input, out idSearch)) { return bllFacade.VideoService.GetVideoById(idSearch); } else if (input.ToLower().Equals("q")) { break; } else { Write("You have to input the id"); } } return null; } private static GenreBO GenreExistCheck() { bool foundGenre = false; string str = ReadLine(); GenreBO genre = null; while (!foundGenre) { genre = bllFacade.GenreService.GetGenreByName(str); if (genre != null) { return genre; } else { WriteLine("The genre inputted was not found"); WriteLine($"Do you wish to create a genre named {str}"); if (ExtraUI.ConfirmInfo()) { genre = new GenreBO { Name = str }; bllFacade.GenreService.CreateGenre(genre); return genre; } else { } } str = ReadLine(); } return null; } } }
5195b9e705d2f518860c4e46aa5eac1f1505240f
C#
NightRoadIx/Curso-C-
/beispiel33.cs
3.109375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FireSharp.Config; using FireSharp.Response; using FireSharp.Interfaces; namespace databasizacion { class Estudiante { // Atributos public int RollNo { get; set; } public string Nombre { get; set; } public float Calificacion { get; set; } } class Program { static void Main(string[] args) { IFirebaseConfig ifc = new FirebaseConfig() { AuthSecret = "1HQd7t7T8G5joitCGQ1qW0Jui3piFOGlvY0aG01o", BasePath = "https://adam-ddc87.firebaseio.com/" }; IFirebaseClient client; try { client = new FireSharp.FirebaseClient(ifc); Console.WriteLine("Conexación se realizo de manera exitosa"); /* CRUD */ // Create o insertar Estudiante estu = new Estudiante(); estu.RollNo = 2; estu.Nombre = "Pepito Pechugas"; estu.Calificacion = 5.89f; client.Set(@"Estudiantes/" + estu.RollNo, estu); Console.WriteLine("Los datos se guardaron de manera correcta"); Console.WriteLine("Continuar"); Console.ReadKey(); // Read, lectura o búsqueda Console.Write("Ingresar dato a buscar: "); int busca = Convert.ToInt32(Console.ReadLine()); // La búsqueda sobre la base de datos var respuesta = client.Get(@"Estudiantes/" + busca); Estudiante dstu = respuesta.ResultAs<Estudiante>(); // Verificar si el objeto es no nulo if (dstu != null) { Console.WriteLine("Registro hallado:"); Console.WriteLine("{0} tiene {1}", dstu.Nombre, dstu.Calificacion); } else Console.WriteLine("No se hallo el registro"); Console.WriteLine("Continuar"); Console.ReadKey(); // Update, actualización estu.Calificacion = 8.86f; estu.RollNo = 2; client.Update(@"Estudiantes/" + estu.RollNo, estu); Console.WriteLine("Continuar"); Console.ReadKey(); // Delete, borrar client.Delete(@"Estudiantes/" + "1"); } catch { Console.WriteLine("Error en obtener base de datos de la web"); } finally { Console.WriteLine("Presione una tecla pa' salir"); Console.ReadKey(); } } } }
ebbb6ea34a5045507e5a32718079fd0ce478e5f0
C#
kasmeltz/PizzaEmpire
/Client/Unity2/Assets/Code/Resources/LightweightResourceManager.cs
3.03125
3
namespace KS.PizzaEmpire.Unity { using KS.PizzaEmpire.Common; using System; using System.Collections.Generic; using UnityEngine; /// <summary> /// Manages the resources used in the game. /// Doesn't use referene counting and is suitable for items that /// are very lightweight and will live in memory for the /// lifetime of the applicaton. /// </summary> public class LightweightResourceManager<T> { private Dictionary<ResourceEnum, T> ResourceObjects { get; set; } private static volatile LightweightResourceManager<T> instance; private static object syncRoot = new object(); private LightweightResourceManager() { } /// <summary> /// Provides the Singleton instance of the LightweightResourceManager /// </summary> public static LightweightResourceManager<T> Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) { instance = new LightweightResourceManager<T>(); instance.Initialize(); } } } return instance; } } /// <summary> /// Initializes the lightweight resource manager. /// </summary> /// <returns></returns> public void Initialize() { ResourceObjects = new Dictionary<ResourceEnum,T>(); } /// <summary> /// Sets the resource associated with the provided resource enum. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="resource"></param> /// <returns></returns> public void Set(ResourceEnum resource, T item) { ResourceObjects[resource] = item; Debug.Log("Setting " + typeof(T).ToString() + " Item: " + resource + ", " + ResourceObjects[resource]); } /// <summary> /// Gets the resource associated with the provided resource enum. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="resource"></param> /// <returns></returns> public T Get(ResourceEnum resource) { Debug.Log("Getting " + typeof(T).ToString() + " Item: " + resource + ", " + ResourceObjects[resource]); return ResourceObjects[resource]; } } }
2e270b0fcd03ea171e475d9b2ae2746ce48a17a5
C#
CrimeMasterGogo31/DsAlgoSample
/CodeForces/ArrayRestoration.cs
3.515625
4
using System; using System.Collections.Generic; using System.Text; namespace DemoConsole.CodeForces { public class ArrayRestoration { //public static void Main() //{ // int t = Convert.ToInt32(Console.ReadLine().Trim()); // while (t-- != 0) // { // var arr = Array.ConvertAll(Console.ReadLine().Trim().Split(' '), // tmp => Convert.ToInt64(tmp)); // var n = arr[0]; // var x = arr[1]; // var y = arr[2]; // if (n == 2) // { // Console.WriteLine(x + " " + y); // continue; // } // if ((y - x) % (n - 1) == 0) // { // Console.Write(x); // var tmp = x + n; // while (tmp <= y) // { // Console.Write(" " + tmp); // tmp += n; // } // Console.WriteLine(); // continue; // } // var diff = y - x; // var newlimit = 2; // while (newlimit < n) // { // if (diff % newlimit == 0) // break; // newlimit++; // } // Console.Write(x); // var count = 1; // var temp = x; // while (count < n && (x - newlimit > 0)) // { // x -= newlimit; // Console.Write(" " + x); // count++; // } // x = temp; // while (count <= n) // { // x += newlimit; // Console.Write(" " + x); // count++; // } // Console.WriteLine(); // } //} } }
4a24382cae481377a3a5bba659e61d2b123f8326
C#
ezemanzano/Labo2
/labo2/Ejercicio33/Libro/Class1.cs
3.578125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Libros { public class Libro { List<string> paginas; public Libro() { this.paginas = new List<string>(); } /// <summary> /// Indexador del libro. /// </summary> /// <param name="indice">Indice de la página</param> /// <returns></returns> public string this[int indice] { get { /* Si el índice es mayor o igual a cero * y menor a la cantidad de elementos de la lista. * Entonces, existe. * Lo retorno. */ if (indice >= 0 && indice < this.paginas.Count) { return this.paginas[indice]; } else { /* Sino, estoy tratando de acceder * a un índice que no existe. * Retorno una cadena vacía. */ return string.Empty; } } set { // Si el índice es válido. if (indice >= 0) { /* Si el índice es mayor o igual a cero * y menor a la cantidad de elementos de la lista. * Entonces, existe. * Lo modifico. */ if (indice < this.paginas.Count) { this.paginas[indice] = value; } else { /* Si supera o iguala * a la cantidad de elementos, * Lo agrego. */ this.paginas.Add(value); } } } } } }
3b96a6a5399f181c64909f5f0b7922c23a0fb97a
C#
harindya/Black-Dot-Test
/Bds.Tech.Test/Model/ResultMixer.cs
2.75
3
using Bds.Tech.Test.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bds.Tech.Test.Model { public class ResultMixer { IList<ISearchEngine> searchEngines = new List<ISearchEngine>(); public void RegisterSearchEngine(ISearchEngine searchEngine) { searchEngines.Add(searchEngine); } public async Task<IEnumerable<Result>> GetCombinedSearchResultsAsync(string searchTerm) { IList<IList<Result>> resultSets = new List<IList<Result>>(); foreach (var engine in searchEngines) { var res = await engine.GetResultsAsync(searchTerm); resultSets.Add(res); } return CombineResults(resultSets); } private IEnumerable<Result> CombineResults(IList<IList<Result>> resultSets) { var maxLength = (from i in resultSets select i.Count).Max(); for (int i = 0; i < maxLength; i++) { foreach (var results in resultSets) { var element = results.ElementAtOrDefault(i); if (element != null) { yield return element; } else { continue; } } } } } }
d344d4a03333a35cd8c946c07e8bc9bd3a5a50cb
C#
yavuzkocar/art-eksi
/Program.cs
3.359375
3
using System; namespace artieksi { class Result { /* * Complete the 'plusMinus' function below. * * The function accepts INTEGER_ARRAY arr as parameter. */ public static void plusMinus(string arr) { char[] bosluk = new char[] { ' ', '.' }; string[] sayi = arr.Split(bosluk, StringSplitOptions.RemoveEmptyEntries); decimal pozitif = 0; decimal negatif = 0; decimal sifir = 0 ; foreach (var sub in sayi) { int b = int.Parse(sub); decimal artieksi= b<0 ? negatif++ : b>0 ? pozitif++ : sifir++ ; } decimal k = pozitif+negatif+sifir ; decimal pson=Convert.ToDecimal( pozitif/k) ; string pson1=string.Format("{0:0.000000}", pson); decimal nson=Convert.ToDecimal( negatif/k) ; string nson1=string.Format("{0:0.000000}", nson); decimal sson=Convert.ToDecimal( sifir/k); string sson1=string.Format("{0:0.000000}", sson); Console.WriteLine(pson1); Console.WriteLine(nson1); Console.WriteLine(sson1); } } class Solution { public static void Main(string[] args) { int n = Convert.ToInt32(Console.ReadLine().Trim()); string arr = Console.ReadLine(); Result.plusMinus(arr); } } }
93ffc6ac2b081efd13fdb437c686206fa735e954
C#
emoacht/Wifinian
/Source/Wifinian/Views/Controls/SimpleToggleButton.cs
2.546875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace Wifinian.Views.Controls { [TemplateVisualState(Name = "Normal", GroupName = "CommonStates")] [TemplateVisualState(Name = "MouseOver", GroupName = "CommonStates")] [TemplateVisualState(Name = "Pressed", GroupName = "CommonStates")] [TemplateVisualState(Name = "Disabled", GroupName = "CommonStates")] [TemplateVisualState(Name = "Checked", GroupName = "CommonStates")] public class SimpleToggleButton : Button { #region Property public bool IsChecked { get { return (bool)GetValue(IsCheckedProperty); } set { SetValue(IsCheckedProperty, value); } } public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register( "IsChecked", typeof(bool), typeof(SimpleToggleButton), new FrameworkPropertyMetadata(false)); #endregion public override void OnApplyTemplate() { base.OnApplyTemplate(); //this.LayoutUpdated += (sender, e) => UpdateState(false); } protected override void OnClick() { OnToggle(); base.OnClick(); } protected virtual void OnToggle() { IsChecked = !IsChecked; } protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) { base.OnPropertyChanged(e); if ((e.Property == IsMouseOverProperty) || (e.Property == IsKeyboardFocusedProperty) || (e.Property == IsPressedProperty) || (e.Property == IsEnabledProperty) || (e.Property == IsCheckedProperty)) UpdateState(true); } protected virtual void UpdateState(bool useTransitions) { VisualStateManager.GoToState(this, GetVisualStateName(), useTransitions); } private string GetVisualStateName() { if (!IsEnabled) return "Disabled"; if (IsChecked) return "Checked"; if (IsPressed) return "Pressed"; if (IsMouseOver) return "MouseOver"; return "Normal"; } } }
89dc8c52847aeca4aacc52d757f021d28318aa23
C#
Lucasciappa/.Net-Curso
/Observer/Observer/Graph.cs
2.890625
3
using System; using System.Collections.Generic; using System.Text; namespace Observer { public class Graph<T> : Observer<T> { public Graph() : base() { } public Graph(T data) : base(data) { } public override void Update(T data) { Console.WriteLine("Hola soy Graph -> " + data.ToString()); } } }
2e3aa9f9e3c697f95044375c9e4576278e5b51ac
C#
john-clark/rust-oxide-umod
/old/plugins/rust/BetterBatteries.cs
2.65625
3
using Newtonsoft.Json; using Oxide.Core; namespace Oxide.Plugins { [Info("Better Batteries", "Orange", "1.0.1")] [Description("Allows players to get better batteries")] public class BetterBatteries : RustPlugin { #region Vars private const string permUse = "InfiniteBatteries.use"; #endregion #region Config private static ConfigData config; private class ConfigData { [JsonProperty(PropertyName = "Make batteries infinite capacity")] public bool capacity; [JsonProperty(PropertyName = "Make batteries increaced power")] public bool output; [JsonProperty(PropertyName = "Make all batteries better")] public bool all; } private ConfigData GetDefaultConfig() { return new ConfigData { capacity = false, output = false, all = false }; } protected override void LoadConfig() { base.LoadConfig(); try { config = Config.ReadObject<ConfigData>(); } catch { LoadDefaultConfig(); } SaveConfig(); } protected override void LoadDefaultConfig() { PrintError("Configuration file is corrupt(or not exists), creating new one!"); config = GetDefaultConfig(); } protected override void SaveConfig() { Config.WriteObject(config); } #endregion #region Oxide Hooks private void OnServerInitialized() { permission.RegisterPermission(permUse, this); if (config.all) { ChangeAllBatteries(); } } private void OnEntitySpawned(BaseNetworkable a) { var entity = a.GetComponent<ElectricBattery>(); if (entity == null) {return;} if (HasPerm(entity.OwnerID.ToString()) || config.all) { ChangeBattery(entity); } } #endregion #region Helpers private bool HasPerm(string id) { return permission.UserHasPermission(id, permUse); } #endregion #region Core private void ChangeBattery(ElectricBattery battery) { if (config.capacity) { battery.maxCapactiySeconds = 86399; battery.capacitySeconds = battery.maxCapactiySeconds; } if (config.output) { battery.maxOutput = 10000; } } private void ChangeAllBatteries() { foreach (var battery in UnityEngine.Object.FindObjectsOfType<ElectricBattery>()) { ChangeBattery(battery); } } #endregion } }
42e894a6a59ca5228444dfbecce32d684b2b4917
C#
chenjiancheng/WindowsService1
/WindowsService1/Utils/IPUtil.cs
2.6875
3
using NLog.LogReceiverService; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace WindowsService1 { class IPUtil { public const int PORT_TREE = 44675; public static string[] GetLocalIpv4() { //事先不知道ip的个数,数组长度未知,因此用StringCollection储存 IPAddress[] localIPs; localIPs = Dns.GetHostAddresses(Dns.GetHostName()); StringCollection IpCollection = new StringCollection(); foreach (IPAddress ip in localIPs) { //根据AddressFamily判断是否为ipv4,如果是InterNetWorkV6则为ipv6 if (ip.AddressFamily == AddressFamily.InterNetwork) IpCollection.Add(ip.ToString()); } string[] IpArray = new string[IpCollection.Count]; IpCollection.CopyTo(IpArray, 0); return IpArray; } } }
69fedee7ad524d1e873560bd294b467299ea6be9
C#
shendongnian/download4
/first_version_download2/595916-57904280-205217655-4.cs
2.59375
3
public async Task<bool> InsertCard(Card card) { try { await _dbContext.AddAsync(card); _dbContext.SaveChanges(); return true; } catch { return false; } }
220447d2bddd1b0a03400202398164e4e5ff2d71
C#
chadbengen/Finbuckle.MultiTenant.Contrib
/src/Finbuckle.MultiTenant.Contrib.Strategies/FormStrategyConfiguration.cs
2.671875
3
using Microsoft.Extensions.Options; using System; using System.Collections.Generic; namespace Finbuckle.MultiTenant.Contrib { public class OptionSnapshotFormStrategyConfiguration : IOptionsSnapshot<FormStrategyConfiguration> { public OptionSnapshotFormStrategyConfiguration(FormStrategyConfiguration value) { Value = value ?? throw new ArgumentNullException(nameof(value)); } public FormStrategyConfiguration Value { get; } public FormStrategyConfiguration Get(string name) { throw new NotImplementedException(); } } /// <summary> /// Defines the configuration values for the <see cref="Strategies.FormStrategy"/>. /// </summary> public class FormStrategyConfiguration { public List<FormStrategyParameter> Parameters { get; set; } } /// <summary> /// A configuration parameter used by the <see cref="Strategies.FormStrategy"/> to lookup the current tenant. /// </summary> public class FormStrategyParameter { /// <summary> /// The controller /// </summary> public string Controller { get; set; } /// <summary> /// The action method /// </summary> public string Action { get; set; } /// <summary> /// The name of the variable /// </summary> public string Name { get; set; } /// <summary> /// Defines how to find the tenant in the <see cref="IMultiTenantStore"/>. /// </summary> public FormStrategyParameterType Type { get; set; } = FormStrategyParameterType.Identifier; } public enum FormStrategyParameterType { /// <summary> /// Finds the tenant by <see cref="TenantInfo.Identifier"/> /// </summary> Identifier = 1, /// <summary> /// Finds the tenant by <see cref="TenantInfo.Id"/> /// </summary> Id = 2 } }
3777f7bfb255cfd20f969739c909c1b9e2435fd6
C#
Skytim/FormTest
/Test/DataSourceSpecial.cs
2.96875
3
using System.Collections.Generic; using System.Data; using System.Windows.Forms; namespace Test { public class DataSourceSpecial { public static DataTable CreateSource(DataGridView productTable, Dictionary<string, string> scrapeData) { var table = new DataTable(); table.Columns.Add("DrawNo", typeof(int)); if (productTable.Rows.Count <= 1) { var count = productTable.RowCount; table.Columns.Add("Results_0", typeof(string)); if (count != 0) { count = count - 1; } ++count; foreach (var item in scrapeData) { var row = table.NewRow(); row["DrawNo"] = item.Key; row["Results_0"] = item.Value; table.Rows.Add(row); } return table; } else { var columnCount = productTable.Rows[0].Cells.Count - 1; productTable.Columns.Add("Results_" + columnCount, "Results_" + columnCount); var drawNoList = productTable.Rows.Count-1; var addColumnNo = productTable.Rows[0].Cells.Count; for (var i = 0; i < drawNoList; i++) { productTable.Rows[i].Cells[addColumnNo - 1].Value = "test"; //var result = scrapeData[drawNo]; } return (DataTable)(productTable.DataSource); ; } } } }
2493831463b6ac140a4b031bc353d88920138b6e
C#
Unit67/MDSimulator
/Assets/_Skrypty/_SaveSystem/SaveSystem.cs
2.796875
3
using UnityEngine; using System.IO; using System.Runtime.Serialization.Formatters.Binary; public static class SaveSystem { public static void SavePlayer(PlayerController player) { BinaryFormatter binaryFormatter = new BinaryFormatter(); string path = Application.persistentDataPath + "/player.MDSimulatorSaveFile"; FileStream fileStream = new FileStream(path, FileMode.Create); PlayerData data = new PlayerData(player); binaryFormatter.Serialize(fileStream, data); fileStream.Close(); } public static PlayerData LoadPlayer() { string path = Application.persistentDataPath + "/player.MDSimulatorSaveFile"; if(File.Exists(path)) { BinaryFormatter binaryFormatter = new BinaryFormatter(); FileStream fileStream = new FileStream(path,FileMode.Open); PlayerData data = binaryFormatter.Deserialize(fileStream) as PlayerData; Debug.Log("Des: " + data.Des + " Money:" + data.Money + " Pos: " + data.Pos[0] + " " + data.Pos[1] + " " + data.Pos[2]); fileStream.Close(); return data; } else { Debug.LogError("Save file not found in" + path); return null; } } public static Vector3 GetPlayerPos() { string path = Application.persistentDataPath + "/player.MDSimulatorSaveFile"; Vector3 Pos = new Vector3(); if(File.Exists(path)) { BinaryFormatter binaryFormatter = new BinaryFormatter(); FileStream fileStream = new FileStream(path, FileMode.Open); PlayerData data = binaryFormatter.Deserialize(fileStream) as PlayerData; if(data.Pos != null) { Pos = new Vector3(data.Pos[0], data.Pos[1], data.Pos[2]); return Pos; } } return Pos; } }
4c8c1c781f5cec673ff8de3cd0f7cff2c4f5e9e4
C#
gocevskam/CSharp
/01Homework.Arrays/05.MaxIncreasingSequence/MaxIncreasingSequence.cs
4.03125
4
using System; class MaxIncreasingSequence { static void Main() { int[] array = {3, 5, 4, 6, 8, 9, 10, 11, 15, 4, 5, 2, 3 }; int maxSequence = 0; int seqence = 1; int endIndex = 0; for (int i = 0; i < array.GetLength(0) - 1; i++) { if (array[i] < array[i + 1]) seqence++; else { if (seqence > maxSequence) { maxSequence = seqence; endIndex = i; } seqence = 1; } } if (seqence > maxSequence) { maxSequence = seqence; endIndex = array.Length - 1; } seqence = 1; Console.WriteLine("The longest sequence of increasing elements is:"); for (int i = endIndex - maxSequence + 1; i < maxSequence; i++) { Console.Write("{0} ", array[i]); } Console.WriteLine(); } }
bcd5c1e8994146bd1b830d50fef50d80867e6951
C#
Mikah-Kainen/FlappyBirdForNeuralNetTesting
/FlappyBird/GameObject.cs
2.640625
3
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Text; namespace FlappyBird { public abstract class GameObject { public Vector2 Pos { get; set; } public Vector2 Size { get; set; } public Vector2 Scale { get; set; } public Vector2 Origin { get; set; } public Rectangle HitBox => new Rectangle((int)(Pos.X - Origin.X * Scale.X), (int)(Pos.Y - Origin.Y * Scale.Y), (int)(Size.X * Scale.X), (int)(Size.Y * Scale.Y)); public object Tag { get; set; } public bool IsVisible { get; set; } public GameObject(Vector2 pos, Vector2 size, Vector2 scale, Vector2 origin) { Pos = pos; Size = size; Scale = scale; Origin = origin; IsVisible = true; } public abstract void Update(GameTime gameTime); public abstract void Draw(SpriteBatch spriteBatch); } }
a97f37e96e75bc650e37ca5618a4ad4daa083282
C#
lostmsu/Quarrel
/src/Quarrel/Converters/AuditLog/ChangeToVisibilityConveter.cs
2.734375
3
// Copyright (c) Quarrel. All rights reserved. using DiscordAPI.API.Guild.Models; using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; namespace Quarrel.Converters.AuditLog { /// <summary> /// Converter to check if change needs to be shown. /// </summary> public class ChangeToVisibilityConveter : IValueConverter { /// <summary> /// Determines if the Change should be visilble. /// </summary> /// <param name="value">Change to be checked for visibility.</param> /// <param name="targetType">Windows.UI.Xaml.Visibility.</param> /// <param name="parameter">Extra info.</param> /// <param name="language">What language the user is using.</param> /// <returns>Whether or not the change should show.</returns> public object Convert(object value, Type targetType, object parameter, string language) { bool hide = true; if (value is Change change) { hide = change.NewValue == null; hide = hide || change.Key == "inviter_id"; } return hide ? Visibility.Collapsed : Visibility.Visible; } /// <inheritdoc/> public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } }
b34e75320e8e7fe3db00db3e66e7f64561e1bca5
C#
Lotus-heart/Job_Schedule
/JCB.cs
2.765625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace 作业调度C_sharp { public enum Status { Wait, Run, Finish }; [Serializable] public class JCB : BaseClone<JCB> { //计时器 public static double Time { get; set; } //内存最大作业数 public static int Number = 1; //作业名 private string _name; public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } //作业状态 private Status _status; public Status Statu { get { return _status; } set { _status = value; OnPropertyChanged("Statu"); } } //作业优先级 public int Super { get; set; } //需要时间 public double Ntime { get; set; } //运行时间 public double Rtime { get; set; } //到达时间 public double Atime { get; set; } //开始时间 public double Stime { get; set; } //完成时间 public double Ftime { get; set; } //周转时间 public double ZzTime { get; set; } //带权周转时间 public double DqzzTime { get; set; } //平均周转时间 public double AzzTime { get; set; } //带权平均周转时间 public double AdqzzTime { get; set; } public event PropertyChangedEventHandler PropertyChanged; protected internal virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } //先来先服务算法 public static void FCFS(List<JCB> JCBs) { //按到达时间排序 JCBs.Sort(delegate (JCB x, JCB y) { return x.Atime.CompareTo(y.Atime); }); //就绪队列 List<JCB> Ready = new List<JCB>(); //运行队列 List<JCB> Run = new List<JCB>(); //进程个数 int n = JCBs.Count(); //进程处理个数 int flag = 0; //计算开始、完成时间 for (int i = 0; flag != n;) { //加入就绪队列 EnReadyQueue(Ready, JCBs, n, ref i); //加入运行队列 if (Ready.Count() != 0 || Run.Count() != JCB.Number) { if (Ready.Count() == 0 && Run.Count() == 0) { Time++; continue; } Enqueue(Ready, Run); } if (Run.Count() != 0) Count_number(Run, ref flag); } //按开始时间排序 JCBs.Sort(delegate (JCB x, JCB y) { return x.Stime.CompareTo(y.Stime); }); Time = 0; } //优先级调度算法 public static void Static_priority(List<JCB> JCBs) { //按到达时间排序 JCBs.Sort(delegate (JCB x, JCB y) { return x.Atime.CompareTo(y.Atime); }); //就绪队列 List<JCB> Ready = new List<JCB>(); //运行队列 List<JCB> Run = new List<JCB>(); //作业个数 int n = JCBs.Count(); //作业处理个数 int flag = 0; //计算开始、完成时间 for (int i = 0; flag != n;) { //加入就绪队列 EnReadyQueue(Ready, JCBs, n, ref i); //加入运行队列 if (Ready.Count() != 0 || Run.Count() == 0) { //按照优先级进行排序 Ready.Sort(delegate (JCB X, JCB Y) { return X.Super.CompareTo(Y.Super); }); if (Ready.Count() == 0 && Run.Count() == 0) { Time++; continue; } Enqueue(Ready, Run); } if (Run.Count() != 0) Count_number(Run, ref flag); } //按开始时间排序 JCBs.Sort(delegate (JCB x, JCB y) { return x.Stime.CompareTo(y.Stime); }); //重置 Time = 0; } //短作业优先算法 public static void Short_priority(List<JCB> JCBs) { //按到达时间排序 JCBs.Sort(delegate (JCB x, JCB y) { return x.Atime.CompareTo(y.Atime); }); //就绪队列 List<JCB> Ready = new List<JCB>(); //运行队列 List<JCB> Run = new List<JCB>(); //作业个数 int n = JCBs.Count(); //作业处理个数 int flag = 0; //计算开始、完成时间 for (int i = 0; flag != n;) { //加入就绪队列 EnReadyQueue(Ready, JCBs, n, ref i); //加入运行队列 if (Ready.Count() != 0 || Run.Count() == 0) { //按照运行时间进行排序 Ready.Sort(delegate (JCB X, JCB Y) { return X.Ntime.CompareTo(Y.Ntime); }); if (Ready.Count() == 0 && Run.Count() == 0) { Time++; continue; } Enqueue(Ready, Run); } if (Run.Count() != 0) Count_number(Run, ref flag); } //按开始时间排序 JCBs.Sort(delegate (JCB x, JCB y) { return x.Stime.CompareTo(y.Stime); }); //重置 Time = 0; } //高响应比算法 public static void Hrrn(List<JCB> JCBs) { //按到达时间排序 JCBs.Sort(delegate (JCB x, JCB y) { return x.Atime.CompareTo(y.Atime); }); //就绪队列 List<JCB> Ready = new List<JCB>(); List<JCB> Ready2 = new List<JCB>(); //运行队列 List<JCB> Run = new List<JCB>(); //作业个数 int n = JCBs.Count(); //作业处理个数 int flag = 0; //计算开始、完成时间 for (int i = 0; flag != n;) { //加入就绪队列 EnReadyQueue(Ready, JCBs, n, ref i); //加入运行队列 if (Ready.Count() != 0 || Run.Count() == 0) { Count_hrrn(Ready); //按照响应时间进行排序 Ready.Sort(delegate (JCB X, JCB Y) { return -X.Super.CompareTo(Y.Super); }); if (Ready.Count() == 0 && Run.Count() == 0) { Time++; continue; } Enqueue(Ready, Run); } if (Run.Count() != 0) Count_number(Run, ref flag); } //按开始时间排序 JCBs.Sort(delegate (JCB x, JCB y) { return x.Stime.CompareTo(y.Stime); }); //重置 Time = 0; } //计算优先权函数 private static void Count_hrrn(List<JCB> ready) { int n = ready.Count(); for(int i = 0; i < n; i++) { ready[i].Super = (int)(1 + (Time - ready[i].Atime) / ready[i].Ntime); } } //分析函数 public static void Analyse(List<JCB> JCBs) { int n = JCBs.Count(); //计算周转、带权周转时间 for (int i = 0; i < n; i++) { //周转时间 = 完成时间 - 到达时间 JCBs[i].ZzTime = JCBs[i].Ftime - JCBs[i].Atime; //带权周转时间 = 周转时间 / 运行时间 JCBs[i].DqzzTime = Math.Round(JCBs[i].ZzTime / JCBs[i].Ntime, 2); } //计算平均周转时间,平均带权周转时间 double SzzTime = 0; double SdqzzTime = 0; for (int i = 0; i < n; i++) { SzzTime = SzzTime + JCBs[i].ZzTime; SdqzzTime = SdqzzTime + JCBs[i].DqzzTime; //平均周转时间 = 周转时间和 / 个数 JCBs[i].AzzTime = Math.Round(SzzTime / n, 2); //平均带权周转时间 = 带权周转时间和 / 个数 JCBs[i].AdqzzTime = Math.Round(SdqzzTime / n, 2); } } public override JCB Clone() { return base.Clone(); } //计数操作 public static void Count_number(List<JCB> Run, ref int flag) { //将1s拆分 for (int j = 0; j < Run.Count(); j++) { //计算运行时间 Run[j].Rtime += 1.0 / Run.Count(); } Time++; //判断是否出队列 for (int j = 0; j < Run.Count(); j++) { if (Run[j].Rtime >= Run[j].Ntime) { Run[j].Ftime = Time; Run[j].Statu = Status.Finish; //时钟校正 //Time--; Run.RemoveAt(j); j--; flag++; } } } //进运行队列操作 public static void Enqueue(List<JCB> Ready,List<JCB> Run) { //非抢占 while (Run.Count() != JCB.Number && Ready.Count() != 0) { //进队 Run.Add(Ready[0]); //出队 Ready.RemoveAt(0); } //设置状态 for (int j = 0; j < Run.Count(); j++) { Run[j].Statu = Status.Run; //开始时间 if (Run[j].Rtime == 0) Run[j].Stime = Time; } } //进就绪队列操作 public static void EnReadyQueue(List<JCB> Ready, List<JCB> JCBs,int n,ref int i) { //加入就绪队列 while (i < n && JCBs[i].Atime == Time) { Ready.Add(JCBs[i]); i++; } } } /// <summary> /// 通用的深复制方法 /// </summary> /// <typeparam name="T"></typeparam> [Serializable] public class BaseClone<T> { public virtual T Clone() { MemoryStream memoryStream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(memoryStream, this); memoryStream.Position = 0; return (T)formatter.Deserialize(memoryStream); } } }
ffc38ee02956012b0f2a3203d672daf223b5f677
C#
genyosha/Isp01_batrak_vd_mdk0101
/self_task/work 20.02.2020/projects/SampleConsoleApp_01/Hierarchy01/Student.cs
3.53125
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace batrak_20._02 { class Student : Person { private int course; private string group; public int Course { get { return course; } set { course = value; } } public string Group { get { return group; } set { group = value; } } public Student(int age, string name, int course, string group) : base(age, name) { this.course = course; this.group = group; } public int NextCourse() { int nextCourse = course++; return nextCourse; } public override void Print() { Console.WriteLine(ToString()); } public override string ToString() { return "Course: " + course + "Group: "+ group; } } }
91686534f51582190ec2956aeb7ec3ef004a5433
C#
mguid65/RTC3
/Real-Time Corruptor/BizHawk_RTC/BizHawk.Common/AWEMemoryStream.cs
2.796875
3
using System; using System.IO; using System.Collections.Generic; using System.Runtime.InteropServices; namespace BizHawk.Common { /// <summary> /// A MemoryStream that uses AWE to achieve a large addressable area, without being subject to 32 bit address space limits. /// </summary> public class AWEMemoryStream : Stream { const int kBlockSizeBits = 20; const int kBlockSize = 1 << 20; [DllImport("kernel32.dll", SetLastError = true)] static extern bool VirtualFree(IntPtr lpAddress, IntPtr dwSize, uint dwFreeType); [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr VirtualAlloc(IntPtr lpAddress, IntPtr dwSize, AllocationType flAllocationType, MemoryProtection flProtect); [Flags] enum MemoryProtection : uint { EXECUTE = 0x10, EXECUTE_READ = 0x20, EXECUTE_READWRITE = 0x40, EXECUTE_WRITECOPY = 0x80, NOACCESS = 0x01, READONLY = 0x02, READWRITE = 0x04, WRITECOPY = 0x08, GUARD_Modifierflag = 0x100, NOCACHE_Modifierflag = 0x200, WRITECOMBINE_Modifierflag = 0x400 } [Flags] enum AllocationType : uint { COMMIT = 0x1000, RESERVE = 0x2000, RESET = 0x80000, LARGE_PAGES = 0x20000000, PHYSICAL = 0x400000, TOP_DOWN = 0x100000, WRITE_WATCH = 0x200000 } public AWEMemoryStream() { // bootstrap the datastructures Position = 0; // allocate the window (address space that we'll allocate physical pages into) mWindow = VirtualAlloc(IntPtr.Zero, new IntPtr(kBlockSize), AllocationType.RESERVE | AllocationType.PHYSICAL, MemoryProtection.READWRITE); } protected override void Dispose(bool disposing) { if (mWindow != IntPtr.Zero) { VirtualFree(mWindow, IntPtr.Zero, 0x8000U); //MEM_RELEASE mWindow = IntPtr.Zero; } if (disposing) { foreach (var block in mBlocks) block.Dispose(); } } ~AWEMemoryStream() { Dispose(false); } long mLength = 0, mPosition = -1; long mCurrBlock = -1; List<AWEMemoryBlock> mBlocks = new List<AWEMemoryBlock>(); IntPtr mWindow; public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return true; } } public override void Flush() { } public override long Length { get { return mLength; } } public override long Position { get { return mPosition; } set { if (!Ensure(value + 1)) throw new OutOfMemoryException("Couldn't set AWEMemoryStream to specified Position"); mPosition = value; } } public override long Seek(long offset, SeekOrigin origin) { switch (origin) { case SeekOrigin.Begin: Position = offset; return Position; case SeekOrigin.Current: Position += offset; return Position; case SeekOrigin.End: Position = Length + offset; return Position; default: throw new InvalidOperationException(); } } bool Ensure(long len) { long blocksNeeded = (len + kBlockSize - 1) >> kBlockSizeBits; while (mBlocks.Count < blocksNeeded) { var block = new AWEMemoryBlock(); if (!block.Allocate(kBlockSize)) return false; mBlocks.Add(block); } return true; } public override void SetLength(long value) { if (!Ensure(value)) throw new OutOfMemoryException("Couldn't set AWEMemoryStream to specified Length"); mLength = value; } public override int Read(byte[] buffer, int offset, int count) { if (count + mPosition > mLength) count = (int)(mLength - mPosition); int ocount = count; while (count > 0) { int todo = count; long lblock = mPosition >> kBlockSizeBits; if (lblock > int.MaxValue) throw new ArgumentOutOfRangeException(); int block = (int)lblock; int blockOfs = (int)(mPosition - (block << kBlockSizeBits)); int remainsInBlock = kBlockSize - blockOfs; if (remainsInBlock < todo) todo = remainsInBlock; if (mCurrBlock != block) { mCurrBlock = block; if (!mBlocks[block].Map(mWindow)) throw new Exception("Couldn't map required memory for AWEMemoryStream.Write"); } Marshal.Copy(IntPtr.Add(mWindow, blockOfs), buffer, offset, todo); count -= todo; mPosition += todo; offset += todo; } return ocount - count; } public override void Write(byte[] buffer, int offset, int count) { long end = mPosition + count; if (!Ensure(end)) throw new OutOfMemoryException("Couldn't reserve required resources for AWEMemoryStream.Write"); SetLength(end); while (count > 0) { int todo = count; long lblock = mPosition >> kBlockSizeBits; if (lblock > int.MaxValue) throw new ArgumentOutOfRangeException(); int block = (int)lblock; int blockOfs = (int)(mPosition - (block << kBlockSizeBits)); int remainsInBlock = kBlockSize - blockOfs; if (remainsInBlock < todo) todo = remainsInBlock; if (mCurrBlock != block) { mCurrBlock = block; if (!mBlocks[block].Map(mWindow)) throw new Exception("Couldn't map required memory for AWEMemoryStream.Write"); } Marshal.Copy(buffer, offset, IntPtr.Add(mWindow, blockOfs), todo); count -= todo; mPosition += todo; offset += todo; } } unsafe class AWEMemoryBlock : IDisposable { [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool AllocateUserPhysicalPages(IntPtr hProcess, ref uint NumberOfPages, IntPtr PageArray); [DllImport("kernel32.dll")] static extern bool MapUserPhysicalPages(IntPtr lpAddress, uint NumberOfPages, IntPtr UserPfnArray); [DllImport("kernel32.dll")] static extern bool FreeUserPhysicalPages(IntPtr hProcess, ref uint NumberOfPages, IntPtr UserPfnArray); public enum ProcessorArchitecture { X86 = 0, X64 = 9, Arm = -1, Itanium = 6, Unknown = 0xFFFF, } [StructLayout(LayoutKind.Sequential)] public struct SystemInfo { public ProcessorArchitecture ProcessorArchitecture; // WORD public uint PageSize; // DWORD public IntPtr MinimumApplicationAddress; // (long)void* public IntPtr MaximumApplicationAddress; // (long)void* public IntPtr ActiveProcessorMask; // DWORD* public uint NumberOfProcessors; // DWORD (WTF) public uint ProcessorType; // DWORD public uint AllocationGranularity; // DWORD public ushort ProcessorLevel; // WORD public ushort ProcessorRevision; // WORD } [DllImport("kernel32", SetLastError = true)] public static extern void GetSystemInfo(out SystemInfo lpSystemInfo); [StructLayout(LayoutKind.Sequential)] public struct LUID { private uint lp; private int hp; public uint LowPart { get { return lp; } set { lp = value; } } public int HighPart { get { return hp; } set { hp = value; } } } [StructLayout(LayoutKind.Sequential)] public struct LUID_AND_ATTRIBUTES { private LUID luid; private uint attributes; public LUID LUID { get { return luid; } set { luid = value; } } public uint Attributes { get { return attributes; } set { attributes = value; } } } [StructLayout(LayoutKind.Sequential)] public struct TOKEN_PRIVILEGES { private uint prvct; [MarshalAs(UnmanagedType.ByValArray)] //edited from stackoverflow article private LUID_AND_ATTRIBUTES[] privileges; public uint PrivilegeCount { get { return prvct; } set { prvct = value; } } public LUID_AND_ATTRIBUTES[] Privileges { get { return privileges; } set { privileges = value; } } } [DllImport("advapi32", SetLastError = true)] public static extern bool OpenProcessToken(IntPtr ProcessHandle, TokenAccessLevels DesiredAccess, out IntPtr TokenHandle); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, uint BufferLength, out TOKEN_PRIVILEGES PreviousState, out uint ReturnLength); [Flags] internal enum TokenAccessLevels { AssignPrimary = 0x00000001, Duplicate = 0x00000002, Impersonate = 0x00000004, Query = 0x00000008, QuerySource = 0x00000010, AdjustPrivileges = 0x00000020, AdjustGroups = 0x00000040, AdjustDefault = 0x00000080, AdjustSessionId = 0x00000100, Read = 0x00020000 | Query, Write = 0x00020000 | AdjustPrivileges | AdjustGroups | AdjustDefault, AllAccess = 0x000F0000 | AssignPrimary | Duplicate | Impersonate | Query | QuerySource | AdjustPrivileges | AdjustGroups | AdjustDefault | AdjustSessionId, MaximumAllowed = 0x02000000 } //http://stackoverflow.com/questions/13616330/c-sharp-adjusttokenprivileges-not-working-on-32bit [DllImport("advapi32.dll", SetLastError = true)] public static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid); public static bool EnableDisablePrivilege(string PrivilegeName, bool EnableDisable) { var htok = IntPtr.Zero; if (!OpenProcessToken(System.Diagnostics.Process.GetCurrentProcess().Handle, TokenAccessLevels.AdjustPrivileges | TokenAccessLevels.Query, out htok)) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); return false; } var tkp = new TOKEN_PRIVILEGES { PrivilegeCount = 1, Privileges = new LUID_AND_ATTRIBUTES[1] }; LUID luid; if (!LookupPrivilegeValue(null, PrivilegeName, out luid)) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); return false; } tkp.Privileges[0].LUID = luid; tkp.Privileges[0].Attributes = (uint)(EnableDisable ? 2 : 0); TOKEN_PRIVILEGES prv; uint rb; if (!AdjustTokenPrivileges(htok, false, ref tkp, 256, out prv, out rb)) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); return false; } return true; } static AWEMemoryBlock() { var si = new SystemInfo(); GetSystemInfo(out si); PageSize = si.PageSize; } static uint PageSize; static bool PrivilegeAcquired; static object StaticLock = new object(); byte[] pageList; static bool TryAcquirePrivilege() { lock (StaticLock) { if (PrivilegeAcquired) return true; if (EnableDisablePrivilege("SeLockMemoryPrivilege", true)) { PrivilegeAcquired = true; return true; } else return false; } } public bool Allocate(int byteSize) { if (!TryAcquirePrivilege()) return false; long lnPagesRequested = byteSize / PageSize; if (lnPagesRequested > uint.MaxValue) throw new InvalidOperationException(); uint nPagesRequested = (uint)lnPagesRequested; long sizePageList = IntPtr.Size * nPagesRequested; pageList = new byte[sizePageList]; fixed (byte* pPageList = &pageList[0]) { uint nPagesAllocated = nPagesRequested; bool bResult = AllocateUserPhysicalPages(System.Diagnostics.Process.GetCurrentProcess().Handle, ref nPagesAllocated, new IntPtr(pPageList)); if (nPagesRequested != nPagesAllocated) { //abort! we're probably about to bomb the process, but just in case, we'll clean up FreeUserPhysicalPages(System.Diagnostics.Process.GetCurrentProcess().Handle, ref nPagesAllocated, new IntPtr(pPageList)); pageList = null; return false; } } return true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public bool Map(IntPtr targetWindow) { // note: unmapping previous mapping seems unnecessary if (pageList == null) return false; // map the desired physical pages fixed (byte* pPageList = &pageList[0]) { bool bResult = MapUserPhysicalPages(targetWindow, NumPages, new IntPtr(pPageList)); return bResult; } } uint NumPages { get { return (uint)(pageList.Length / (uint)IntPtr.Size); } } protected virtual void Dispose(bool disposing) { if (pageList == null) return; fixed (byte* pPageList = &pageList[0]) { uint nPagesRequested = NumPages; FreeUserPhysicalPages(System.Diagnostics.Process.GetCurrentProcess().Handle, ref nPagesRequested, new IntPtr(pPageList)); pageList = null; } } ~AWEMemoryBlock() { Dispose(false); } } } }
9515b3b27aa253e57a27bc57ce5f36680a16356c
C#
tpsa/pwsg
/wpftutorials/pwsg2/Form1.cs
2.65625
3
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pwsg2 { public partial class Form1 : Form { Color[,] tab; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { DialogResult res = MessageBox.Show("Czy na pewno chcesz wyjść z programu?", "Zamknięcie programu", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question ); if (res != DialogResult.Yes) e.Cancel = true; } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { //MessageBox.Show("sss"); } private void panel1_Paint(object sender, PaintEventArgs e) { } private void Plansza_Enter(object sender, EventArgs e) { } private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e) { } private void button3_Click(object sender, EventArgs e) { DialogResult res = colorDialog1.ShowDialog(); if (res == DialogResult.OK) { button3.BackColor = colorDialog1.Color; pictureBox1.Invalidate(); } } private void button4_Click(object sender, EventArgs e) { DialogResult res = colorDialog2.ShowDialog(); if (res == DialogResult.OK) { button4.BackColor = colorDialog2.Color; pictureBox1.Invalidate(); } } private void radioButton2_CheckedChanged(object sender, EventArgs e) { } private void radioButton1_CheckedChanged(object sender, EventArgs e) { if (tab == null) return; for (int i = 0; i < numericUpDown2.Value; i++) for (int j = 0; j < numericUpDown3.Value; j++) { if ((i + j) % 2 == 0) tab[i, j] = colorDialog1.Color; else tab[i, j] = colorDialog2.Color; } } private void button2_Click(object sender, EventArgs e) { if (radioButton1.Checked) { // Szachownica //pictureBox1.Image. } else { // pusta pictureBox1.BackColor = Color.Black; } } private void numericUpDown2_ValueChanged(object sender, EventArgs e) { } private void numericUpDown3_ValueChanged(object sender, EventArgs e) { } private void numericUpDown4_ValueChanged(object sender, EventArgs e) { if (numericUpDown4.Value * numericUpDown3.Value >= 400) { numericUpDown3.Value = 400 / numericUpDown4.Value; } if (numericUpDown4.Value * numericUpDown2.Value >= 400) { numericUpDown2.Value = 400 / numericUpDown4.Value; } } private void button1_Click(object sender, EventArgs e) { pictureBox1.Invalidate(); } private void pictureBox1_Paint(object sender, PaintEventArgs e) { Rectangle box = new Rectangle(0, 0, 400, 400); Rectangle rect = new Rectangle(0,0,10,10); e.Graphics.FillRectangle(new SolidBrush(colorDialog2.Color), box); e.Graphics.FillRectangle(new SolidBrush(colorDialog1.Color), rect); /* for (int i = 0; i <numericUpDown2.Value; i++) for (int j = 0; j < numericUpDown3.Value; j++) { //Rectangle r = new Rectangle(); Rectangle r = new Rectangle((int)i * (int)numericUpDown4.Value, (int)j * (int)numericUpDown4.Value, (int)numericUpDown4.Value, (int)numericUpDown4.Value); e.Graphics.FillRectangle(new SolidBrush(tab[i, j]),r); } */ } } }
cb6cc2c49688ad25547bd5de9078eb8b6da5a9b0
C#
Enthralment/WebService
/ASP_Hook/Controllers/ValuesController.cs
2.578125
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using HookLib; using Newtonsoft.Json; namespace ASP_Hook.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { static string entryAddr; static Data[] data = new Data[7]; static List<string> parts = new List<string>(); // GET api/values [HttpGet] public IEnumerable<string> Get() { return parts; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return parts[id]; } // POST api/values [HttpPost] public void Post([FromBody]string value) { entryAddr = value; entryAddr = Address.CorrectAddress(Address.AdressParts(value)); parts.Add(entryAddr); } /*public void Post([FromBody]string[] value) { for (int i = 0; i < value.Length; i++) { data[i].Title = value[i]; data[i].Sub = ""; } entryAddr = Address.CorrectAddress(Address.AdressParts(Address.CorrectAddress(data))); for (int i = 0; i < data.Length; i++) { parts.Add(entryAddr); } }*/ // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { entryAddr = Address.CorrectAddress(Address.AdressParts(value)); parts[id] = entryAddr; } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { parts.RemoveAt(id); } } }
e2834f7096fd308d6a4fcf8253cd5d1a64f7d5be
C#
UnitedTraders/Shtirlitz
/Shtirlitz/Common/IStage.cs
2.8125
3
using System.Threading; namespace Shtirlitz.Common { /// <summary> /// Describes one stage in one report generation. /// </summary> public interface IStage { /// <summary> /// Gets the root directory of the report. /// </summary> string RootPath { get; } /// <summary> /// Gets the relative progress weight of this stage. /// /// Basically it should be equal to the number of stages in a composite stage, and 1.0 otherwise. /// </summary> double Weight { get; } /// <summary> /// Gets the user-friendly name of the current stage. /// </summary> string Name { get; } /// <summary> /// Gets the cancellation token for this stage. /// </summary> CancellationToken CancellationToken { get; } /// <summary> /// Gets the type of the current stage. /// </summary> ReportStageType Type { get; } /// <summary> /// Event is raised periodically to notify about the stage progress. /// </summary> event ProgressCallback Progress; /// <summary> /// Synchronously runs the stage. /// </summary> void Run(); } }
2c46b4b6e86c65f85e002f72e3adc2ac067f4b81
C#
shendongnian/download4
/first_version_download2/407763-35602940-111644825-2.cs
2.734375
3
public class EnStatusEnum Converter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return ((enStatus)value).ToString() } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } }
64cc37f48791b7e969add0d0db5dfe9135075c4d
C#
HarveyHuBJ/PowerWorkflow
/PowerWorkflow/Workflow/PowerThreadStateMachine.cs
2.609375
3
using Newtonsoft.Json; using PowerWorkflow.Enums; using PowerWorkflow.Workflow.Exceptions; using System; using System.Collections.Generic; using System.Linq; namespace PowerWorkflow.Workflow { public class PowerThreadStateMachine { /// <summary> /// 节点到节点的自然转换 /// </summary> public List<Transmission> Transmissions { get; set; } [JsonIgnore] public PowerThreadNode StartNode { get { if (!Transmissions.Any()) { throw new InvalidPowerThreadStateMachine(); } return Transmissions.First(p => p.FromNode.IsStart).FromNode; } } public void Next(PowerThreadContext context, PowerThreadNode fromNode) { if (context.IsCurrentNode(fromNode) == false) { throw new InvalidThreadActionException("Not actived thread node!"); } if (fromNode.Equals(PowerThreadDefaultNodes.DefaultEndNode)) { throw new InvalidTransmissionSinceThreadAlreadyEnd(); } var toNode = GetNextNode(context, fromNode); if (toNode != null) { context.PowerThread.SetCurrentNode(toNode); if (!IsEndNode(toNode)) { toNode.LoadNode(); } if (toNode.IsEnd) { context.PowerThread.SetState(PowerThreadState.End); } else if (IsUnfound(toNode)) { context.PowerThread.SetState(PowerThreadState.ErrorMissFoundNode); } else { context.PowerThread.SetState(PowerThreadState.Processing); } } else { // 如果找不到下一个节点, 也认为其结束。 context.PowerThread.SetState(PowerThreadState.End); } } private bool IsEndNode(PowerThreadNode toNode) { return toNode.Equals(PowerThreadDefaultNodes.DefaultEndNode); } private bool IsUnfound(PowerThreadNode toNode) { return toNode.Name == "[UnfoundNode]"; } public void TerminateThread(PowerThreadContext context, PowerThreadNode fromNode) { context.PowerThread.SetState(PowerThreadState.Terminated); } private PowerThreadNode GetNextNode(PowerThreadContext context, PowerThreadNode fromNode) { var transmission = Transmissions.FirstOrDefault(p => p.FromNode.ObjectId == fromNode.ObjectId); if (transmission == null) { return PowerThreadDefaultNodes.DefaultEndNode; } foreach (var item in transmission.ConditionBranches) { if (item.Condition.IsSatisified(context)) { return item.ToNode; } } // return PowerThreadDefaultNodes.MissFoundNode; } } public class Transmission { public Transmission() { ConditionBranches = new List<TransmissionConditionBranch>(); } public Transmission(PowerThreadNode from, PowerThreadNode to) { this.FromNode = from; ConditionBranches = new List<TransmissionConditionBranch>() { new TransmissionConditionBranch{Condition= TransmissionCondition.Default, ToNode = to } }; } public PowerThreadNode FromNode { get; set; } [JsonIgnore] public IList<PowerThreadNode> ToNodes { get { return ConditionBranches.Select(p => p.ToNode).ToList(); } } public IList<TransmissionConditionBranch> ConditionBranches { get; set; } = new List<TransmissionConditionBranch>(); } public class TransmissionConditionBranch { public TransmissionCondition Condition { get; set; } public PowerThreadNode ToNode { get; set; } } public class TransmissionCondition { /// <summary> /// Without judgement /// </summary> public static TransmissionCondition Default = new TransmissionCondition(); public virtual bool IsSatisified(PowerThreadContext context) { return true; } } public class VariableTransmissionCondition : TransmissionCondition { public string VariableExpression { get; set; } public override bool IsSatisified(PowerThreadContext context) { // TODO: test from context variables; return base.IsSatisified(context); } } }
8bad2a226c5003f2a62e5fdc3cc659ea37fb1032
C#
H0nok4/Unity-Training
/目前在做的/SRPG/SRPG DEMO/Assets/Script/Gameplay/BuffSystem/BuffManager.cs
2.578125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class BuffManager { //每个角色都有一个BuffManager实例 private SrpgClassUnit m_Unit; private List<Buff> m_Buffs; public BuffManager(SrpgClassUnit unit) { m_Unit = unit; m_Buffs = new List<Buff>(); } public List<Buff> buffs { get { return m_Buffs; } private set { m_Buffs = value; } } public void AddBuff(Buff newBuff) { bool hasSameBuff = false; for(int i = 0; i < m_Buffs.Count; i++) { if(m_Buffs[i].id == newBuff.id) { //如果有重复的技能,刷新该技能的回合数,尝试叠加层数 hasSameBuff = true; m_Buffs[i].curDurationTimes = m_Buffs[i].maxDurationTimes; if(m_Buffs[i].curOverlayTimes < m_Buffs[i].maxOverlayTimes) { m_Buffs[i].curOverlayTimes++; } break; } } if(!hasSameBuff) { m_Buffs.Add(newBuff); newBuff.OnBuffAdd(m_Unit); } m_Unit.UpdateHPSlider(); } public void AddBuff(string newBuffstr) { var type = Type.GetType(newBuffstr); if(type == null) { Debug.LogError("Error newBuff name not found"); } var newBuff = (Buff)type.Assembly.CreateInstance(newBuffstr); if (newBuff == null) { Debug.LogError("Creat newBuff failure"); } bool hasSameBuff = false; for (int i = 0; i < m_Buffs.Count; i++) { if (m_Buffs[i].id == newBuff.id) { //如果有重复的技能,刷新该技能的回合数,尝试叠加层数 hasSameBuff = true; m_Buffs[i].curDurationTimes = m_Buffs[i].maxDurationTimes; if (m_Buffs[i].curOverlayTimes < m_Buffs[i].maxOverlayTimes) { m_Buffs[i].curOverlayTimes++; } break; } } if (!hasSameBuff) { m_Buffs.Add(newBuff); newBuff.OnBuffAdd(m_Unit); } m_Unit.UpdateHPSlider(); } public void ReduceBuffDuretionTurn() { for(int i = 0; i < m_Buffs.Count; i++) { if(m_Buffs[i].durationType == BuffDurationType.limit) { m_Buffs[i].curDurationTimes--; } } } public void RemoveBuff() { for(int i = m_Buffs.Count - 1; i >= 0 ; i--) { if (m_Buffs[i].curDurationTimes == 0) { m_Buffs[i].OnBuffRemove(m_Unit); m_Buffs.RemoveAt(i); } } } public void RemoveBuff(Buff buff) { m_Buffs.Remove(buff); } }
3ffb6c19c4d638d5e3b07e775650f3a7072ec02b
C#
jonmholt/thoughtworks
/thoughtworks/ReceiptFormatter.cs
3.171875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace thoughtworks { public class ReceiptFormatter { static public string getReceipt(List<IItem> list) { double tax = 0; double total = 0; string receipt = ""; foreach (IItem item in list) { receipt += String.Format("1 {0}: {1:c}\n", item.Description, item.ShelfPrice); tax += item.Tax; total += item.ShelfPrice; } receipt += String.Format("Sales Taxes: {0:c}\n",tax); receipt += String.Format("Total: {0:c}\n", total); return receipt; } } }
661297ca85282c017048ab76cff7a87437f5f944
C#
jlavoine/DotR
/DotR/Assets/Scripts/DotR/Abilities/AbilityData.cs
2.984375
3
using System.Collections.Generic; ////////////////////////////////////////// /// AbilityData /// Immutable data for an ability. ////////////////////////////////////////// public class AbilityData : GenericData { // name of the ability public string Name; // brief description of the ability public string Desc; // amount of cost required to activate the ability public int Cost; // color the ability requires public AbilityColors RequiredColor; // required colors for the chain version public List<AbilityColors> RequiredColors; // target of the ability public CombatTargets Target; // power of the ability public int Power; // list of bonuses this ability has public List<BonusData> Bonuses; // damage types of the ability public List<DamageTypes> DamageTypes; // effects to be applied (if any) public List<AppliedEffectData> AppliedEffects; // effects to be removed (if any) public List<RemovedEffectData> RemovedEffects; public AbilityData() { // since these are optional, let's make sure these variables are instantiated AppliedEffects = new List<AppliedEffectData>(); RemovedEffects = new List<RemovedEffectData>(); DamageTypes = new List<DamageTypes>(); Bonuses = new List<BonusData>(); } ////////////////////////////////////////// /// VerifyChain() /// Returns whether or not the incoming /// list of colors can be matched to this /// ability. ////////////////////////////////////////// public bool VerifyChain( List<AbilityColors> i_listColors ) { // if the chain so far is longer than the ability's required colors, then they are not a match if ( i_listColors.Count > RequiredColors.Count ) return false; // otherwise, let's check to see if there's a match for ( int i = 0; i < i_listColors.Count; ++i ) { if ( i_listColors[i] != RequiredColors[i] ) { return false; } } // if there was a match throughout every color in the chain, verified! return true; } }
f3e53ac432f5d3d4e043b35e18b75b8ede7ce547
C#
a-haapa/village
/village/TaskDB.cs
2.765625
3
using System.Data; using System.IO; using System.Data.SQLite; using System.Data.SQLite.Linq; using System; using System.Collections.Generic; namespace village { public static class TaskDB { private static string filename; private static string tablename; private static string tablename2; private static string tablename3; private static string tablename4; private static string tablename5; private static string tablename6; private static string tablename7; private static string tablename8; static TaskDB() { //Tietokannan taulut filename = village.Properties.Settings.Default.database; tablename = village.Properties.Settings.Default.table1; //asiakas tablename2 = village.Properties.Settings.Default.table2; //lasku tablename3 = village.Properties.Settings.Default.table3; //varaus tablename4 = village.Properties.Settings.Default.table4; //posti tablename5 = village.Properties.Settings.Default.table5; //mökki tablename6 = village.Properties.Settings.Default.table6; //toiminta-alue tablename7 = village.Properties.Settings.Default.table7; //palvelu tablename8 = village.Properties.Settings.Default.table8; //varauksen palvelu } public static DataTable HaeToimintaalue() { //Tietojen haku "Toiminta-alueet" taulusta if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT * FROM {tablename6}", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeTaID(string str) { //Tietojen haku "Toiminta-alueet" taulusta if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT toimintaalue_id FROM {tablename6} WHERE nimi='{str}'", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeToimintaalueMuok(int id) //Luotu oma toiminta-alueen haku muokkausta varten { //Tietojen haku "Toiminta-alueet" taulusta if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT * FROM {tablename6}", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static bool LisaaToimintaalue(Toimintaalue t) { // Lisää käyttäjän kirjaamat toiminta-aluetiedot kantaan try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename};Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"INSERT INTO {tablename6} (nimi)" + $"VALUES ('{t.Nimi}')", connection); cmd.ExecuteNonQuery(); connection.Close(); return true; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static bool LisaaMokki(Mokki m) { // Lisää käyttäjän kirjaamat mökkitiedot tietokantaan try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename};Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"INSERT INTO {tablename5} (mokkinimi,toimintaalue_id,katuosoite,postinro,henkilomaara,kuvaus,varustelu,mokinhinta,mokinalv)" + $"VALUES ('{m.Mokkinimi}','{m.MokinToimintaalue.Toimintaalue_id}','{m.Katuosoite}','{m.Postinro}','{m.Henkilomaara}','{m.Kuvaus}','{m.Varustelu}','{m.Mokinhinta}','{m.Mokinalv}')", connection); cmd.ExecuteNonQuery(); connection.Close(); return true; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static DataTable HaeMokki(int varausid) { //Tietojen haku "Mökki" taulusta toiminta-alueen ja henkilömäärän mukaan if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT toimintaalue.nimi,mokki_id,mokkinimi,mokinhinta,mokinalv,katuosoite,postinro " + $"FROM {tablename5},{tablename3},{tablename6} WHERE varaus.mokki_mokki_id=mokki.mokki_id and varaus.varaus_id='{varausid}' and mokki.toimintaalue_id=toimintaalue.toimintaalue_id", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeMokki2(int id, DateTime date1, DateTime date2) { //Tietojen haku "Mökki" taulusta toiminta-alueen ja henkilömäärän mukaan if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT mokki_id,mokkinimi,henkilomaara,mokinhinta,mokinalv,katuosoite,postinro " + $"FROM {tablename5},{tablename6} WHERE mokki.toimintaalue_id='{id}' and mokki.henkilomaara <'{4}' and mokki_id NOT IN " + $"(SELECT mokki_id FROM {tablename3},{tablename5} " + $"WHERE mokki.mokki_id=varaus.mokki_mokki_id and varaus.varattu_alkupvm BETWEEN '{date1.ToString("yyyy-MM-dd")}' and '{date2.ToString("yyyy-MM-dd")}' and varaus.varattu_loppupvm BETWEEN '{date1.ToString("yyyy-MM-dd")}' and '{date2.ToString("yyyy-MM-dd")}')", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeMokki4(int id, DateTime date1, DateTime date2) { //Tietojen haku "Mökki" taulusta toiminta-alueen ja henkilömäärän mukaan if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT mokki_id,mokkinimi,henkilomaara,mokinhinta,mokinalv,katuosoite,postinro " + $"FROM {tablename5} WHERE toimintaalue_id='{id}' and henkilomaara <'{7}' and mokki_id NOT IN " + $"(SELECT mokki_id FROM {tablename3},{tablename5} " + $"WHERE mokki.mokki_id=varaus.mokki_mokki_id and varaus.varattu_alkupvm BETWEEN '{date1.ToString("yyyy-MM-dd")}' and '{date2.ToString("yyyy-MM-dd")}' and varaus.varattu_loppupvm BETWEEN '{date1.ToString("yyyy-MM-dd")}' and '{date2.ToString("yyyy-MM-dd")}')", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeMokki5(int id, DateTime date1, DateTime date2) { //Tietojen haku "Mökki" taulusta toiminta-alueen ja henkilömäärän mukaan if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT mokki_id,mokkinimi,henkilomaara,mokinhinta,mokinalv,katuosoite,postinro " + $"FROM {tablename5} WHERE mokki.toimintaalue_id='{id}' and mokki.henkilomaara BETWEEN '{7}' and '{10}' and mokki_id NOT IN " + $"(SELECT mokki_id FROM {tablename3},{tablename5} " + $"WHERE mokki.mokki_id=varaus.mokki_mokki_id and varaus.varattu_alkupvm BETWEEN '{date1.ToString("yyyy-MM-dd")}' and '{date2.ToString("yyyy-MM-dd")}' and varaus.varattu_loppupvm BETWEEN '{date1.ToString("yyyy-MM-dd")}' and '{date2.ToString("yyyy-MM-dd")}')", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeMokki6(int id, DateTime date1, DateTime date2) { //Tietojen haku "Mökki" taulusta toiminta-alueen ja henkilömäärän mukaan if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT mokki_id,mokkinimi,henkilomaara,mokinhinta,mokinalv,katuosoite,postinro " + $"FROM {tablename5} WHERE mokki.toimintaalue_id='{id}' and mokki.henkilomaara> '{10}' and mokki_id NOT IN " + $"(SELECT mokki_id FROM {tablename3},{tablename5} " + $"WHERE mokki.mokki_id=varaus.mokki_mokki_id and varaus.varattu_alkupvm BETWEEN '{date1.ToString("yyyy-MM-dd")}' and '{date2.ToString("yyyy-MM-dd")}' and varaus.varattu_loppupvm BETWEEN '{date1.ToString("yyyy-MM-dd")}' and '{date2.ToString("yyyy-MM-dd")}')", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeMokki3(int id, DateTime date1, DateTime date2) { //Tietojen haku "Mökki" taulusta toiminta-alueen ja henkilömäärän mukaan if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT mokki_id,mokkinimi,henkilomaara,mokinhinta,mokinalv,katuosoite,postinro " + $"FROM {tablename5},{tablename6} WHERE mokki.toimintaalue_id='{id}' and mokki_id NOT IN " + $"(SELECT mokki_id FROM {tablename3},{tablename5} " + $"WHERE mokki.mokki_id=varaus.mokki_mokki_id and varaus.varattu_alkupvm BETWEEN '{date1.ToString("yyyy-MM-dd")}' and '{date2.ToString("yyyy-MM-dd")}' and varaus.varattu_loppupvm BETWEEN '{date1.ToString("yyyy-MM-dd")}' and '{date2.ToString("yyyy-MM-dd")}')", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeMokit() { //Tietojen haku "Mökki" taulusta if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT mokki_id,mokkinimi,henkilomaara,mokinhinta,mokinalv,katuosoite,postinro,kuvaus,varustelu FROM {tablename5}", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable Hae(int id) { //Hakee yksittäisen mökin id-numeron perusteella if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT * FROM {tablename5}, {tablename6} WHERE mokki.mokki_id='{id}'", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable PoistaToimintaAlue(int id) { //Tietojen poistaminen tietokannassa "Toiminta-Alue" -kohdasta try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"DELETE FROM {tablename6} WHERE toimintaalue_id = '{id}'", connection); SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); HaeToimintaalue(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static DataTable PoistaMokki(int id) { //Tietojen poistaminen tietokannassa "mökki" -kohdasta try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"DELETE FROM {tablename5} WHERE mokki_id = '{id}'", connection); SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); HaeMokit(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static bool LisaaAsiakas(Asiakas a) { // Lisää käyttäjän kirjaamat asiakastiedot tietokantaan try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename};Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"INSERT INTO {tablename} (etunimi,sukunimi,postinro,lahiosoite,email,puhelinnro)" + $"VALUES ('{a.Etunimi}','{a.Sukunimi}','{a.Postinro}','{a.Lahiosoite}','{a.Email}','{a.Puhelinnro}')", connection); cmd.ExecuteNonQuery(); connection.Close(); return true; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static DataTable HaeAsiakas(Asiakas a) { //Tietojen haku "asiakas" -taulusta sähköpostiosoitteen perusteella if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT * FROM {tablename} WHERE email='{a.Email}'", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeAsID() { //ID haku "asiakas" -taulusta sähköpostiosoitteen perusteella if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT max(asiakas_id) FROM {tablename}", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeAsiakkaanTiedot() { //Tietojen haku "asiakas" -taulusta if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT * FROM {tablename}", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeAs(int varausid) { //Tietojen haku "asiakas" -taulusta if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT asiakas.asiakas_id,etunimi,sukunimi,lahiosoite,postinro FROM {tablename},{tablename3} " + $"WHERE varaus.asiakas_id=asiakas.asiakas_id and varaus.varaus_id='{varausid}'", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static bool MuokkaaAsiakas(Asiakas a) { //Päivittää tiedot asiakas taulussa try { if (System.IO.File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename};Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"UPDATE {tablename} SET etunimi='{a.Etunimi}', asiakas_id='{a.Asiakas_id}', etunimi ='{a.Etunimi}', sukunimi='{a.Sukunimi}'" + $", lahiosoite='{a.Lahiosoite}', postinro='{a.Postinro}', email='{a.Email}',puhelinnro ='{a.Puhelinnro}' WHERE asiakas_id='{a.Asiakas_id}'", connection); cmd.ExecuteNonQuery(); connection.Close(); return true; } else { throw new System.IO.FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static DataTable PoistaAsiakas(int id) { //Tietojen poistaminen tietokannassa "asiakas" -kohdasta try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"DELETE FROM {tablename} WHERE asiakas_id = '{id}'", connection); SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); HaeAsiakkaanTiedot(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static bool MuokkaaToimintaAlue( Toimintaalue t) { //Päivittää tiedot toiminta-alue taulussa try { if (System.IO.File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename};Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"UPDATE {tablename6} SET nimi='{t.Nimi}', toimintaalue_id='{t.Toimintaalue_id}' WHERE toimintaalue_id='{t.Toimintaalue_id}'", connection); cmd.ExecuteNonQuery(); connection.Close(); return true; } else { throw new System.IO.FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static bool MuokkaaMokki(Mokki m) { //Päivittää tiedot mökki taulussa try { if (System.IO.File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename};Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"UPDATE {tablename5} SET mokkinimi='{m.Mokkinimi}', mokki_id='{m.Mokki_id}', henkilomaara='{m.Henkilomaara}', mokinhinta='{m.Mokinhinta}'" + $", katuosoite='{m.Katuosoite}', postinro='{m.Postinro}', kuvaus='{m.Kuvaus}', varustelu='{m.Varustelu}' WHERE mokki_id='{m.Mokki_id}'", connection); cmd.ExecuteNonQuery(); connection.Close(); return true; } else { throw new System.IO.FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static DataTable HaePalvelut() { //Tietojen haku "Palvelu" taulusta if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT palvelu_id,toimintaalue.toimintaalue_id,palvelu.nimi,tyyppi,kuvaus,hinta,alv,toimintaalue.nimi" + $" FROM {tablename7},{tablename6} WHERE palvelu.toimintaalue_id = toimintaalue.toimintaalue_id", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaePalvelunNimi(string ta) { //Tietojen haku "Palvelu" taulusta if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT palvelu.* FROM {tablename6},{tablename7} WHERE palvelu.toimintaalue_id=toimintaalue.toimintaalue_id and toimintaalue.nimi='{ta}'", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static bool LisaaPalvelu(Palvelu p) { // Lisää käyttäjän kirjaamat palvelut kantaan try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename};Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"INSERT INTO {tablename7} (toimintaalue_id,nimi,tyyppi,kuvaus,hinta,alv)" + $"VALUES ('{p.toimintaalue.Toimintaalue_id}','{p.Nimi}','{p.Tyyppi}','{p.Kuvaus}','{p.Hinta}','{p.Alv}')", connection); cmd.ExecuteNonQuery(); connection.Close(); return true; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static bool LisaaVarauksenPalvelu(varausL v, Palvelu p) { // Lisää käyttäjän kirjaamat palvelut kantaan try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename};Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"INSERT INTO {tablename8} (varaus_id,palvelu_id,lkm) VALUES ((SELECT max(varaus_id) FROM {tablename3}),'{p.Palvelu_id}','{v.Lukumaara}')", connection); cmd.ExecuteNonQuery(); connection.Close(); return true; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static DataTable HaeVarauksenPalvelut(int varausid) { //THakee varausten palvelut if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT palvelu.palvelu_id,palvelu.nimi,varauksen_palvelut.lkm,palvelu.hinta FROM {tablename7},{tablename8} " + $"WHERE palvelu.palvelu_id=varauksen_palvelut.palvelu_id and varauksen_palvelut.varaus_id='{varausid}' ", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeVaratutPalv(string toimialue,DateTime alku,DateTime loppu) { //THakee varausten palvelut raporttiin if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT varaus.varaus_id,palvelu.palvelu_id,palvelu.nimi,varauksen_palvelut.lkm,varattu_alkupvm,varattu_loppupvm " + $"FROM {tablename7},{tablename8},{tablename3},{tablename5},{tablename6} " + $"WHERE varauksen_palvelut.palvelu_id=palvelu.palvelu_id and varauksen_palvelut.varaus_id=varaus.varaus_id and mokki.mokki_id=varaus.mokki_mokki_id and toimintaalue.toimintaalue_id=mokki.toimintaalue_id " + $"and varaus.varattu_alkupvm BETWEEN '{alku.ToString("yyyy-MM-dd")}' and '{loppu.ToString("yyyy-MM-dd")}' and toimintaalue.nimi='{toimialue}' ", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaePalv(varausL v) { //THakee varausten palvelut raporttiin if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT palvelu.* FROM {tablename3},{tablename5},{tablename6},{tablename7} " + $"WHERE mokki.mokki_id=varaus.mokki_mokki_id and toimintaalue.toimintaalue_id=mokki.toimintaalue_id " + $"and palvelu.toimintaalue_id=toimintaalue.toimintaalue_id and varaus.varaus_id='{v.Varaus_id}'", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeHinta(Palvelu p) { //THakee varausten palvelut if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT hinta FROM {tablename7} " + $"WHERE nimi='{p.Palvelu_id}' ", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable PoistaPalvelu(int id) { //Tietojen poistaminen tietokannassa "Palvelu" -kohdasta try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"DELETE FROM {tablename7} WHERE palvelu_id = '{id}'", connection); SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); HaePalvelut(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static DataTable PoistaVarauksenPalvelu(int id, int varausid) { //Tietojen poistaminen tietokannassa "Palvelu" -kohdasta try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"DELETE FROM {tablename8} WHERE palvelu_id = '{id}' and varaus_id= '{varausid}'", connection); SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); HaePalvelut(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static bool MuokkaaPalvelu(Palvelu pa) { //Päivittää tiedot palvelu taulussa try { if (System.IO.File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename};Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"UPDATE {tablename7} SET nimi='{pa.Nimi}',tyyppi='{pa.Tyyppi}',kuvaus='{pa.Kuvaus}',hinta='{pa.Hinta}',nimi='{pa.Nimi}',alv='{pa.Alv}' WHERE palvelu_id='{pa.Palvelu_id}'", connection); cmd.ExecuteNonQuery(); connection.Close(); return true; } else { throw new System.IO.FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static bool LisaaVaraus(varausL v) { // Lisää käyttäjän kirjaamat palvelut tietokantaan try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename};Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"INSERT INTO {tablename3} (asiakas_id,mokki_mokki_id,varattu_pvm,vahvistus_pvm,varattu_alkupvm,varattu_loppupvm)" + $"VALUES ('{v.asiakas.Asiakas_id}','{v.Mokki_mokki_id}','{v.Varattu.ToString("yyyy-MM-dd")}','{v.Vahvistus_pvm.ToString("yyyy-MM-dd")}','{v.Varattu_alkupvm.ToString("yyyy-MM-dd")}','{v.Varattu_loppupvm.ToString("yyyy-MM-dd")}')", connection); cmd.ExecuteNonQuery(); connection.Close(); return true; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static DataTable HaeVarausPVM() { //THakee varausten alku ja loppupäivämäärän !!! KESKEN, en tiedä onko sittenkään tarvetta !!! if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT varattu_alkupvm,varattu_loppupvm FROM {tablename3}", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeVaraukset() { //Hakee varaukset if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT varaus.varaus_id,mokki.mokkinimi,varattu_alkupvm,varattu_loppupvm, etunimi,sukunimi " + $"FROM {tablename3} " + $"LEFT JOIN asiakas ON varaus.asiakas_id=asiakas.asiakas_id " + $"LEFT JOIN mokki ON varaus.mokki_mokki_id=mokki.mokki_id", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeVaraus(int varausid) { //Hakee varaukset if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT varaus_id,varattu_pvm,varattu_alkupvm,varattu_loppupvm FROM {tablename3} WHERE varaus_id='{varausid}'", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeVaID() { //THakee varauksen Id:n if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT max(varaus_id) FROM {tablename3}", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable PoistaVaraus(int id) { //Tietojen poistaminen tietokannassa "Palvelu" -kohdasta try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"DELETE FROM {tablename3} WHERE varaus_id = '{id}'", connection); SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); HaePalvelut(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static DataTable HaeRaportti(string toimialue, DateTime alku, DateTime loppu) { //Hakee varaukset if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT mokki_id,mokkinimi,varattu_alkupvm,varattu_loppupvm FROM {tablename5},{tablename3},{tablename6} " + $"WHERE mokki.mokki_id=varaus.mokki_mokki_id and varaus.varattu_alkupvm BETWEEN '{alku.ToString("yyyy-MM-dd")}' and '{loppu.ToString("yyyy-MM-dd")}' and mokki.toimintaalue_id=toimintaalue.toimintaalue_id", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static bool LisaaLasku(Lasku l) { // Lisää käyttäjän kirjaamat palvelut tietokantaan try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename};Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"INSERT INTO {tablename2} (varaus_id,summa,alv)" + $"VALUES ((SELECT max(varaus_id) FROM {tablename3}),'{l.summa}','{l.alv}')", connection); cmd.ExecuteNonQuery(); connection.Close(); return true; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static DataTable HaeLaskut(DateTime alku,DateTime loppu) { //Hakee laskut toivotulle aikavälille if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT varaus.varaus_id,lasku_id,summa,asiakas_id,varattu_alkupvm,varattu_loppupvm FROM {tablename2},{tablename3} " + $"WHERE lasku.varaus_id=varaus.varaus_id and varattu_alkupvm BETWEEN '{alku.ToString("yyyy-MM-dd")}' and '{loppu.ToString("yyyy-MM-dd")}' and varattu_loppupvm BETWEEN '{alku.ToString("yyyy-MM-dd")}' and '{loppu.ToString("yyyy-MM-dd")}'", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeSumma(int lasku_id) { //Hakee laskut toivotulle aikavälille if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT lasku.summa FROM {tablename2},{tablename3},{tablename8},{tablename7} " + $"WHERE varaus.varaus_id=lasku.varaus_id and varauksen_palvelut.varaus_id=varaus.varaus_id and palvelu.palvelu_id=varauksen_palvelut.palvelu_id " + $"and lasku_id='{lasku_id}'", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable HaeKaikkiLaskut() { //Hakee laskut toivotulle aikavälille if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"SELECT varaus.varaus_id,lasku_id,summa,asiakas_id,varattu_alkupvm,varattu_loppupvm FROM {tablename2},{tablename3} WHERE varaus.varaus_id=lasku.varaus_id and varaus.vahvistus_pvm<'{DateTime.Today.ToString("yyyy-MM-dd")}'", connection); //tiedon lukeminen SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } public static DataTable PoistaLasku(int id) { //Tietojen poistaminen tietokannassa "Palvelu" -kohdasta try { if (File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename}; Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"DELETE FROM {tablename2} WHERE varaus_id = '{id}'", connection); SQLiteDataReader rdr = cmd.ExecuteReader(); DataTable tt = new DataTable(); tt.Load(rdr); rdr.Close(); connection.Close(); HaePalvelut(); return tt; } else { throw new FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } public static bool MuokkaaVahvistus(Lasku l, DateTime date) { //Päivittää tiedot palvelu taulussa try { if (System.IO.File.Exists(filename)) { SQLiteConnection connection = new SQLiteConnection($"Data source={filename};Version=3"); connection.Open(); SQLiteCommand cmd = new SQLiteCommand($"UPDATE {tablename3} SET vahvistus_pvm='{date.ToString("yyyy-MM-dd")}' WHERE varaus_id='{l.varaus.Varaus_id}'", connection); cmd.ExecuteNonQuery(); connection.Close(); return true; } else { throw new System.IO.FileNotFoundException("Tiedostoa ei löytynyt"); } } catch { throw; } } } }
ef4a3706a7a73ea231bb36217c947e892efd40b9
C#
DanTup/Google-Wave-Notifier
/GoogleWaveNotifier/Enc.cs
3.421875
3
using System; using System.IO; using System.Text; using System.Security.Cryptography; namespace GoogleWaveNotifier { /// <summary> /// Simple encryption to avoid storing plaintext usernames/passwords in the config file. /// This is not very secure - if someone has a copy of Google Wave Notifier and your config /// file, they can work out your password. Your password is only as secure as the config file! /// </summary> static class Enc { /// <summary> /// Encryption key. This can be changed, but will break backwards compatibility with previously created config files. /// </summary> static readonly byte[] sKey = Convert.FromBase64String("xRYtpojf0oo="); static SymmetricAlgorithm key = new DESCryptoServiceProvider { Key = sKey, IV = sKey }; // Encrypt the string. public static string Encrypt(string text) { // Create a memory stream. MemoryStream ms = new MemoryStream(); // Create a CryptoStream using the memory stream and the // CSP DES key. CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write); // Create a StreamWriter to write a string // to the stream. StreamWriter sw = new StreamWriter(encStream); // Write the plaintext to the stream. sw.WriteLine(text); // Close the StreamWriter and CryptoStream. sw.Close(); encStream.Close(); // Get an array of bytes that represents // the memory stream. byte[] buffer = ms.ToArray(); // Close the memory stream. ms.Close(); // Return the encrypted byte array. return Convert.ToBase64String(buffer); } // Decrypt the byte array. public static string Decrypt(string text) { if (string.IsNullOrEmpty(text)) return null; try { // Create a memory stream to the passed buffer. MemoryStream ms = new MemoryStream(Convert.FromBase64String(text)); // Create a CryptoStream using the memory stream and the // CSP DES key. CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read); // Create a StreamReader for reading the stream. StreamReader sr = new StreamReader(encStream); // Read the stream as a string. string val = sr.ReadLine(); // Close the streams. sr.Close(); encStream.Close(); ms.Close(); return val; } catch { return null; } } } }
1ad305344f39e03ad02d024fe12652e9cd78bd80
C#
shendongnian/download4
/code10/1730667-50141829-172574993-2.cs
3.609375
4
//Change #1 -- new type with space for each attribute public class Employee { public string Name {get;set;} public string code {get;set;} public bool Left {get;set;} } // ... public IEnumerable<Employee> GetEmployees(bool Left) { //Change #2 -- ask for other fields in the the SQL select clause string sql = "Select code, Name, Left from employee where Left= @Left"; using (var cn = new SqlConnection("<CONNECTION STRING>")) using (var cmd = new SqlCommand(sql, cn)) { cmd.Parameters.Add("@Left", SqlDbType.Char, 1).Value = Left?"Y":"N"; cn.Open(); using (var rdr = cmd.ExecuteReader()) { while(rdr.Read()) { //Change #3 -- use all fields from the query results yield return new Employee() { Name = rdr["Name"], code = rdr["code"], Left = (rdr["Left"] == "Y")?true:false }; } rdr.Close(); } } } // ... var employees = GetEmployees(true); foreach (var e in employees) { //Change #4 -- Write all fields to the response. Response.Write("<span>{0}</span><span>{1}</span><span>{2}</span>", e.Name, e.code, e.Left ); }
5458f2ff007bd9dbdd6b135c83e3bd3231a9908e
C#
elifmacit/ClassMetotDemo
/MusteriManager.cs
2.890625
3
using System; using System.Collections.Generic; using System.Text; namespace ClassMetotDemo { class MusteriManager { List<Musteri> musteriler = new List<Musteri>(); public void Ekle(Musteri musteri) { String mesaj = "\n\nTebrikler! Müşteri başarıyla eklendi."; mesaj = mesaj + "\nMüşteri ID\t\t: " + musteri.MusteriID; mesaj = mesaj + "\nMüşteri Adı\t\t: " + musteri.MusteriAdi; mesaj = mesaj + "\nMüşteri Soyadı\t\t: " + musteri.MusteriSoyadi; mesaj = mesaj + "\nMüşteri Yaş\t\t: " + musteri.MusteriYas; mesaj = mesaj + "\nMüşteri Bakiye\t\t: " + musteri.MusteriBakiye; Console.WriteLine(mesaj); musteriler.Add(musteri); } public void Listele() { String mesaj = "Müşteri listesi:\n\n"; foreach (Musteri musteri in musteriler) { mesaj = mesaj + "\nMüşteri ID\t: " + musteri.MusteriID; mesaj = mesaj + "\tMüşteri Adı\t: " + musteri.MusteriAdi; mesaj = mesaj + "\tMüşteri Soyadı\t: " + musteri.MusteriSoyadi; mesaj = mesaj + "\tMüşteri Yaş\t: " + musteri.MusteriYas; mesaj = mesaj + "\tMüşteri Bakiye\t: " + musteri.MusteriBakiye; } Console.WriteLine(mesaj); } public void Sil(Musteri musteri) { Console.WriteLine("Müşteri başarıyla silindi. Müşteri Id : "+musteri.MusteriID); } } }
903d6f6ff5f1ec17b29cee73a05afbd2940885bd
C#
bpbrox/GeniApiSample
/GeniApiSample/JsonDictionary.cs
3.15625
3
/****************************** Module Header ******************************\ Module Name: JsonDictionary.cs Project: GeniApiSample Copyright (c) Bjørn P. Brox <bjorn.brox@gmail.com> THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. \***************************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Text; namespace GeniApiSample { /// <summary> /// The base JSON object is a Dictionary where we avoid KeyNotFoundException's /// by having a object this[key] option which return null if not found. /// </summary> [Serializable] public class JsonDictionary : Dictionary<string, object> { private JsonDictionary(IDictionary<string, object> dictionary) : base(dictionary) { } private JsonDictionary() { } public new object this[string key] { get { object @object; return TryGetValue(key, out @object) ? @object : null; } set { base[key] = value; } } public static JsonDictionary RequestUrl(string url, string accessToken) { return RequestUri(new Uri(url), accessToken); } public static JsonDictionary RequestUri(Uri uri, string accessToken) { using (WebClient request = new WebClient()) { if (accessToken != null) { request.Headers.Add("Authorization", String.Format("Bearer {0}", Uri.EscapeDataString(accessToken))); } return JsonParser.JsonDecode(request.DownloadString(uri)); } } /// <summary> /// This class decodes JSON strings. /// See http://www.json.org/ /// </summary> internal class JsonParser { private enum JsonToken { None = -1, // Used to denote no Lookahead available CurlyOpen, CurlyClose, BracketOpen, BracketClose, Colon, Comma, String, Number, True, False, Null } private readonly char[] _jsonData; private readonly StringBuilder _sb = new StringBuilder(); private JsonToken _lookAheadToken = JsonToken.None; private int _jsonIndex; private JsonParser(string json) { _jsonData = json.ToCharArray(); } /// <summary> /// Decodes a string into a JsonDictionaryclass. /// </summary> /// <param name="jsonString">String to decode</param> /// <returns>Null if decoding fails, JsonDictionaryclass if success</returns> public static JsonDictionary JsonDecode(string jsonString) { try { object jsonObject = new JsonParser(jsonString).ParseValue(); if (jsonObject == null) return null; if (jsonObject is JsonDictionary) return jsonObject as JsonDictionary; return jsonObject is Dictionary<string, object> ? new JsonDictionary((Dictionary<string, object>) jsonObject) : new JsonDictionary(new Dictionary<string, object> {{"results", jsonObject}}); } catch (Exception) { return null; } } private JsonDictionary ParseObject() { JsonDictionary table = new JsonDictionary(); ConsumeToken(); // Skip the { while (true) { switch (LookAhead()) { case JsonToken.Comma: ConsumeToken(); break; case JsonToken.CurlyClose: ConsumeToken(); return table; default: // name string name = ParseString(); // : if (NextToken() != JsonToken.Colon) throw new Exception("Expected colon at index " + _jsonIndex); // value table[name] = ParseValue(); break; } } } private ArrayList ParseArray() { ArrayList array = new ArrayList(); ConsumeToken(); // Skip the [ while (true) { switch (LookAhead()) { case JsonToken.Comma: ConsumeToken(); break; case JsonToken.BracketClose: ConsumeToken(); return array; default: array.Add(ParseValue()); break; } } } private object ParseValue() { switch (LookAhead()) { case JsonToken.Number: return ParseNumber(); case JsonToken.String: return ParseString(); case JsonToken.CurlyOpen: return ParseObject(); case JsonToken.BracketOpen: return ParseArray(); case JsonToken.True: ConsumeToken(); return true; case JsonToken.False: ConsumeToken(); return false; case JsonToken.Null: ConsumeToken(); return null; } throw new Exception("Unrecognized token at index " + _jsonIndex); } private string ParseString() { ConsumeToken(); // " _sb.Length = 0; int runIndex = -1; while (_jsonIndex < _jsonData.Length) { var c = _jsonData[_jsonIndex++]; if (c == '"') { if (runIndex != -1) { if (_sb.Length == 0) return new string(_jsonData, runIndex, _jsonIndex - runIndex - 1); _sb.Append(_jsonData, runIndex, _jsonIndex - runIndex - 1); } return _sb.ToString(); } if (c != '\\') { if (runIndex == -1) runIndex = _jsonIndex - 1; continue; } if (_jsonIndex == _jsonData.Length) break; if (runIndex != -1) { _sb.Append(_jsonData, runIndex, _jsonIndex - runIndex - 1); runIndex = -1; } switch (_jsonData[_jsonIndex++]) { case '"': _sb.Append('"'); break; case '\\': _sb.Append('\\'); break; case '/': _sb.Append('/'); break; case 'b': _sb.Append('\b'); break; case 'f': _sb.Append('\f'); break; case 'n': _sb.Append('\n'); break; case 'r': _sb.Append('\r'); break; case 't': _sb.Append('\t'); break; case 'u': { int remainingLength = _jsonData.Length - _jsonIndex; if (remainingLength < 4) break; // parse the 32 bit hex into an integer codepoint uint codePoint = ParseUnicode(_jsonData[_jsonIndex], _jsonData[_jsonIndex + 1], _jsonData[_jsonIndex + 2], _jsonData[_jsonIndex + 3]); _sb.Append((char) codePoint); // skip 4 chars _jsonIndex += 4; } break; } } throw new Exception("Unexpectedly reached end of string"); } private uint ParseSingleChar(char c1, uint multipliyer) { uint p1 = 0; if (c1 >= '0' && c1 <= '9') p1 = (uint) (c1 - '0')*multipliyer; else if (c1 >= 'A' && c1 <= 'F') p1 = (uint) ((c1 - 'A') + 10)*multipliyer; else if (c1 >= 'a' && c1 <= 'f') p1 = (uint) ((c1 - 'a') + 10)*multipliyer; return p1; } private uint ParseUnicode(char c1, char c2, char c3, char c4) { uint p1 = ParseSingleChar(c1, 0x1000); uint p2 = ParseSingleChar(c2, 0x100); uint p3 = ParseSingleChar(c3, 0x10); uint p4 = ParseSingleChar(c4, 1); return p1 + p2 + p3 + p4; } private object ParseNumber() { ConsumeToken(); // Need to start back one place because the first digit is also a token and would have been consumed var startIndex = _jsonIndex - 1; bool isDouble = false; do { var c = _jsonData[_jsonIndex]; if ((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E') { if (++_jsonIndex == _jsonData.Length) throw new Exception("Unexpected end of string whilst parsing number"); isDouble |= c == '.' || c == 'e' || c == 'E'; continue; } break; } while (true); string numberStr = new string(_jsonData, startIndex, _jsonIndex - startIndex); return isDouble ? Double.Parse(numberStr, NumberStyles.Any, CultureInfo.InvariantCulture) : Int64.Parse(numberStr, NumberStyles.Any, CultureInfo.InvariantCulture); } private JsonToken LookAhead() { if (_lookAheadToken != JsonToken.None) return _lookAheadToken; return _lookAheadToken = NextTokenCore(); } private void ConsumeToken() { _lookAheadToken = JsonToken.None; } private JsonToken NextToken() { var result = _lookAheadToken != JsonToken.None ? _lookAheadToken : NextTokenCore(); _lookAheadToken = JsonToken.None; return result; } private JsonToken NextTokenCore() { char c; // Skip past whitespace do { c = _jsonData[_jsonIndex]; if (c == 0xfeff) // byte order mark (BOM) continue; if (c > ' ') break; if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break; } while (++_jsonIndex < _jsonData.Length); if (_jsonIndex == _jsonData.Length) { throw new Exception("Reached end of string unexpectedly"); } c = _jsonData[_jsonIndex]; _jsonIndex++; switch (c) { case '{': return JsonToken.CurlyOpen; case '}': return JsonToken.CurlyClose; case '[': return JsonToken.BracketOpen; case ']': return JsonToken.BracketClose; case ',': return JsonToken.Comma; case '"': return JsonToken.String; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': case '+': case '.': return JsonToken.Number; case ':': return JsonToken.Colon; case 'f': if (_jsonData.Length - _jsonIndex >= 4 && _jsonData[_jsonIndex + 0] == 'a' && _jsonData[_jsonIndex + 1] == 'l' && _jsonData[_jsonIndex + 2] == 's' && _jsonData[_jsonIndex + 3] == 'e') { _jsonIndex += 4; return JsonToken.False; } break; case 't': if (_jsonData.Length - _jsonIndex >= 3 && _jsonData[_jsonIndex + 0] == 'r' && _jsonData[_jsonIndex + 1] == 'u' && _jsonData[_jsonIndex + 2] == 'e') { _jsonIndex += 3; return JsonToken.True; } break; case 'n': if (_jsonData.Length - _jsonIndex >= 3 && _jsonData[_jsonIndex + 0] == 'u' && _jsonData[_jsonIndex + 1] == 'l' && _jsonData[_jsonIndex + 2] == 'l') { _jsonIndex += 3; return JsonToken.Null; } break; } throw new Exception("Could not find token at index " + --_jsonIndex); } } } }
4b8efefa9299831e0578f819e56b78967d35c7cd
C#
pakrologie/jeuDeDame
/Jeu De Dame - Serveur - Copie/Jeu De Dame - Serveur/CheckTime.cs
2.609375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace Jeu_De_Dame___Serveur { class CheckTime { static Mutex mut = new Mutex(); public static void CheckDuration() { while (true) { mut.WaitOne(); for (int i = 0; i < ClientManager.ListClient.Count; i++) { Timer(i); } mut.ReleaseMutex(); Thread.Sleep(20); } } public static void Timer(int IndexClient) { if (ClientManager.ListClient[IndexClient].info_game.isplaying) { if (ClientManager.ListClient[IndexClient].info_game.tour) { int TimeCount = (Environment.TickCount / 1000) - (ClientManager.ListClient[IndexClient].info_game.timeCount / 1000); if (TimeCount >= 30) { int IndexOpponent = ClientManager.byPseudo(ClientManager.ListClient[IndexClient].info_game.opponent); if (IndexOpponent == -1) { return; } ClientManager.ListClient[IndexClient].info_game.asked = false; ClientManager.ListClient[IndexOpponent].info_game.asked = false; playerManager.ChangeGameTurn(ClientManager.ListClient[IndexClient]); ClientManager.ListClient[IndexClient].SendMsg("Temps écoulé ! Changement de tour !"); ClientManager.ListClient[IndexOpponent].SendMsg("Temps écoulé ! Changement de tour !"); } } } } } }
99385a88010ba830d3c86fa3f558805839b556b0
C#
VB6Hobbyst7/v7-framework
/src/Xeora.CLI/Program.cs
2.5625
3
using System; using System.Reflection; using System.Threading.Tasks; using Xeora.CLI.Basics; namespace Xeora.CLI { public static class Program { public static async Task Main(string[] args) { if (args == null || args.Length == 0) { Program.PrintUsage(); Environment.Exit(0); } ICommand cliCommand = null; switch (args[0]) { case "framework": cliCommand = new Framework(); break; case "create": cliCommand = new Create(); break; case "dss": cliCommand = new Dss(); break; case "run": cliCommand = new Run(); break; case "compile": cliCommand = new Compile(); break; case "publish": cliCommand = new Publish(); break; case "extract": cliCommand = new Extract(); break; case "-v": case "--version": Program.PrintVersionText(); Environment.Exit(0); break; default: Program.PrintUsage(); Console.WriteLine("unrecognizable argument"); Console.WriteLine(); Environment.Exit(2); break; } string[] filtered = new string[args.Length - 1]; Array.Copy(args, 1, filtered, 0, filtered.Length); Environment.Exit(await cliCommand.Execute(filtered)); } private static void PrintVersionText() { System.Version vI = Assembly.GetExecutingAssembly().GetName().Version; Console.WriteLine($"{vI?.Major}.{vI?.Minor}.{vI?.Build}"); } private static void PrintUsage() { Console.WriteLine(); Console.WriteLine("xeora COMMAND"); Console.WriteLine(); Console.WriteLine("Options:"); Console.WriteLine(" -h, --help print this screen"); Console.WriteLine(" -v, --version print CLI version information and quit"); Console.WriteLine(); Console.WriteLine("Commands:"); Console.WriteLine(" compile compile the xeora project for release"); Console.WriteLine(" create create the xeora project from template"); Console.WriteLine(" framework download/update xeora framework executable"); Console.WriteLine(" publish publish the xeora project to the target"); Console.WriteLine(" run run the xeora project"); Console.WriteLine(" dss start the xeora dss service"); Console.WriteLine(); } } }
8b6fd1463218e87910c6d564e0b134318e3a0aff
C#
a592955699/M8cool
/InfoSniffer/PageRequestManager.cs
2.5625
3
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text.RegularExpressions; using System.Collections.Specialized; using System.IO; namespace InfoSniffer { public class PageRequestManager { public static string AppDataPath { get { return HttpRuntime.AppDomainAppPath + @"App_Data\InfoSniffer\"; } } /// <summary> /// 读取所有的配置文件名 /// </summary> /// <returns></returns> public static string[] GetConfigs() { string[] files = System.IO.Directory.GetFiles(AppDataPath, "*.xml"); for (int i = 0; i < files.Length; i++) { string file = files[i]; files[i] = Path.GetFileNameWithoutExtension(file); } return files; } /// <summary> /// 读取根页 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static List<ListPage> GetAllFirstPages(string fileName) { return GetAllFirstPages(fileName, null); } /// <summary> /// 读取根页重载 /// </summary> /// <param name="fileName"></param> /// <param name="rootPageName"></param> /// <returns></returns> public static List<ListPage> GetAllFirstPages(string fileName, string rootPageName) { SnifferConfig.OpenSnfFile(string.Format(AppDataPath + "{0}.xml", fileName)); RootPageConfiguration rootPageConf = SnifferConfig.GetRootPageConfiguration(rootPageName); if (rootPageConf == null) return null; ListPage rootPage = new ListPage((ListPageConfiguration)rootPageConf); List<ListPage> allFirstPages = new List<ListPage>(); if (rootPageConf.IsSniffer) { rootPage.Sniffer(); if (!rootPage.Done || rootPage.SubPageUrlResults.Count == 0) { //采集不到 } foreach (UrlItem urlItem in rootPage.SubPageUrlResults) { ListPage page = new ListPage(rootPage, (ListPageConfiguration)rootPage.ListPageConfiguration.SubPageConfiguration); page.PageName = urlItem.Title; page.PageUrl = urlItem.Url; allFirstPages.Add(page); } } else { foreach (ListPageConfiguration firstPageConfi in rootPageConf.SubPageConfigurations) { allFirstPages.Add(new ListPage(rootPage, firstPageConfi)); } } return allFirstPages; } /// <summary> /// 读取列表页 /// </summary> /// <param name="fileName"></param> /// <param name="rootPageName"></param> /// <param name="firstIndex"></param> /// <param name="pageIndex"></param> /// <returns></returns> public static ListPage GetListPage(string fileName, int firstIndex, int pageIndex) { return GetListPage(fileName, null, firstIndex, pageIndex); } /// <summary> /// 读取列表页重载 /// </summary> public static ListPage GetListPage(string fileName, string rootPageName, int firstIndex, int pageIndex) { List<ListPage> allFirstPages = GetAllFirstPages(fileName, rootPageName); ListPage firstPage = allFirstPages[firstIndex]; //列表页的页码大于1,则要替换页码 if (firstPage.ListPageConfiguration.SubPageConfiguration.PageType == PageType.DetailPage && pageIndex > 1) { if (firstPage.ListPageConfiguration.PageMethod == PageMethod.Get) { ReplacePageIndex(firstPage, pageIndex); } else { firstPage.PageQuery = string.Format(firstPage.PageQuery, pageIndex); } } firstPage.Sniffer(); return firstPage; } /// <summary> /// 读取详细页 /// </summary> /// <param name="fileName"></param> /// <param name="firstIndex"></param> /// <param name="pageIndex"></param> /// <param name="urlIndex"></param> /// <returns></returns> public static DetailPage GetDetailPage(string fileName, int firstIndex, int pageIndex, int urlIndex) { return GetDetailPage(fileName, null, firstIndex, pageIndex, urlIndex); } /// <summary> /// 读取详细页重载 /// </summary> /// <returns></returns> public static DetailPage GetDetailPage(string fileName, string rootPageName, int firstIndex, int pageIndex, int urlIndex) { ListPage firstPage = GetListPage(fileName, rootPageName, firstIndex, pageIndex); UrlItem urlItem = firstPage.SubPageUrlResults[urlIndex]; DetailPageConfiguration detailPageConf = (DetailPageConfiguration)firstPage.ListPageConfiguration.SubPageConfiguration; DetailPage detailPage = new DetailPage(firstPage, detailPageConf); detailPage.PageIndex = detailPageConf.PageStartIndex; detailPage.PageName = urlItem.Title; detailPage.PageUrl = urlItem.Url; detailPage.Sniffer(); return detailPage; } /// <summary> /// 替换页码 /// </summary> /// <param name="listPage"></param> /// <param name="pageIndex"></param> private static void ReplacePageIndex(ListPage listPage, int pageIndex) { string stringPageIndex; if (!string.IsNullOrEmpty(listPage.ListPageConfiguration.PageIndexFormat)) stringPageIndex = pageIndex.ToString(listPage.ListPageConfiguration.PageIndexFormat); else stringPageIndex = pageIndex.ToString(); string pageQuery = string.Format(listPage.ListPageConfiguration.ReplacePageQuery, stringPageIndex); listPage.PageUrl = Regex.Replace(listPage.PageUrl, listPage.ListPageConfiguration.PageQuery, pageQuery); } } }
42afefd765bb71047708aca2617d2a12baaf6f95
C#
Weiaett/dotNetLabs
/lab1/lab1/Actors/Illustrator.cs
3.1875
3
using System; using lab1.Products; namespace lab1.Actors { /// <summary> /// Иллюстратор /// </summary> public class Illustrator : Actor { public Illustrator(string name) : base(name) { } /// <summary> /// Иллюстратор добавляет иллюстрации к уже написанным страницам книги /// </summary> /// <param name="book"></param> public override void MakeBook(IBook book) { Illustration illustration = new Illustration((uint)Random.Next(5, checked((int)book.Text.PagesNum))); book.Illustrations.Add(illustration); Console.WriteLine($"Иллюстрация на {illustration.Page} страницe"); } } }
d267d5605b4a6da999f0e3b9217d4f29ee41a711
C#
GermanKurochkin/10
/lab10/Engine.cs
3.28125
3
using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace lab10 { public interface IExecutable { void Show(); int ToWatt(); } public class SortByPower:IComparer { int IComparer.Compare(object obj1, object obj2) { Engine eng1 = (Engine)obj1; Engine eng2 = (Engine)obj2; if (eng1.Power < eng2.Power) return -1; else if (eng1.Power == eng2.Power) return 0; else return 1; } } public class Engine :IExecutable,IComparable,ICloneable { protected int power; protected string name; public int[] mas = new int[] { 1, 1, 1, 1, 1 }; public int Power { get { return power; } set { if (value < 0) power = 0; else power = value; } } public string Name { get { return name; } set { name = value; } } public Engine() { power = 0; name = "-"; } public Engine(string n,int f) { Name = n; Power = f; } public override bool Equals(object e) { return Name==((Engine)e).Name && Power== ((Engine)e).Power; } public virtual void Show() { Console.WriteLine($"Двигатель {name}; сила тяги - {power} лошадиных сил"); } public void ShowNoVirt() { Console.WriteLine($"Двигатель {name}; сила тяги - {power} лошадиных сил"); } public int ToWatt() { return (int)Math.Round(power * 735.5); } public int CompareTo(object obj) { Engine eng = (Engine)obj; return string.Compare(name, eng.name); } public Engine ShallowCopy() { return (Engine)MemberwiseClone(); } public object Clone() { return new Engine("Клон " + name, power); } } }
e0d3241b238bf7d224b4db6ede6bb6f32391dd82
C#
Guad-in/C-Sharp
/Rock_P_S/Rock_Paper_Scissors.cs
3.4375
3
//Take user input //Generate a random choice //Compare the choice //Declare the winner using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RockPaperScissors { public class Rock_Paper_Scissors { public static void Main(string[] args) { string Yourself; string Selection; int randomInteger; bool go_Again = true; int score_Of_The_Yourself = 0; int score_Of_Selection = 0; while (go_Again) { while (score_Of_The_Yourself < 3 && score_Of_Selection < 3) { Console.Write("Make a choice Rock or Paper Scissors?: "); Yourself = Console.ReadLine(); Yourself = Yourself.ToUpper(); Random randomNum = new Random(); randomInteger = randomNum.Next(1, 3); //Choose a random number between 1 and 4 switch (randomInteger) { case 1: Selection = "ROCK"; Console.Write("Opponent Chose Rock\n"); if (Yourself == "ROCK"&&Selection== "ROCK") { Console.WriteLine("DRAW"); } else if (Yourself == "Paper"&&Selection== "ROCK") { Console.WriteLine(" Opponent WINS!!!!!!!"); score_Of_The_Yourself++; } else if (Yourself == "Scissors"&&Selection== "ROCK") { Console.WriteLine("You Win!!!!!!!"); score_Of_Selection++; } break; case 2: Selection = "PAPER"; Console.Write("Opponent Chose Paper\n"); if (Yourself == "PAPER"|| Yourself == "paper"&& Selection == "PAPER" || Selection == "Paper") { Console.WriteLine("DRAW BABY!!"); } else if (Yourself == "ROCK"|| Yourself == "Rock"&& Selection == "PAPER" || Selection == "Paper") { Console.WriteLine("Opponent WINS!!!!!!!"); score_Of_Selection++; } else if (Yourself == "SCISSORS"||Yourself == "Scissors"&& Selection == "PAPER" || Selection == "Paper") { Console.WriteLine("You Win!!!!!!!"); score_Of_The_Yourself++; } break; case 3: Selection = "SCISSORS"; Console.Write("Opponent Chose Scissors\n"); if (Yourself == "Scissors"|| Yourself == "SCISSORS" && Selection == "SCISSORS" || Selection == "Scissors") { Console.WriteLine(" Draw!!"); } else if (Yourself == "ROCK"||Yourself == "Rock"&& Selection == "SCISSORS" || Selection == "Scissors") { Console.WriteLine("You WIN!!!!!!!"); score_Of_The_Yourself++; } else if (Yourself == "Paper"||Yourself == "PAPER"&& Selection == "SCISSORS" || Selection == "Scissors") { Console.WriteLine("You Win"); score_Of_Selection++; } break; default: Console.WriteLine("Invalid Entry"); break; } } if (score_Of_The_Yourself == 3) { Console.WriteLine("YOU Won!"); } else if (score_Of_Selection == 3) { Console.WriteLine("Opponent Won!"); } else { Console.WriteLine("Draw "); } Console.WriteLine("Play Again?(y/n)"); string loop_Cond = Console.ReadLine(); if (loop_Cond == "Y" || loop_Cond == "y") { go_Again = true; Console.Clear(); } else if (loop_Cond == "N" || loop_Cond == "n") { go_Again = false; } else { } } } } }
8ddce568b170a0a04475bb6e62e60b07f2fd9de5
C#
CollaboratingPlatypus/PetaPoco
/PetaPoco/Core/GridReader.cs
2.828125
3
using System; using System.Collections.Generic; using System.Data; using System.Linq; using PetaPoco.Core; using PetaPoco.Internal; namespace PetaPoco { public class GridReader : IGridReader { private readonly Database _db; private readonly IMapper _defaultMapper; private IDbCommand _command; private IDataReader _reader; /// <summary> /// The control structure for a multi-result set query /// </summary> /// <param name="database"></param> /// <param name="command"></param> /// <param name="reader"></param> /// <param name="defaultMapper"></param> internal GridReader(Database database, IDbCommand command, IDataReader reader, IMapper defaultMapper) { _db = database; _command = command; _reader = reader; _defaultMapper = defaultMapper; } #region public Read<T> methods /// <summary> /// Reads from a GridReader, returning the results as an IEnumerable collection /// </summary> /// <typeparam name="T">The Type representing a row in the result set</typeparam> /// <returns>An enumerable collection of result records</returns> public IEnumerable<T> Read<T>() { return SinglePocoFromIDataReader<T>(_gridIndex); } /// <summary> /// Perform a multi-poco read from a GridReader /// </summary> /// <typeparam name="T1">The first POCO type</typeparam> /// <typeparam name="T2">The second POCO type</typeparam> /// <returns>A collection of POCOs as an IEnumerable</returns> public IEnumerable<T1> Read<T1, T2>() { return MultiPocoFromIDataReader<T1>(_gridIndex, new Type[] { typeof(T1), typeof(T2) }, null); } /// <summary> /// Perform a multi-poco read from a GridReader /// </summary> /// <typeparam name="T1">The first POCO type</typeparam> /// <typeparam name="T2">The second POCO type</typeparam> /// <typeparam name="T3">The third POCO type</typeparam> /// <returns>A collection of POCOs as an IEnumerable</returns> public IEnumerable<T1> Read<T1, T2, T3>() { return MultiPocoFromIDataReader<T1>(_gridIndex, new Type[] { typeof(T1), typeof(T2), typeof(T3) }, null); } /// <summary> /// Perform a multi-poco read from a GridReader /// </summary> /// <typeparam name="T1">The first POCO type</typeparam> /// <typeparam name="T2">The second POCO type</typeparam> /// <typeparam name="T3">The third POCO type</typeparam> /// <typeparam name="T4">The forth POCO type</typeparam> /// <returns>A collection of POCOs as an IEnumerable</returns> public IEnumerable<T1> Read<T1, T2, T3, T4>() { return MultiPocoFromIDataReader<T1>(_gridIndex, new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }, null); } /// <summary> /// Perform a multi-poco query /// </summary> /// <typeparam name="T1">The first POCO type</typeparam> /// <typeparam name="T2">The second POCO type</typeparam> /// <typeparam name="TRet">The type of objects in the returned IEnumerable</typeparam> /// <param name="cb">A callback function to connect the POCO instances, or null to automatically guess the relationships</param> /// <returns>A collection of POCOs as an IEnumerable</returns> public IEnumerable<TRet> Read<T1, T2, TRet>(Func<T1, T2, TRet> cb) { return MultiPocoFromIDataReader<TRet>(_gridIndex, new Type[] { typeof(T1), typeof(T2) }, cb); } /// <summary> /// Perform a multi-poco query /// </summary> /// <typeparam name="T1">The first POCO type</typeparam> /// <typeparam name="T2">The second POCO type</typeparam> /// <typeparam name="T3">The third POCO type</typeparam> /// <typeparam name="TRet">The type of objects in the returned IEnumerable</typeparam> /// <param name="cb">A callback function to connect the POCO instances, or null to automatically guess the relationships</param> /// <returns>A collection of POCOs as an IEnumerable</returns> public IEnumerable<TRet> Read<T1, T2, T3, TRet>(Func<T1, T2, T3, TRet> cb) { return MultiPocoFromIDataReader<TRet>(_gridIndex, new Type[] { typeof(T1), typeof(T2), typeof(T3) }, cb); } /// <summary> /// Perform a multi-poco query /// </summary> /// <typeparam name="T1">The first POCO type</typeparam> /// <typeparam name="T2">The second POCO type</typeparam> /// <typeparam name="T3">The third POCO type</typeparam> /// <typeparam name="T4">The forth POCO type</typeparam> /// <typeparam name="TRet">The type of objects in the returned IEnumerable</typeparam> /// <param name="cb">A callback function to connect the POCO instances, or null to automatically guess the relationships</param> /// <returns>A collection of POCOs as an IEnumerable</returns> public IEnumerable<TRet> Read<T1, T2, T3, T4, TRet>(Func<T1, T2, T3, T4, TRet> cb) { return MultiPocoFromIDataReader<TRet>(_gridIndex, new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }, cb); } #endregion #region PocoFromIDataReader /// <summary> /// Read data to a single poco /// </summary> /// <typeparam name="T">The type representing a row in the result set</typeparam> /// <param name="index">Reader row to be read from the underlying IDataReader</param> /// <returns></returns> private IEnumerable<T> SinglePocoFromIDataReader<T>(int index) { if (_reader == null) throw new ObjectDisposedException(GetType().FullName, "The data reader has been disposed"); if (_consumed) throw new InvalidOperationException("Query results must be consumed in the correct order, and each result can only be consumed once"); _consumed = true; var pd = PocoData.ForType(typeof(T), _defaultMapper); try { while (index == _gridIndex) { var factory = pd.GetFactory(_command.CommandText, _command.Connection.ConnectionString, 0, _reader.FieldCount, _reader, _defaultMapper) as Func<IDataReader, T>; while (true) { T poco; try { if (!_reader.Read()) yield break; poco = factory(_reader); } catch (Exception x) { if (_db.OnException(x)) throw; yield break; } yield return poco; } } } finally // finally so that First etc progresses things even when multiple rows { if (index == _gridIndex) { NextResult(); } } } /// <summary> /// Read data to multiple POCOs /// </summary> /// <typeparam name="TRet">The type of objects in the returned IEnumerable</typeparam> /// <param name="index">Reader row to be read from the underlying IDataReader</param> /// <param name="types">An array of Types representing the POCO types of the returned result set.</param> /// <param name="cb">A callback function to connect the POCO instances, or null to automatically guess the relationships</param> /// <returns>A collection of POCOs as an IEnumerable</returns> private IEnumerable<TRet> MultiPocoFromIDataReader<TRet>(int index, Type[] types, object cb) { if (_reader == null) throw new ObjectDisposedException(GetType().FullName, "The data reader has been disposed"); if (_consumed) throw new InvalidOperationException("Query results must be consumed in the correct order, and each result can only be consumed once"); _consumed = true; try { var cmd = _command; var r = _reader; var factory = MultiPocoFactory.GetFactory<TRet>(types, cmd.Connection.ConnectionString, cmd.CommandText, r, _defaultMapper); if (cb == null) cb = MultiPocoFactory.GetAutoMapper(types.ToArray()); bool bNeedTerminator = false; while (true) { TRet poco; try { if (!r.Read()) break; poco = factory(r, cb); } catch (Exception x) { if (_db.OnException(x)) throw; yield break; } if (poco != null) yield return poco; else bNeedTerminator = true; } if (bNeedTerminator) { var poco = (TRet) (cb as Delegate).DynamicInvoke(new object[types.Length]); if (poco != null) yield return poco; else yield break; } } finally { if (index == _gridIndex) { NextResult(); } } } #endregion #region DataReader Management private int _gridIndex; private bool _consumed; /// <summary> /// Advance the IDataReader to the NextResult, if available /// </summary> private void NextResult() { if (!_reader.NextResult()) return; _gridIndex++; _consumed = false; } /// <summary> /// Dispose the grid, closing and disposing the underlying reader, command, and shared connection /// </summary> public void Dispose() { if (_reader != null) { if (!_reader.IsClosed && _command != null) _command.Cancel(); _reader.Dispose(); _reader = null; } if (_command != null) { _command.Dispose(); _command = null; } _db.CloseSharedConnection(); } #endregion } }
d00898130762f082e4b9c9c29538e249b75881f1
C#
ldl2/C-
/week1/Human2/Wizard.cs
3.46875
3
using System; using System.Collections.Generic; namespace Human { public class Wizard : Human { public Wizard(string _name) : base(_name) { intelligence = 25; health = 50; name = _name; } public void Heal() { this.health += 10 * this.intelligence; if (this.health > 50) { this.health = 50; } } public void fireball(object thing) { Random num = new Random(); int flame = num.Next(20,50); Human enemey = thing as Human; if(enemey == null) { Console.WriteLine("Failed Attack"); } else { enemey.health -= flame; } } } }
31764ee2a1c64cc3d73fe73f1668ab68709d012a
C#
destroyer0fWorlds/TypeSearch
/TypeSearch.Tests/BoolTests.cs
2.671875
3
using System.Linq; using System.Collections.Generic; using Xunit; using TypeSearch.Tests.Mocks; namespace TypeSearch.Tests { public class BoolTests { [Fact] public void Bool_IsEqualTo_Search() { // Arrange var testCollection = new List<TestEntity>() { new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true } }; // Act var searchDefinition = new SearchDefinition<TestEntity>(); searchDefinition.Filter .Where(i => i.BoolProperty).IsEqualTo(true); var searchResults = new Searcher<TestEntity>(testCollection.AsQueryable()) .Search(searchDefinition); var expectedResults = testCollection.Where(i => i.BoolProperty == true); // Assert Assert.NotNull(searchResults.ResultSet); Assert.Equal(expectedResults.Count(), searchResults.ResultSet.Count); Assert.Equal(expectedResults.Count(), searchResults.FilteredRecordCount); } [Fact] public void Bool_IsNotEqualTo_Search() { // Arrange var testCollection = new List<TestEntity>() { new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true } }; // Act var searchDefinition = new SearchDefinition<TestEntity>(); searchDefinition.Filter .Where(i => i.BoolProperty).IsNotEqualTo(true); var searchResults = new Searcher<TestEntity>(testCollection.AsQueryable()) .Search(searchDefinition); var expectedResults = testCollection.Where(i => i.BoolProperty != true); // Assert Assert.NotNull(searchResults.ResultSet); Assert.Equal(expectedResults.Count(), searchResults.ResultSet.Count); Assert.Equal(expectedResults.Count(), searchResults.FilteredRecordCount); } [Fact] public void Bool_In_Search() { // Arrange var testCollection = new List<TestEntity>() { new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true } }; // Act var searchDefinition = new SearchDefinition<TestEntity>(); searchDefinition.Filter .Where(i => i.BoolProperty).In(true); var searchResults = new Searcher<TestEntity>(testCollection.AsQueryable()) .Search(searchDefinition); var expectedResults = testCollection.Where(i => new bool[] { true }.Contains(i.BoolProperty)); // Assert Assert.NotNull(searchResults.ResultSet); Assert.Equal(expectedResults.Count(), searchResults.ResultSet.Count); Assert.Equal(expectedResults.Count(), searchResults.FilteredRecordCount); } [Fact] public void Bool_NotIn_Search() { // Arrange var testCollection = new List<TestEntity>() { new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true } }; // Act var searchDefinition = new SearchDefinition<TestEntity>(); searchDefinition.Filter .Where(i => i.BoolProperty).NotIn(true); var searchResults = new Searcher<TestEntity>(testCollection.AsQueryable()) .Search(searchDefinition); var expectedResults = testCollection.Where(i => !(new bool[] { true }.Contains(i.BoolProperty))); // Assert Assert.NotNull(searchResults.ResultSet); Assert.Equal(expectedResults.Count(), searchResults.ResultSet.Count); Assert.Equal(expectedResults.Count(), searchResults.FilteredRecordCount); } [Fact] public void Bool_IsTrue_Search() { // Arrange var testCollection = new List<TestEntity>() { new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true } }; // Act var searchDefinition = new SearchDefinition<TestEntity>(); searchDefinition.Filter .Where(i => i.BoolProperty).IsTrue(); var searchResults = new Searcher<TestEntity>(testCollection.AsQueryable()) .Search(searchDefinition); var expectedResults = testCollection.Where(i => i.BoolProperty); // Assert Assert.NotNull(searchResults.ResultSet); Assert.Equal(expectedResults.Count(), searchResults.ResultSet.Count); Assert.Equal(expectedResults.Count(), searchResults.FilteredRecordCount); } [Fact] public void Bool_IsFalse_Search() { // Arrange var testCollection = new List<TestEntity>() { new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true } }; // Act var searchDefinition = new SearchDefinition<TestEntity>(); searchDefinition.Filter .Where(i => i.BoolProperty).IsFalse(); var searchResults = new Searcher<TestEntity>(testCollection.AsQueryable()) .Search(searchDefinition); var expectedResults = testCollection.Where(i => !i.BoolProperty); // Assert Assert.NotNull(searchResults.ResultSet); Assert.Equal(expectedResults.Count(), searchResults.ResultSet.Count); Assert.Equal(expectedResults.Count(), searchResults.FilteredRecordCount); } [Fact] public void Bool_Contains_Search() { // Arrange var testCollection = new List<TestEntity>() { new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true } }; // Act var searchDefinition = new SearchDefinition<TestEntity>(); searchDefinition.Filter .Where(i => i.BoolProperty).Contains("ru"); var searchResults = new Searcher<TestEntity>(testCollection.AsQueryable()) .Search(searchDefinition); var expectedResults = testCollection.Where(i => i.BoolProperty.ToString().Contains("ru")); // Assert Assert.NotNull(searchResults.ResultSet); Assert.Equal(expectedResults.Count(), searchResults.ResultSet.Count); Assert.Equal(expectedResults.Count(), searchResults.FilteredRecordCount); } [Fact] public void Bool_DoesNotContain_Search() { // Arrange var testCollection = new List<TestEntity>() { new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true } }; // Act var searchDefinition = new SearchDefinition<TestEntity>(); searchDefinition.Filter .Where(i => i.BoolProperty).DoesNotContain("ru"); var searchResults = new Searcher<TestEntity>(testCollection.AsQueryable()) .Search(searchDefinition); var expectedResults = testCollection.Where(i => !i.BoolProperty.ToString().Contains("ru")); // Assert Assert.NotNull(searchResults.ResultSet); Assert.Equal(expectedResults.Count(), searchResults.ResultSet.Count); Assert.Equal(expectedResults.Count(), searchResults.FilteredRecordCount); } [Fact] public void Bool_StartsWith_Search() { // Arrange var testCollection = new List<TestEntity>() { new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true } }; // Act var searchDefinition = new SearchDefinition<TestEntity>(); searchDefinition.Filter .Where(i => i.BoolProperty).StartsWith("t"); var searchResults = new Searcher<TestEntity>(testCollection.AsQueryable()) .Search(searchDefinition); var expectedResults = testCollection.Where(i => i.BoolProperty.ToString().StartsWith("t")); // Assert Assert.NotNull(searchResults.ResultSet); Assert.Equal(expectedResults.Count(), searchResults.ResultSet.Count); Assert.Equal(expectedResults.Count(), searchResults.FilteredRecordCount); } [Fact] public void Bool_DoesNotStartWith_Search() { // Arrange var testCollection = new List<TestEntity>() { new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true } }; // Act var searchDefinition = new SearchDefinition<TestEntity>(); searchDefinition.Filter .Where(i => i.BoolProperty).DoesNotStartWith("t"); var searchResults = new Searcher<TestEntity>(testCollection.AsQueryable()) .Search(searchDefinition); var expectedResults = testCollection.Where(i => !i.BoolProperty.ToString().StartsWith("t")); // Assert Assert.NotNull(searchResults.ResultSet); Assert.Equal(expectedResults.Count(), searchResults.ResultSet.Count); Assert.Equal(expectedResults.Count(), searchResults.FilteredRecordCount); } [Fact] public void Bool_EndsWith_Search() { // Arrange var testCollection = new List<TestEntity>() { new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true } }; // Act var searchDefinition = new SearchDefinition<TestEntity>(); searchDefinition.Filter .Where(i => i.BoolProperty).EndsWith("ue"); var searchResults = new Searcher<TestEntity>(testCollection.AsQueryable()) .Search(searchDefinition); var expectedResults = testCollection.Where(i => i.BoolProperty.ToString().EndsWith("ue")); // Assert Assert.NotNull(searchResults.ResultSet); Assert.Equal(expectedResults.Count(), searchResults.ResultSet.Count); Assert.Equal(expectedResults.Count(), searchResults.FilteredRecordCount); } [Fact] public void Bool_DoesNotEndWith_Search() { // Arrange var testCollection = new List<TestEntity>() { new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true }, new TestEntity() { BoolProperty = false }, new TestEntity() { BoolProperty = true } }; // Act var searchDefinition = new SearchDefinition<TestEntity>(); searchDefinition.Filter .Where(i => i.BoolProperty).DoesNotEndWith("ue"); var searchResults = new Searcher<TestEntity>(testCollection.AsQueryable()) .Search(searchDefinition); var expectedResults = testCollection.Where(i => !i.BoolProperty.ToString().EndsWith("ue")); // Assert Assert.NotNull(searchResults.ResultSet); Assert.Equal(expectedResults.Count(), searchResults.ResultSet.Count); Assert.Equal(expectedResults.Count(), searchResults.FilteredRecordCount); } } }
825b71bed5098121681880d4316a23e42601cc8c
C#
mwpowellhtx/Kingdom.Protobuf
/src/Kingdom.Protobuf.Descriptors/Strategies/IDescriptorVisitor.cs
2.5625
3
// ReSharper disable once IdentifierTypo namespace Kingdom.Protobuf { /// <summary> /// Represents a <typeparamref name="T"/> <see cref="IDescriptor"/> Visitor pattern. /// </summary> /// <typeparam name="T"></typeparam> public interface IDescriptorVisitor<in T> where T : IDescriptor { /// <summary> /// Visits the <paramref name="descriptor"/>. /// </summary> /// <param name="descriptor"></param> void Visit(T descriptor); } /// <inheritdoc /> /// <summary> /// Represents an <see cref="T:Kingdom.OrTools.Sat.IDescriptorVisitor`1" /> with a <typeparamref name="TResult" />. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TResult"></typeparam> public interface IDescriptorVisitor<in T, out TResult> : IDescriptorVisitor<T> where T : IDescriptor { /// <summary> /// Gets the <typeparamref name="TResult"/> after visitation. /// </summary> TResult Result { get; } /// <summary> /// Visits the <paramref name="descriptor"/> With the <typeparamref name="TResult"/>. /// </summary> /// <param name="descriptor"></param> /// <returns></returns> TResult VisitWithResult(T descriptor); } }
90dd69b5a71366de5d06c521b4a3ac3515d5c2b1
C#
clethbridge/EntityQueryLanguage
/EntityQueryLanguage.Components/Models/EntityType.cs
2.84375
3
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace EntityQueryLanguage.Components.Models { [DebuggerDisplay("{EntityKey}")] public class EntityType { /// <summary> /// A unique key used to identify and map the subject Entity Type to a database object. /// </summary> public string EntityKey { get; set; } /// <summary> /// The name of this object in the database /// </summary> public string DatabaseName { get; set; } public bool CanInsert { get; set; } public bool CanUpdate { get; set; } public bool CanDelete { get; set; } /// <summary> /// A collection of fields that correspond to the columns of this object within the database. /// </summary> public List<EntityField> EntityFields { get; set; } = new List<EntityField>(); /// <summary> /// Returns the specified field from the subject entity. /// </summary> public EntityField GetEntityField(string termKey) => EntityFields.FirstOrDefault(f => f.TermKey == termKey); public EntityField PrimaryKey => EntityFields.FirstOrDefault(f => f.IsPrimaryKey); /// <summary> /// The set of fields that can not be null for the subject entity . /// </summary> public List<EntityField> RequiredFields => EntityFields.Where(f => !f.IsNullable).ToList(); /// <summary> /// The set of unqiue term keys for each field belonging to the subject entity. /// </summary> public List<string> TermKeys => EntityFields.Select(f => f.TermKey).ToList(); } }
088a087bfdea927d1cfbccc4606f8eb5ac11969c
C#
michal-kindl/generate-diagrams-from-source-code
/ClassDiagramGenerator.cs
3.015625
3
using System; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.IO; // ClassDiagramGenerator from https://github.com/pierre3/PlantUmlClassDiagramGenerator namespace Diagrams { /// <summary> /// Class to generate PlantUML class diagram from C # source code /// </summary> public class ClassDiagramGenerator : CSharpSyntaxWalker { private TextWriter writer; private string indent; private int nestingDepth = 0; private bool showMethodParameterTypes = true; private bool showMethodParameters = true; /// <summary> /// Constructor /// </summary> /// <param name="writer">TextWriter to output the result</param> /// <param name="indent">String to be used as indent</param> public ClassDiagramGenerator(TextWriter writer, string indent, bool showMethodParameters, bool showMethodParameterTypes) { this.writer = writer; this.indent = indent; this.showMethodParameters = showMethodParameters; this.showMethodParameterTypes = showMethodParameterTypes; } /// <summary> /// Output interface definition in PlantUML format /// </summary> public override void VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) { VisitTypeDeclaration(node, () => base.VisitInterfaceDeclaration(node)); } /// <summary> /// Output definition of class in PlantUML format /// </summary> public override void VisitClassDeclaration(ClassDeclarationSyntax node) { VisitTypeDeclaration(node, () => base.VisitClassDeclaration(node)); } /// <summary> /// Output the structure definition in PlantUML format /// </summary> public override void VisitStructDeclaration(StructDeclarationSyntax node) { var name = node.Identifier.ToString(); var typeParam = node.TypeParameterList?.ToString() ?? ""; WriteLine($"class **{name}{typeParam}** <<struct>> {{"); nestingDepth++; base.VisitStructDeclaration(node); nestingDepth--; WriteLine("}"); } /// <summary> /// Output definition of enum type in PlantUML format /// </summary> /// <param name="node"></param> public override void VisitEnumDeclaration(EnumDeclarationSyntax node) { WriteLine($"{node.EnumKeyword} **{node.Identifier}** {{"); nestingDepth++; base.VisitEnumDeclaration(node); nestingDepth--; WriteLine("}"); } /// <summary> /// Output definition of type (class, interface, structure) in PlantUML format /// </summary> private void VisitTypeDeclaration(TypeDeclarationSyntax node, Action visitBase) { var modifiers = GetTypeModifiersText(node.Modifiers); var keyword = (node.Modifiers.Any(SyntaxKind.AbstractKeyword) ? "abstract " : "") + node.Keyword.ToString(); var name = node.Identifier.ToString(); var typeParam = node.TypeParameterList?.ToString() ?? ""; WriteLine($"{keyword} **{name}{typeParam}** {modifiers}{{"); nestingDepth++; visitBase(); nestingDepth--; WriteLine("}"); if (node.BaseList != null) { foreach (var b in node.BaseList.Types) { var nodeBaseType = b.Type.ToFullString(); var shortNodeBaseType = nodeBaseType.Split('<').First(); if (nodeBaseType.Contains("<")) { WriteLine($"class \"{shortNodeBaseType}\" as {nodeBaseType}\n"); } WriteLine($"{name} <|-- {shortNodeBaseType}"); } } } public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { var modifiers = GetMemberModifiersText(node.Modifiers); var name = node.Identifier.ToString(); var args = showMethodParameters ? node.ParameterList.Parameters.Select(p => showMethodParameterTypes ? $"{p.Identifier}:{p.Type}" : $"{p.Identifier}") : new string[] { }; //var args = node.ParameterList.Parameters.Select(p => $"{p.Identifier}:{p.Type}"); WriteLine($"{modifiers}**{name}**({string.Join(", ", args)})"); } /// <summary> /// Output field definition /// </summary> public override void VisitFieldDeclaration(FieldDeclarationSyntax node) { var modifiers = GetMemberModifiersText(node.Modifiers); var typeName = node.Declaration.Type.ToString(); var variables = node.Declaration.Variables; foreach (var field in variables) { var useLiteralInit = field.Initializer?.Value?.Kind().ToString().EndsWith("LiteralExpression") ?? false; var initValue = "";// useLiteralInit ? (" = " + field.Initializer.Value.ToString()) : ""; WriteLine($"{modifiers}{field.Identifier} : {typeName}{initValue}"); } } /// <summary> /// Output property definition /// </summary> public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) { var modifiers = GetMemberModifiersText(node.Modifiers); var name = node.Identifier.ToString(); var typeName = node.Type.ToString(); var accessor = node.AccessorList.Accessors .Where(x => !x.Modifiers.Select(y => y.Kind()).Contains(SyntaxKind.PrivateKeyword)) .Select(x => $"<<{(x.Modifiers.ToString() == "" ? "" : (x.Modifiers.ToString() + " "))}{x.Keyword}>>"); var useLiteralInit = node.Initializer?.Value?.Kind().ToString().EndsWith("LiteralExpression") ?? false; var initValue = useLiteralInit ? (" = " + node.Initializer.Value.ToString()) : ""; WriteLine($"{modifiers}**{name}**: {typeName} {string.Join(" ", accessor)}{initValue}"); } /// <summary> /// Output method definition /// </summary> public override void VisitMethodDeclaration(MethodDeclarationSyntax node) { var modifiers = GetMemberModifiersText(node.Modifiers); var name = node.Identifier.ToString(); var returnType = node.ReturnType.ToString(); var args = showMethodParameters ? node.ParameterList.Parameters.Select(p => showMethodParameterTypes ? $"{p.Identifier}:{p.Type}" : $"{p.Identifier}") : new string[] { }; //var args = node.ParameterList.Parameters.Select(p => $"{p.Identifier}:{p.Type}"); WriteLine($"{modifiers}**{name}**({string.Join(", ", args)}) : {returnType}"); } /// <summary> /// Output enum type members /// </summary> /// <param name="node"></param> public override void VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) { WriteLine($"{node.Identifier}{node.EqualsValue},"); } /// <summary> /// Write one line to the result output TextWriter. /// </summary> private void WriteLine(string line) { //Append indentation to the beginning of the line by the nesting level var space = string.Concat(Enumerable.Repeat(indent, nestingDepth)); writer.WriteLine(space + line); } /// <summary> /// Convert qualifier of type (class, interface, structure) to a string /// </summary> /// <param name="modifiers">TokenList of the modifier</param> /// <returns>String after conversion</returns> private string GetTypeModifiersText(SyntaxTokenList modifiers) { var tokens = modifiers.Select(token => { switch (token.Kind()) { case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.AbstractKeyword: return ""; default: return $"<<{token.ValueText}>>"; } }).Where(token => token != ""); var result = string.Join(" ", tokens); if (result != string.Empty) { result += " "; }; return result; } /// <summary> /// Convert qualifier of type member to string /// </summary> /// <param name="modifiers">TokenList of the modifier</param> /// <returns></returns> private string GetMemberModifiersText(SyntaxTokenList modifiers) { var tokens = modifiers.Select(token => { switch (token.Kind()) { case SyntaxKind.PublicKeyword: return "+"; case SyntaxKind.PrivateKeyword: return "-"; case SyntaxKind.ProtectedKeyword: return "#"; case SyntaxKind.AbstractKeyword: case SyntaxKind.StaticKeyword: return $"{{{token.ValueText}}}"; case SyntaxKind.InternalKeyword: default: return $"<<{token.ValueText}>>"; } }); var result = string.Join(" ", tokens); if (result != string.Empty) { result += " "; }; return result; } } }
1af5c5dad5ab5ffa647070c73cb275d47c6e2dc0
C#
AVPolyakov/SharpLayout
/SharpLayout/ReflectionUtil.cs
2.71875
3
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; namespace SharpLayout { public static class ReflectionUtil { private static readonly ConcurrentDictionary<MethodInfo, PropertyInfo> propertyDictionary = new ConcurrentDictionary<MethodInfo, PropertyInfo>(); private static readonly ConcurrentDictionary<Type, Dictionary<MethodBase, PropertyInfo>> propertyDictionaryByGetMethod = new ConcurrentDictionary<Type, Dictionary<MethodBase, PropertyInfo>>(); private static readonly ConcurrentDictionary<MethodInfo, FieldInfo> fieldDictionary = new ConcurrentDictionary<MethodInfo, FieldInfo>(); /// <summary> /// Получает <see cref="PropertyInfo"/> для свойства, которое используется в теле метода /// <paramref name="func"/>. Например, <c><![CDATA[GetProperyInfo<Message, string>(_ => _.Subject)]]></c>, /// возвращает <see cref="PropertyInfo"/> для свойства <c>Subject</c>. /// </summary> public static PropertyInfo GetProperyInfo<T, TPropery>(Func<T, TPropery> func) { var methodInfo = func.Method; if (propertyDictionary.TryGetValue(methodInfo, out var value)) return value; var tuples = IlReader.Read(methodInfo).ToList(); if (!tuples.Select(_ => _.Item1).SequenceEqual(new[] {OpCodes.Ldarg_1, OpCodes.Callvirt, OpCodes.Ret})) throw new ArgumentException($"The {nameof(func)} must encapsulate a method with a body that " + "consists of a sequence of intermediate language instructions " + $"{nameof(OpCodes.Ldarg_1)}, {nameof(OpCodes.Callvirt)}, {nameof(OpCodes.Ret)}.", nameof(func)); return ResolveProperty(methodInfo, tuples[1].Item2.Value); } /// <summary> /// Получает <see cref="MemberInfo"/> для свойства или поля, которое используется /// в теле метода <paramref name="func"/>. Например, /// <c><![CDATA[GetMemberInfo<string>(() => MyResources.Subject)]]></c>, /// возвращает <see cref="MemberInfo"/> для свойства <c>Subject</c>. /// </summary> public static MemberInfo GetMemberInfo<TPropery>(Func<TPropery> func) { var methodInfo = func.Method; if (propertyDictionary.TryGetValue(methodInfo, out var value)) return value; var tuples = IlReader.Read(methodInfo).ToList(); var codes = tuples.Select(_ => _.Item1).ToList(); if (codes.SequenceEqual(new[] {OpCodes.Call, OpCodes.Ret})) return ResolveProperty(methodInfo, tuples[0].Item2.Value); else if (codes.SequenceEqual(new[] {OpCodes.Ldarg_0, OpCodes.Ldfld, OpCodes.Ret})) return ResolveField(methodInfo, tuples[1].Item2.Value); else if (codes.SequenceEqual(new[] { OpCodes.Ldarg_0, OpCodes.Ldfld, OpCodes.Callvirt, OpCodes.Ret})) return ResolveProperty(methodInfo, tuples[2].Item2.Value); else throw new ArgumentException($"The {nameof(func)} must encapsulate a method with a body that " + "consists of a sequence of intermediate language instructions " + $"{nameof(OpCodes.Call)}, {nameof(OpCodes.Ret)} or " + $"{nameof(OpCodes.Ldarg_0)}, {nameof(OpCodes.Ldfld)}, {nameof(OpCodes.Ret)}.", nameof(func)); } private static PropertyInfo ResolveProperty(MethodInfo methodInfo, int metadataToken) { var methodBase = methodInfo.Module.ResolveMethod(metadataToken, methodInfo.DeclaringType.GetGenericArguments(), null); if (!propertyDictionaryByGetMethod.TryGetValue(methodBase.DeclaringType, out var infos)) { infos = methodBase.DeclaringType.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) .ToDictionary(_ => { MethodBase method = _.GetGetMethod(true); return method; }); propertyDictionaryByGetMethod.TryAdd(methodBase.DeclaringType, infos); } var propertyInfo = infos[methodBase]; propertyDictionary.TryAdd(methodInfo, propertyInfo); return propertyInfo; } private static MemberInfo ResolveField(MethodInfo methodInfo, int metadataToken) { var fieldInfo = methodInfo.Module.ResolveField(metadataToken, methodInfo.DeclaringType.GetGenericArguments(), null); fieldDictionary.TryAdd(methodInfo, fieldInfo); return fieldInfo; } } }
b3be668c3d5a984ae1a71a9f494595d16e036940
C#
NesQ1kx/Drocsid
/Dal/ForumDao.cs
2.59375
3
using DalContracts; using Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dal { public class ForumDao : IForumDao { public List<Topic> GetForIndex() { List<Topic> topics; using (var db = new SampleContext()) { return topics = db.Topics.OrderByDescending(t => t.Pubdate).Take(5).ToList(); } } public Topic GetTopic(int id) { Topic topic; using(var db = new SampleContext()) { return topic = db.Topics.Find(id); } } public List<Comment> GetComments(int id) { List<Comment> comments; using(var db = new SampleContext()) { return comments = db.Comments.Where(c => c.TopicId == id).ToList(); } } public List<Section> GetSections() { List<Section> sections; using(var db = new SampleContext()) { sections = db.Sections.ToList(); } return sections; } public List<Topic> GetTopicsShort(int id) { List<Topic> topics; using (var db = new SampleContext()) { return topics = db.Topics.Where(t => t.SectionId == id).Take(3).ToList(); } } public List<Topic> GetAllTopics(int id) { List<Topic> topics; using (var db = new SampleContext()) { return topics = db.Topics.Where(t => t.SectionId == id).ToList(); } } public void AddComment(Comment comment) { using (var db = new SampleContext()) { db.Comments.Add(comment); db.SaveChanges(); } } public void AddTopic(Topic topic) { using (var db = new SampleContext()) { db.Topics.Add(topic); db.SaveChanges(); } } public User GetUser(int id) { User user; using (var db = new SampleContext()) { return user = db.Users.Find(id); } } public void UpdateMessages(int id) { User user; using (var db = new SampleContext()) { user = db.Users.Find(id); user.Messages += 1; db.SaveChanges(); } } public List<Topic> GetTopics() { List<Topic> topics; using (var db = new SampleContext()) { return topics = db.Topics.ToList(); } } public Section GetSection(int id) { Section section; using (var db = new SampleContext()) { return section = db.Sections.Find(id); } } public void DeleteTopic(int id) { using (var db = new SampleContext()) { Topic topic = db.Topics.Find(id); List<Comment> comments = db.Comments.Where(c => c.TopicId == id).ToList(); foreach(var c in comments) { db.Comments.Remove(c); } db.Topics.Remove(topic); db.SaveChanges(); } } public void DeleteComment(int id) { using (var db = new SampleContext()) { Comment comment = db.Comments.Find(id); db.Comments.Remove(comment); db.SaveChanges(); } } public void AddSection(Section section) { using (var db = new SampleContext()) { db.Sections.Add(section); db.SaveChanges(); } } } }
d39468da9ddda60e3cb523a757ab5609c974642e
C#
maolen/Profile
/Services/AuthService.cs
2.890625
3
using Domain; using Profile.DataAccess; using Services.Abstract; using System.Linq; using System.Text.RegularExpressions; namespace Profile.Services { public class AuthService : IAuth { private readonly Context context; private BcryptHasher bcryptHasher = new BcryptHasher(); public AuthService(Context context) { this.context = context; } public bool IsValidEmail(string email) { string emailFormat = @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$"; return Regex.IsMatch(email, emailFormat); } private bool Authentication(string email) { if (context.Users.SingleOrDefault(x => x.Email == email) is null) { return false; } return true; } public bool SignUp(string fullName, string email, string password) { if (Authentication(email) || !IsValidEmail(email)) return false; var user = new User { Email = email, Password = bcryptHasher.EncryptPassword(password), FullName = fullName }; context.Add(user); context.SaveChanges(); return true; } public User SignIn(string email, string password) { var user = context.Users.FirstOrDefault(x => x.Email == email); if (user is null || !BCrypt.Net.BCrypt.Verify(password, user.Password)) return null; return user; } } }
be5ec2f051a3dd17e775f1066987fea3bb8d4c4c
C#
rinavin/RCJS
/CefSharp.MinimalExample-master/magic/Sources/RichClientDotNet/Controls/com/magicsoftware/Editors/TreeEditor.cs
2.890625
3
using System; using System.Collections.Generic; using System.Text; using com.magicsoftware.controls; using System.Windows.Forms; using System.Drawing; namespace com.magicsoftware.editors { /// <summary> /// implement editor for tree /// </summary> public class TreeEditor : Editor { private TreeNode node; public TreeEditor(TreeView treeView, TreeNode node) : base(treeView) { Node = node; } void TreeView_Layout(object sender, LayoutEventArgs e) { Layout(); } /// <summary> /// set node to editor /// </summary> public TreeNode Node { get { return node; } set { if (node != null) node.TreeView.Layout -= TreeView_Layout; this.node = value; if (node != null) node.TreeView.Layout += TreeView_Layout; } } /// <summary> /// hide editor /// </summary> public override void Hide() { Node = null; base.Hide(); } /// <summary> /// return true if comtrol is hidden /// </summary> /// <returns></returns> public override bool isHidden() { return node == null; } /// <summary> /// calculate editor bounds /// </summary> /// <returns></returns> public override Rectangle Bounds() { Rectangle rect = node.Bounds; rect.Width = parentControl.ClientRectangle.Width - rect.X; rect.Height = ((TreeView)parentControl).ItemHeight + SystemInformation.BorderSize.Height * 2; return rect; } } }
b8a7c635a3cd3176940538a22a1df0babed4a702
C#
nehachauhan14/blog-api
/BloggerApp/Controllers/BloggerController.cs
2.765625
3
using BlogsDataAccess; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace BloggerApp.Controllers { public class BloggerController : ApiController { [HttpGet] public HttpResponseMessage GetBlogersList() { using (BloggerAppDBEntities entities = new BloggerAppDBEntities()) { return Request.CreateResponse(HttpStatusCode.OK, entities.User_Details.ToList()); } } /// <summary> /// need to change this API to handle error or duplicate Uname isssue /// </summary> /// <param name="newUser"></param> /// <returns></returns> [AllowAnonymous] [HttpPost] [Route("api/Blogger/RegisterUser")] public HttpResponseMessage RegisterUser([FromBody] User_Details newUser) { try { using (BloggerAppDBEntities entities = new BloggerAppDBEntities()) { var user = entities.User_Details.FirstOrDefault(d => d.UserName == newUser.UserName); if (user == null) { entities.User_Details.Add(newUser); entities.SaveChanges(); var message = Request.CreateResponse(HttpStatusCode.Created, newUser); message.Headers.Location = new Uri(Request.RequestUri + newUser.UserName.ToString()); return message; } else { var message = Request.CreateResponse(HttpStatusCode.Conflict, "User already exists!"); return message; } } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex); } } } }
32c13be82bf50fec4b7652fbdc981e008e322a49
C#
bmegana/sdgamejam2019
/JourneyToTheHorizon/Assets/Scripts/GatherWater.cs
2.546875
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GatherWater : MonoBehaviour { bool bHaveWater = false; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if ( Input.GetAxis( "Submit" ) > 0 ) { RaycastHit hit; if ( Physics.SphereCast( transform.position, 0.5f, transform.forward, out hit, maxDistance:1.0f ) ) { if ( hit.collider.gameObject.tag == "Water" ) { Debug.Log( "Found Water!" ); } } } } }
71322103faf7475a94678504496fd7d0ae590d1e
C#
co185057/MeijerTESTSVN
/Meijer/Platform-Core-Patch/LaunchPadNet/Executable.cs
2.640625
3
using System; using System.ComponentModel; using System.Diagnostics; using System.Threading; using System.Text ; using System.Collections; using RPSWNET; using CommonLibsNet; namespace LaunchPadNet { /// <summary> /// Summary description for Executable. /// </summary> public class Executable { /// <summary> /// Executable constructor. /// </summary> public Executable( String sExecutableName) { executableName = sExecutableName; } /// <summary> /// Get the executable name. /// </summary> public String ExecutableName { get { return executableName; } } /// <summary> /// Get/Set the executable window title string - use for traversing windows. /// </summary> public String WindowTitle { get { return windowTitle; } set { windowTitle = value; } } /// <summary> /// Get/Set the maximize flag. /// </summary> public bool Maximize { get { return maximize; } set { maximize = value; } } /// <summary> /// Get/Set the minimize at start indicator. Used to get rid of DOS boxes and "ScotInputWindow". /// </summary> public bool MinimizeStart { get { return minimizeStart; } set { minimizeStart = value; } } /// <summary> /// Get/Set the main executable filename. /// </summary> public String Filename { get { return filename; } set { filename = value; } } /// <summary> /// Get/Set the main executable path. /// </summary> public String Path { get { return path; } set { path = value; } } /// <summary> /// Get/Set the executable arguments. /// </summary> public String Arguments { get { return arguments; } set { arguments = value; } } /// <summary> /// Get/Set the windows window that is sent the stop message number. /// </summary> public String StopWindow { get { return stopWindow; } set { stopWindow = value; } } /// <summary> /// Get/Set the windows message number is sent to the stop message window. /// </summary> public uint StopUserMessage { get { return stopUserMessage; } set { stopUserMessage = value; } } /// <summary> /// Return the executable name. /// </summary> public override String ToString () { return ExecutableName ; } /// <summary> /// Get/Set the main executable indicator. /// </summary> public bool IsMainExecutable { get { return isMainExecutable ; } set { isMainExecutable = value; } } /// <summary> /// Get/Set the windows Process. /// </summary> public Process LocalProcess { get { return localProcess; } set { localProcess = value; } } /// <summary> /// Get/Set the FunctionProcess array. /// </summary> public ArrayList FunctionProcessor { get { return m_functionProcessor; } set { m_functionProcessor = value; } } /// <summary> /// Callback-Loop to check if executable is minimized. If so, restore to normal size. /// </summary> private void CheckMinimize() { while(LocalProcess != null && !LocalProcess.HasExited ) { try { PInvoke.EnumWindowsCallBack EnumWindowsFunc = new PInvoke.EnumWindowsCallBack(RestoreToNormalIfMinimize ); PlatformEnumWindows(EnumWindowsFunc, 0 ); } catch ( Exception e ) { CmDataCapture.Capture( CmDataCapture.MaskError, String.Format("<Exception> [RestoreToNormalIfMinimize()] new Delegate: {0}", e.Message )); } Thread.Sleep(500); } } /// <summary> /// Does the executable have a window. /// </summary> private bool IsAWindow() { if (WindowTitle != null && !WindowTitle.Trim().Equals("") ) return true; else return false; } /// <summary> /// Start the executable callback. /// </summary> private bool Start() { bool retVal = true; // Some executable files (such as ADD.BAT) should only run once even if starting/stopping // the lane software. Thus, if this executable file should only run once and it has already // been run, do not run it again. Return a successful flag indicating things have been // processed as desired. if ( ExecuteOnlyOnce && HasBeenExecuted ) { return retVal; } else { // Now we have executed this application. HasBeenExecuted = true; } Stop(); int processID = 0; Process[] foundProcesses = null; //No need to find Windowless executables try { if ( IsAWindow()) { //Get Possible Window Titles separated by commas from the config file String []windowTitles = WindowTitle.Split(','); for ( int count = 0;count<windowTitles.Length ;count++) { IntPtr hWnd = PInvoke.FindWindow(null,windowTitles[count]); if( hWnd != IntPtr.Zero) { #if ( !WINCE ) WindowTitle = windowTitles[count]; #endif PInvoke.GetWindowThreadProcessId( hWnd, out processID); //get First process, and use ProcessName property to get all Windows running Process firstProcess = Process.GetProcessById(processID); LocalProcess = firstProcess; if ( firstProcess != null) { foundProcesses = Process.GetProcessesByName(firstProcess.ProcessName); } break; } } //close all open windows if( foundProcesses != null) { foreach(Process nextProcess in foundProcesses) { nextProcess.CloseMainWindow(); } } } } catch(Exception ex) { CmDataCapture.Capture( CmDataCapture.MaskError, String.Format("<Exception> [Executable.startProcess()] Error finding processes: {0}", ex.Message )); } try { //Since there might be some arguments included, just start a new process CmDataCapture.Capture( CmDataCapture.MaskError, String.Format("[Executable.Start()] - Starting {0}", Filename )); ProcessStartInfo startInfo = new ProcessStartInfo(Path + Filename); if( Arguments != null && !Arguments .Equals("") ) startInfo.Arguments = Arguments; // If the config file option to start minimized is true, then set the option before starting. if (MinimizeStart) { startInfo.WindowStyle = ProcessWindowStyle.Minimized; //Fix Tar#327968 //startInfo.WindowStyle = ProcessWindowStyle.Hidden; } Process process = new Process(); process.StartInfo = startInfo; process.Start(); LocalProcess = process; if (IsAWindow()) { try { process.WaitForInputIdle(); Thread.Sleep(1000); if (process.HasExited) { retVal = false; CmDataCapture.Capture( CmDataCapture.MaskError, String.Format("Executable::Start() [Executable.startProcess()] Error starting process: {0}", Path + Filename )); } } catch( Exception ex) { // This happens sometimes with batch files. It creates the following exception // "WaitForInputIdle failed. This could be because the process does not have a graphical interface." // Add this try/catch to miminize the side effects. CmDataCapture.Capture( CmDataCapture.MaskError, String.Format("<Exception> [Executable.startProcess()] Error WAITING for process: {0} - {1}", Path + Filename, ex.Message )); } #if ( WINCE ) #else if ( retVal && IsMainExecutable == false ) //allow minimize for main executable { Thread tMinimize = new Thread( new ThreadStart(CheckMinimize)); tMinimize.Start(); } #endif } // Let executable complete before continuing... if ( retVal && WaitForExit ) { CmDataCapture.Capture( CmDataCapture.MaskExtensive, String.Format("Let executable complete before continuing..." + ExecutableName )); if ( LocalProcess != null && !LocalProcess.HasExited ) { LocalProcess.WaitForExit(); } } } catch( Exception ex) { retVal = false; CmDataCapture.Capture( CmDataCapture.MaskError, String.Format("<Exception> [Executable.startProcess()] Error starting process: {0} - {1}", Path + Filename, ex.Message )); } return retVal; } /// <summary> /// Stop the executable. /// </summary> private void Stop() { try { if ( LocalProcess != null ) { if (LocalProcess.HasExited == false ) { int elapsedMS = 0; // Elapsed MilliSeconds to wait for a gentle shutdown... ConfigDataLaunchPad configData = ConfigDataLaunchPad.GetConfigData(); if ( ( this.IsMainExecutable ) && ( this.Filename.ToLower().IndexOf( "rapnet" ) >= 0 ) ) { CmDataCapture.Capture( CmDataCapture.MaskInfo, "Sending alternative Stop to RapNet via RemoteMessage" ); MyApplication.SendProcessMessage( ConfigDataLaunchPad.rapApplication, "operation=stop-app;" ); if ( configData.ShutDownTimeout > 15000 ) elapsedMS = configData.ShutDownTimeout - 15000; } // Request the process to close in a civil manner... //LocalProcess.CloseMainWindow(); UIntPtr wParam = UIntPtr.Zero; IntPtr lParam = IntPtr.Zero; IntPtr hWnd = IntPtr.Zero; uint message = PInvoke.WM_CLOSE; // If the config file overrides the process window title, use the user defined window. if (!StopWindow.Equals("")) { hWnd = PInvoke.FindWindow(null,StopWindow); } else { hWnd = LocalProcess.MainWindowHandle; } // If the config file overrides WM_CLOSE, use the User defined message. if ( StopUserMessage != 0) { message = PInvoke.WM_USER + stopUserMessage; } //if ( PInvoke.PostMessage( LocalProcess.MainWindowHandle, PInvoke.WM_USER + 101, wParam, lParam) ) if ( PInvoke.PostMessage(hWnd, message, wParam, lParam) ) { CmDataCapture.Capture( CmDataCapture.MaskInfo, "Stop() GENTLE: " + LocalProcess.ProcessName); while ( !LocalProcess.HasExited && elapsedMS < configData.ShutDownTimeout) // 15000 ms is 15 seconds { Thread.Sleep(100); elapsedMS += 100; } } // No more Mr. Nice guy! Shut em down... if ( !LocalProcess.HasExited ) { LocalProcess.Kill(); CmDataCapture.Capture( CmDataCapture.MaskInfo, "Stop() HARD: LocalProcess.Kill(): " + LocalProcess.ProcessName); } } } } catch(Exception ex) { CmDataCapture.Capture( CmDataCapture.MaskError, String.Format("<Exception> [Executable.Stop()] Exception stopping processes: {0}", ex.Message )); } LocalProcess = null; } /// <summary> /// Maximize the executable callback. /// </summary> private bool MaximizeWindows(IntPtr hWnd, int iProcessIndex) { if ( LocalProcess == null || LocalProcess.HasExited || !IsAWindow()) { return false; //stop enumeration } bool bNotFound = true; int processID = -1; PInvoke.GetWindowThreadProcessId( hWnd, out processID); if( processID == LocalProcess.Id ) { StringBuilder sbProcessText = new StringBuilder(256); PInvoke.GetWindowText( hWnd, sbProcessText, sbProcessText.Capacity); String []windowTitles = WindowTitle.Split(','); for ( int count = 0;count<windowTitles.Length ;count++) { if (sbProcessText.ToString().EndsWith(windowTitles[count]) ) { #if ( !WINCE ) WindowTitle = windowTitles[count]; #endif IntPtr hParentWnd = IntPtr.Zero; // In the scotapp assist mode, sometimes the POS solution window is displayed on top // of the regular scotapp window. If that happens, and the keylock button is pressed // the customer will want to return to the POS window on the next button press. Save // the handle of that window so that the window can be redisplayed on the next button press. // After the button is pressed, restore the window pointer to zero. if (ForegroundWindowHandle != IntPtr.Zero) { hParentWnd = ForegroundWindowHandle; } else { hParentWnd = PInvoke.GetParent( hWnd ); } if( hParentWnd == IntPtr.Zero) hParentWnd = hWnd; PInvoke.WINDOWPLACEMENT winPlace = new PInvoke.WINDOWPLACEMENT(); winPlace.length = 44; bool bResult = false; #if ( !WINCE ) bResult = PInvoke.GetWindowPlacement( hParentWnd, out winPlace); #else // CE doesn't support GetWindowPlacement bResult = true; // We're not using these, just stop compile warnings PInvoke.POINT point = new PInvoke.POINT(); PInvoke.RECT rect = new PInvoke.RECT(); winPlace.flags = 0; winPlace.ptMinPosition = point; winPlace.ptMaxPosition = point; winPlace.rcNormalPosition = rect; // Default value winPlace.showCmd = ( uint )PInvoke.ShowWindowFlags.SW_MINIMIZE; #endif if((bResult) && (winPlace.showCmd != (uint)PInvoke.ShowWindowFlags.SW_SHOWMAXIMIZED ) ) { CmDataCapture.Capture( CmDataCapture.MaskError, String.Format("[Executable.Maximize()] Window[{0}] placement matched", sbProcessText.ToString() )); int nFlag; if( Maximize ) { nFlag = (int) PInvoke.ShowWindowFlags.SW_SHOWMAXIMIZED; } else { //restore normal window even if minimized nFlag = (int) PInvoke.ShowWindowFlags.SW_SHOWNORMAL; } PInvoke.ShowWindow(hParentWnd, nFlag); } IntPtr hWndInsertAfter = IntPtr.Zero; // If true, the executable window style be HWND_TOPMOST (if false HWND_TOP) hWndInsertAfter = (TopMost ? ((IntPtr) PInvoke.SetWindowPosInsertAfter.HWND_TOPMOST) :((IntPtr) PInvoke.SetWindowPosInsertAfter.HWND_TOP)); PInvoke.SetForegroundWindow(hParentWnd); // In the scotapp assist mode, sometimes the POS solution window is displayed on top // of the regular scotapp window. If that happens, and the keylock button is pressed // the customer will want to return to the POS window on the next button press. Save // the handle of that window so that the window can be redisplayed on the next button press. // After the button is pressed, restore the window pointer to zero. if (ForegroundWindowHandle != IntPtr.Zero) { int nFlag= (int) PInvoke.ShowWindowFlags.SW_SHOW; //SW_SHOWNORMAL; // SW_SHOWNA; PInvoke.ShowWindow( ForegroundWindowHandle, nFlag); CmDataCapture.Capture( CmDataCapture.MaskError, "Executable.MaximizeWindows(): ForegroundWindowTitle - ForegroundWindowHandle CLEAR=\'0\'"); ForegroundWindowHandle = IntPtr.Zero; break; } #if ( !WINCE ) PInvoke.SetWindowPos(hParentWnd,hWndInsertAfter,0,0,0,0,(uint)(PInvoke.SetWindowPosFlags.SWP_NOMOVE|PInvoke.SetWindowPosFlags.SWP_NOSIZE|PInvoke.SetWindowPosFlags.SWP_SHOWWINDOW)); #else int windowWidth = 240; int windowHeight = 320; int newXPosition = 0; int newYPosition = 0; PInvoke.SetWindowPos(hParentWnd,hWndInsertAfter,newXPosition,newYPosition,windowWidth,windowHeight,(uint)(PInvoke.SetWindowPosFlags.SWP_SHOWWINDOW)); #endif PInvoke.SetFocus(hParentWnd); bNotFound = false; break; } } } return bNotFound; } /// <summary> /// Minimize the executable callback. /// </summary> private bool MinimizeWindows(IntPtr hWnd, int iProcessIndex) { if ( LocalProcess == null || LocalProcess.HasExited || !IsAWindow()) { return false; //stop enumeration } bool bNotFound = true; int processID = -1; PInvoke.GetWindowThreadProcessId( hWnd, out processID); if( processID == LocalProcess.Id ) { StringBuilder sbProcessText = new StringBuilder(256); PInvoke.GetWindowText( hWnd, sbProcessText, sbProcessText.Capacity); String []windowTitles = WindowTitle.Split(','); for ( int count = 0;count<windowTitles.Length ;count++) { if (sbProcessText.ToString().EndsWith(windowTitles[count]) ) { #if ( !WINCE ) WindowTitle = windowTitles[count]; #endif IntPtr hParentWnd = PInvoke.GetParent( hWnd); if( hParentWnd == IntPtr.Zero) hParentWnd = hWnd; PInvoke.WINDOWPLACEMENT winPlace = new PInvoke.WINDOWPLACEMENT(); winPlace.length = 44; bool bResult = false; #if ( !WINCE ) bResult = PInvoke.GetWindowPlacement( hParentWnd, out winPlace); #else // CE doesn't support GetWindowPlacement bResult = true; winPlace.showCmd = ( uint ) PInvoke.ShowWindowFlags.SW_NORMAL; #endif if(bResult && (winPlace.showCmd != (uint)PInvoke.ShowWindowFlags.SW_SHOWMINIMIZED)) { //int nFlag = (int) PInvoke.ShowWindowFlags.SW_MINIMIZE; int nFlag = (int) PInvoke.ShowWindowFlags.SW_HIDE; PInvoke.ShowWindow( hParentWnd, nFlag); } bNotFound = false; break; } } } return bNotFound; } /// <summary> /// Return window to normal. /// </summary> private bool RestoreToNormalIfMinimize(IntPtr hWnd, int iProcessIndex) { if ( LocalProcess == null || LocalProcess.HasExited || !IsAWindow()) { return false; //stop enumeration } bool bNotFound = true; int processID = -1; PInvoke.GetWindowThreadProcessId( hWnd, out processID); if( processID == LocalProcess.Id ) { StringBuilder sbProcessText = new StringBuilder(256); PInvoke.GetWindowText( hWnd, sbProcessText, sbProcessText.Capacity); String []windowTitles = WindowTitle.Split(','); for ( int count = 0;count<windowTitles.Length ;count++) { if (sbProcessText.ToString().EndsWith(windowTitles[count]) ) { #if ( !WINCE ) WindowTitle = windowTitles[count]; #endif IntPtr hParentWnd = PInvoke.GetParent( hWnd); if( hParentWnd == IntPtr.Zero) hParentWnd = hWnd; PInvoke.WINDOWPLACEMENT winPlace = new PInvoke.WINDOWPLACEMENT(); winPlace.length = 44; bool bResult = false; #if ( !WINCE ) bResult = PInvoke.GetWindowPlacement( hParentWnd, out winPlace); #else // CE doesn't support GetWindowPlacement bResult = true; winPlace.showCmd = ( int ) PInvoke.ShowWindowFlags.SW_NORMAL; #endif if(bResult && (winPlace.showCmd == (uint)PInvoke.ShowWindowFlags.SW_SHOWMINIMIZED)) { int nFlag= (int) PInvoke.ShowWindowFlags.SW_RESTORE; PInvoke.ShowWindow( hParentWnd, nFlag); } if(bResult && (winPlace.showCmd == (uint)PInvoke.ShowWindowFlags.SW_NORMAL && Maximize )) { int nFlag= (int) PInvoke.ShowWindowFlags.SW_MAXIMIZE; PInvoke.ShowWindow( hParentWnd, nFlag); } bNotFound = false; break; } } } return bNotFound; } /// <summary> /// Minimize the executable. /// </summary> public void MinimizeWindow() { try { PInvoke.EnumWindowsCallBack EnumWindowsFunc = new PInvoke.EnumWindowsCallBack(MinimizeWindows); PlatformEnumWindows(EnumWindowsFunc, 0 ); } catch ( Exception e ) { CmDataCapture.Capture( CmDataCapture.MaskError, String.Format("<Exception> [MinimizeWindow()] new Delegate: {0}", e.Message )); } } /// <summary> /// Maximize the executable. /// </summary> public void MaximizeWindow() { try { PInvoke.EnumWindowsCallBack EnumWindowsFunc = new PInvoke.EnumWindowsCallBack(MaximizeWindows); PlatformEnumWindows(EnumWindowsFunc, 0 ); } catch ( Exception e ) { CmDataCapture.Capture( CmDataCapture.MaskError, String.Format("<Exception> [MaximizeWindow()] new Delegate: {0}", e.Message )); } } /// <summary> /// Platform Neutral EnumWindows function /// </summary> /// <param name="EnumWindowsFunc">delegate to call back</param> /// <param name="valInt">Value to pass to delegate</param> private void PlatformEnumWindows( PInvoke.EnumWindowsCallBack EnumWindowsFunc, int valInt ) { #if ( !WINCE ) PInvoke.EnumWindows( EnumWindowsFunc, valInt); #else EnumCEWindows( EnumWindowsFunc, valInt ); #endif } /// <summary> /// EnumCEWindows - Do an EnumWindows for CE.NET. /// </summary> /// <param name="EnumWindowsFunc">CallBack function</param> /// <param name="valInt">Value to pass to callbacks in LParam</param> private void EnumCEWindows( PInvoke.EnumWindowsCallBack EnumWindowsFunc, int valInt ) { // unsafe { IntPtr [] Handles = new IntPtr [ 2048 ]; // fixed ( IntPtr * pHandles = Handles ) { int iHandleCount = 2048; try { PInvoke.GetWindowHandles( Handles, ref iHandleCount ); } catch ( Exception e ) { CmDataCapture.Capture( CmDataCapture.MaskError, String.Format( "<Exception> [PInvoke::EnumCEWindows - GetWindowHandles()] [{0}]", e.Message )); } //CmDataCapture.Capture( CmDataCapture.MaskError, // String.Format( "GetWindowHandles found {0} handles", iHandleCount )); int i = 0; for( i = 0; i < iHandleCount; i++ ) { try { bool bCallResult = true; bCallResult = EnumWindowsFunc( Handles[ i ], valInt ); if ( bCallResult == false ) { return; } } catch ( Exception e ) { CmDataCapture.Capture( CmDataCapture.MaskError, String.Format( "<Exception> [PInvoke::EnumCEWindows - Callback] [{0}] [{1}]", e.Message, EnumWindowsFunc.GetType().Name.ToString() )); } } } } } /// <summary> /// Execute the task. /// </summary> public bool Execute(String function) { bool retVal=true; switch(function.ToLower()) { case "minimize": if ( LocalProcess !=null) { try { PInvoke.EnumWindowsCallBack EnumWindowsFunc = new PInvoke.EnumWindowsCallBack(MinimizeWindows); PlatformEnumWindows(EnumWindowsFunc, 0 ); } catch (Exception e ) { CmDataCapture.Capture( CmDataCapture.MaskError, String.Format("<Exception> [MinimizeWindow2()] new Delegate: {0}", e.Message )); } } else { CmDataCapture.Capture( CmDataCapture.MaskError,"<Exception> [ExecutableMain.Execute()] Cannot Minimize null process."); retVal = false; } break; case "maximize": if ( LocalProcess != null) { try { PInvoke.EnumWindowsCallBack EnumWindowsFunc = new PInvoke.EnumWindowsCallBack(MaximizeWindows); PlatformEnumWindows(EnumWindowsFunc, 0 ); } catch ( Exception e ) { CmDataCapture.Capture( CmDataCapture.MaskError, String.Format("<Exception> [MaximizeWindow2()] new Delegate: {0}", e.Message )); } } else { CmDataCapture.Capture( CmDataCapture.MaskError,"<Exception> [ExecutableMain.Execute()] Cannot Maximize null process."); retVal = false; } break; case "stop": Stop(); break; case "start": retVal = Start(); break; default: CmDataCapture.Capture( CmDataCapture.MaskError,"<Exception> [ExecutableMain.Execute()] Unknown function to execute."); break; } return retVal; } /// <summary> /// Execute only one time (e.g. ADD.BAT) /// </summary> public bool ExecuteOnlyOnce { get { return executeOnlyOnce; } set { executeOnlyOnce = value; } } /// <summary> /// Used in conjunction with "ExecuteOnlyOnce". If the executable file has already run, /// set this boolean value to true. /// </summary> public bool HasBeenExecuted { get { return hasBeenExecuted; } set { hasBeenExecuted = value; } } /// <summary> /// Save the handle of the foreground window. /// </summary> public IntPtr ForegroundWindowHandle { get { return foregroundWindowHandle; } set { foregroundWindowHandle = value; } } /// <summary> /// Get/Set for topMost. If true, the executable window style be HWND_TOPMOST (if false HWND_TOP) /// </summary> public bool TopMost { get { return topMost; } set { topMost = value; } } /// <summary> /// Inidcates if LaunchPad should wait til this executable is complete before continuing (used for ADD.BAT) /// </summary> public bool WaitForExit { get { return waitForExit; } set { waitForExit = value; } } /// <summary> /// Executable name /// </summary> private String executableName; /// <summary> /// executable window title string - use for traversing windows /// </summary> private String windowTitle; /// <summary> /// Main executable filename /// </summary> private String filename = ""; /// <summary> /// Main executable path /// </summary> private String path = ""; /// <summary> /// Executable arguments /// </summary> private String arguments; /// <summary> /// Executable override of the STOP Window (if empty, use the MainWindowTitle from the Process class) /// </summary> private String stopWindow = ""; /// <summary> /// Executable override of the STOP User Message. (default to 0). If overridden WM_USER + override value is sent. /// If not overridden, WM_CLOSE is sent. /// </summary> private uint stopUserMessage = 0; /// <summary> /// Maximize flag /// </summary> private bool maximize = true; /// <summary> /// Minimize at start indicator. Used to get rid of DOS boxes and "ScotInputWindow". /// </summary> private bool minimizeStart = false; /// <summary> /// Main executable indicator /// </summary> private bool isMainExecutable = false; /// <summary> /// Windows process /// </summary> private Process localProcess = null; /// <summary> /// FunctionProcess array /// </summary> private ArrayList m_functionProcessor = new ArrayList(); /// <summary> /// Let executable complete before continuing... /// </summary> private bool waitForExit = false; /// <summary> /// If true, the executable window style be HWND_TOPMOST (if false HWND_TOP) /// </summary> private bool topMost = true; /// <summary> /// Execute only one time (e.g. ADD.BAT) /// </summary> private bool executeOnlyOnce = false; /// <summary> /// Used in conjunction with "ExecuteOnlyOnce". If the executable file has already run, /// set this boolean value to true. /// </summary> private bool hasBeenExecuted = false; /// <summary> /// Save the handle of the foreground window. /// </summary> private IntPtr foregroundWindowHandle = IntPtr.Zero; }//end class }
4f3197571bd0822a027cabf8f82438419375b7b9
C#
piotr0sawicki/Polygon_Projekt_20Z
/Assets/Scripts/HealthComponent.cs
2.828125
3
using UnityEngine; using UnityEngine.Assertions; public class HealthComponent : MonoBehaviour { [SerializeField, Range(1.0f, 1000.0f)] private float maxHealth = 10.0f; private float currentHealth = 1.0f; public event System.Action OnHealthChange; public event System.Action OnHit; public event System.Action OnDeath; public bool IsAlive => currentHealth > 0.0f; public float MaxHealth => maxHealth; public float HealthPercentage => currentHealth / maxHealth; public float CurrentHealth { get { return currentHealth; } set { if (currentHealth != value) { currentHealth = Mathf.Clamp(value, 0.0f, maxHealth); OnHealthChange?.Invoke(); } } } private void Awake() { currentHealth = maxHealth; } public void ApplyDamage(float amount) { Assert.IsTrue(amount > 0.0f); if (IsAlive) { CurrentHealth -= amount; if (IsAlive) { OnHit?.Invoke(); } else { OnDeath?.Invoke(); Destroy(gameObject); } } } public void ApplyHeal(float amount) { Assert.IsTrue(amount > 0.0f); if (IsAlive) { CurrentHealth += amount; } } }
cd5678e4866335aaaf0d101ac4b0c1fad6c66163
C#
PDmatrix/advent-of-code
/CSharp/Solutions/2017/22/Year2017Day22.cs
3.140625
3
using System; using System.Collections.Generic; using System.Linq; using AdventOfCode.Common; using JetBrains.Annotations; namespace AdventOfCode.Solutions._2017._22; [UsedImplicitly] public class Year2017Day22 : ISolution { private const string Directions = "URDLURDL"; private const string PossibleStates = ".W#F."; public object Part1(IEnumerable<string> input) { var gridState = GetGridState(input); var currentPosition = (x: 12, y: 12); var currentDirection = 'U'; var newInfections = 0; for (var i = 0; i < 10000; i++) { var isInfected = gridState.GetValueOrDefault(currentPosition, '.') == '#'; currentDirection = Directions[Directions.IndexOf(currentDirection) + (isInfected ? 1 : 3)]; if (isInfected) { gridState.Remove(currentPosition); } else { newInfections++; gridState[currentPosition] = '#'; } currentPosition = GetNewPosition(currentPosition, currentDirection); } return newInfections.ToString(); } public object Part2(IEnumerable<string> input) { var gridState = GetGridState(input); var currentPosition = (x: 12, y: 12); var currentDirection = 'U'; var newInfections = 0; for (var i = 0; i < 10000000; i++) { var currentState = gridState.GetValueOrDefault(currentPosition, '.'); currentDirection = currentState switch { '.' => Directions[Directions.IndexOf(currentDirection) + 3], '#' => Directions[Directions.IndexOf(currentDirection) + 1], 'F' => Directions[Directions.IndexOf(currentDirection) + 2], _ => currentDirection }; var newState = PossibleStates[PossibleStates.IndexOf(currentState) + 1]; if (newState == '#') newInfections++; gridState[currentPosition] = newState; currentPosition = GetNewPosition(currentPosition, currentDirection); } return newInfections.ToString(); } private static Dictionary<(int x, int y), char> GetGridState(IEnumerable<string> input) => input.SelectMany((row, y) => row.Select((state, x) => (state, x, y))) .ToDictionary(key => (key.x, key.y), value => value.state); private static (int x, int y) GetNewPosition((int x, int y) position, char direction) => direction switch { 'U' => (position.x, position.y - 1), 'D' => (position.x, position.y + 1), 'L' => (position.x - 1, position.y), 'R' => (position.x + 1, position.y), _ => throw new Exception("Unexpected position") }; }
358934ab2af14e69124d47051411b64bdaf22604
C#
kunkliricsi/Snake-AI
/Handlers/StrategyHandler.cs
2.828125
3
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows; using Kukac.enums; using Kukac.interfaces; using Kukac.kukac; namespace Kukac.ai.Handlers { using Strategies; /// <summary> /// The God object. It's purpose is to handle all end every strategy it gets. /// Also functions as a strategy that can be used in other strategies and strategy handlers. /// It's decision is equal to the decision of the strategy with the highest priority that had /// a valid outcome. /// </summary> class StrategyHandler : Strategy, Ai { private readonly Dictionary<Strategy, int> strategyPriorities = new Dictionary<Strategy, int>(); #region Constructors public StrategyHandler( Adat data, Test snake, IDictionary<Strategy, int> strategiesWithPriorities) : base(data, snake) { this.strategyPriorities = new Dictionary<Strategy, int>(strategiesWithPriorities); foreach (var strategy in strategyPriorities.Keys) strategy.Config(data, snake); this.finalDirection = Iranyok.LE; } public void initAdat(Adat adat) { this.data = (Data)adat; } public void initKukac(Test kukac) { this.snake = kukac; } #endregion /// <summary> /// Orders strategies by priority. /// </summary> /// <returns> /// A list of the ordered strategies. /// </returns> private List<Strategy> GetOrderedStrategiesByPriority() { List<KeyValuePair<Strategy, int>> orderedStrategiesByPriorityPairs = strategyPriorities.OrderBy(x => x.Value).ToList(); List<Strategy> orderedStrategiesByPriorityStrategies = new List<Strategy>(); foreach (KeyValuePair<Strategy, int> stratPair in orderedStrategiesByPriorityPairs) orderedStrategiesByPriorityStrategies.Add(stratPair.Key); return orderedStrategiesByPriorityStrategies; } /// <summary> /// Runs every strategy it holds, by the highest priority. /// /// </summary> /// <returns></returns> public override bool Run() { List<Strategy> orderedStrategiesByPriority = GetOrderedStrategiesByPriority(); foreach (Strategy strategy in orderedStrategiesByPriority) { if (strategy.Run()) { this.finalDirection = strategy.FinalDirection; return true; } } return false; } /// <summary> /// Runs the handler. Returns the evaluated direction it thinks the snake should move in. /// </summary> /// <returns></returns> public Iranyok setIrany() { Run(); return finalDirection; } } }
dedc9097cfb9278c8838ea80c00face87218ef55
C#
chakrabar/Dorkari
/Dorkari.Helpers.File/Compresser.cs
3
3
using ICSharpCode.SharpZipLib.Core; using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Tar; using ICSharpCode.SharpZipLib.Zip; using System; using System.IO; namespace Dorkari.Helpers.Files { public class Compresser //from SharpZipLib samples { public void CreateTarGZipFromDirectory(string tgzOutputFilename, string sourceDirectory) { using (Stream outStream = File.Create(tgzOutputFilename)) using (Stream gzoStream = new GZipOutputStream(outStream)) using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzoStream)) { // Note that the RootPath is currently case sensitive and must be forward slashes e.g. "c:/temp" // and must not end with a slash, otherwise cuts off first char of filename // This is scheduled for fix in next release tarArchive.RootPath = sourceDirectory.Replace('\\', '/'); if (tarArchive.RootPath.EndsWith("/")) tarArchive.RootPath = tarArchive.RootPath.Remove(tarArchive.RootPath.Length - 1); AddDirectoryFilesToTarGZip(tarArchive, sourceDirectory); } } private void AddDirectoryFilesToTarGZip(TarArchive tarArchive, string sourceDirectory, bool recurse = false) { // Write each file to the tar. string[] filenames = Directory.GetFiles(sourceDirectory); foreach (string filename in filenames) { TarEntry tarEntry = TarEntry.CreateEntryFromFile(filename); tarArchive.WriteEntry(tarEntry, true); } if (recurse) { TarEntry tarEntry = TarEntry.CreateEntryFromFile(sourceDirectory); tarArchive.WriteEntry(tarEntry, false); //optional string[] directories = Directory.GetDirectories(sourceDirectory); foreach (string directory in directories) AddDirectoryFilesToTarGZip(tarArchive, directory, recurse); } } public void CreateCustomTarGZipFromDirectory(string outputFileName, string sourceDirectory, bool includeSubDirectories = false, bool createEntryForSourceDirectory = false) { using (Stream outStream = File.Create(outputFileName)) { using (GZipOutputStream gzoStream = new GZipOutputStream(outStream)) { gzoStream.SetLevel(3); // 1 - 9, 1 is best speed, 9 is best compression //3 using (TarOutputStream tarOutputStream = new TarOutputStream(gzoStream)) CreateTarManually(tarOutputStream, sourceDirectory, includeSubDirectories, createEntryForSourceDirectory); } } } private void CreateTarManually(TarOutputStream tarOutputStream, string sourceDirectory, bool isRecursive, bool createEntryForSourceDirectory) { using (tarOutputStream) { if (createEntryForSourceDirectory) { TarEntry tarEntry = TarEntry.CreateEntryFromFile(sourceDirectory); tarOutputStream.PutNextEntry(tarEntry); } string[] filenames = Directory.GetFiles(sourceDirectory); foreach (string filename in filenames) { using (Stream inputStream = File.OpenRead(filename)) { string tarName = Path.GetFileName(filename); //FROM C:\A\B\C.txt TO C.txt long fileSize = inputStream.Length; TarEntry entry = TarEntry.CreateTarEntry(tarName); entry.Size = fileSize; // Must set size, otherwise TarOutputStream will fail when output exceeds. tarOutputStream.PutNextEntry(entry); // Add the entry to the tar stream, before writing the data. byte[] localBuffer = new byte[32 * 1024]; // this is copied from TarArchive.WriteEntryCore while (true) { int numRead = inputStream.Read(localBuffer, 0, localBuffer.Length); if (numRead <= 0) { break; } tarOutputStream.Write(localBuffer, 0, numRead); } } tarOutputStream.CloseEntry(); } if (isRecursive) { string[] directories = Directory.GetDirectories(sourceDirectory); foreach (string directory in directories) { CreateTarManually(tarOutputStream, directory); } } } } //from https://github.com/icsharpcode/SharpZipLib/wiki/GZip-and-Tar-Samples#createFull public void CreateTarFromDirectory(string outputFileName, string sourceDirectory) { // Create an output stream. Does not have to be disk, could be MemoryStream etc. Stream outStream = File.Create(outputFileName); //@"c:\temp\test.tar"; // If you wish to create a .Tar.GZ (.tgz): // - set the filename above to a ".tar.gz", // - create a GZipOutputStream here // - change "new TarOutputStream(outStream)" to "new TarOutputStream(gzoStream)" // Stream gzoStream = new GZipOutputStream(outStream); // gzoStream.SetLevel(3); // 1 - 9, 1 is best speed, 9 is best compression TarOutputStream tarOutputStream = new TarOutputStream(outStream); CreateTarManually(tarOutputStream, sourceDirectory); //@"c:\temp\debug" // Closing the archive also closes the underlying stream. // If you don't want this (e.g. writing to memorystream), set tarOutputStream.IsStreamOwner = false tarOutputStream.Close(); } private void CreateTarManually(TarOutputStream tarOutputStream, string sourceDirectory) { // Optionally, write an entry for the directory itself. TarEntry tarEntry = TarEntry.CreateEntryFromFile(sourceDirectory); tarOutputStream.PutNextEntry(tarEntry); // Write each file to the tar. string[] filenames = Directory.GetFiles(sourceDirectory); foreach (string filename in filenames) { // You might replace these 3 lines with your own stream code using (Stream inputStream = File.OpenRead(filename)) { string tarName = filename.Substring(3); // strip off "C:\" long fileSize = inputStream.Length; // Create a tar entry named as appropriate. You can set the name to anything, // but avoid names starting with drive or UNC. TarEntry entry = TarEntry.CreateTarEntry(tarName); // Must set size, otherwise TarOutputStream will fail when output exceeds. entry.Size = fileSize; // Add the entry to the tar stream, before writing the data. tarOutputStream.PutNextEntry(entry); // this is copied from TarArchive.WriteEntryCore byte[] localBuffer = new byte[32 * 1024]; while (true) { int numRead = inputStream.Read(localBuffer, 0, localBuffer.Length); if (numRead <= 0) { break; } tarOutputStream.Write(localBuffer, 0, numRead); } } tarOutputStream.CloseEntry(); } // Recurse. Delete this if unwanted. string[] directories = Directory.GetDirectories(sourceDirectory); foreach (string directory in directories) { CreateTarManually(tarOutputStream, directory); } } public void ExtractZippedFiles(string zippedFilePath, string outputDirectory) { using (FileStream fs = File.OpenRead(zippedFilePath)) using (var zf = new ZipFile(fs)) { foreach (ZipEntry zipEntry in zf) { if (!zipEntry.IsFile) { continue; // Ignore directories } String entryFileName = zipEntry.Name; byte[] buffer = new byte[4096]; // 4K is optimum using (Stream zipStream = zf.GetInputStream(zipEntry)) { // Manipulate the output filename here as desired. String fullZipToPath = Path.Combine(outputDirectory, entryFileName); string directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) Directory.CreateDirectory(directoryName); using (FileStream streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } } } } } public void ExtractZipFilesCustom(string archiveFilenameIn, string password, string outFolder) { ZipFile zf = null; try { FileStream fs = File.OpenRead(archiveFilenameIn); zf = new ZipFile(fs); if (!String.IsNullOrEmpty(password)) { zf.Password = password; // AES encrypted entries are handled automatically } foreach (ZipEntry zipEntry in zf) { if (!zipEntry.IsFile) { continue; // Ignore directories } String entryFileName = zipEntry.Name; // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName); // Optionally match entrynames against a selection list here to skip as desired. // The unpacked length is available in the zipEntry.Size property. byte[] buffer = new byte[4096]; // 4K is optimum Stream zipStream = zf.GetInputStream(zipEntry); // Manipulate the output filename here as desired. String fullZipToPath = Path.Combine(outFolder, entryFileName); string directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) Directory.CreateDirectory(directoryName); // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size // of the file, but does not waste memory. // The "using" will close the stream even if an exception occurs. using (FileStream streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } } } finally { if (zf != null) { zf.IsStreamOwner = true; // Makes close also shut the underlying stream zf.Close(); // Ensure we release resources } } } public void CompressFilesToZip(string outZipPath, string sourceFolderPath, string password = null) { FileStream fsOut = File.Create(outZipPath); ZipOutputStream zipStream = new ZipOutputStream(fsOut); zipStream.SetLevel(3); //0-9, 9 being the highest level of compression if (!String.IsNullOrEmpty(password)) zipStream.Password = password; // optional. Null is the same as not setting. Required if using AES. // This setting will strip the leading part of the folder path in the entries, to // make the entries relative to the starting folder. // To include the full path for each entry up to the drive root, assign folderOffset = 0. int folderOffset = sourceFolderPath.Length + (sourceFolderPath.EndsWith("\\") ? 0 : 1); CompressFolder(sourceFolderPath, zipStream, folderOffset); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); } // Recurses down the folder structure private void CompressFolder(string sourceFolderPath, ZipOutputStream zipStream, int folderOffset) { string[] files = Directory.GetFiles(sourceFolderPath); foreach (string filename in files) { FileInfo fi = new FileInfo(filename); string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity // Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256. // A password on the ZipOutputStream is required if using AES. // newEntry.AESKeySize = 256; // To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code, // you need to do one of the following: Specify UseZip64.Off, or set the Size. // If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either, // but the zip will be in Zip64 format which not all utilities can understand. // zipStream.UseZip64 = UseZip64.Off; newEntry.Size = fi.Length; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); } string[] folders = Directory.GetDirectories(sourceFolderPath); foreach (string folder in folders) { CompressFolder(folder, zipStream, folderOffset); } } public void ExtractTGZ(string gzArchiveFilePath, string destinationDirectory) { using (Stream inStream = File.OpenRead(gzArchiveFilePath)) using (Stream gzipStream = new GZipInputStream(inStream)) using (TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream)) tarArchive.ExtractContents(destinationDirectory); } } }
a2a85f58e2465906a98bb03475db45edc674a01a
C#
BryanApellanes/Bam.Net
/shared/bam.net.shared/Testing/Specification/ItContext.cs
2.78125
3
using Bam.Net.CoreServices; using System; using System.Collections.Generic; using System.Text; namespace Bam.Net.Testing.Specification { public class ItContext { Queue<AssertionAction> _shouldQueue; public ItContext() { _shouldQueue = new Queue<AssertionAction>(); Assertions = new List<Assertion>(); } public object AssertionTarget { get; set; } protected internal List<Assertion> Assertions { get; set; } protected ServiceRegistry SpecificationTestRegistry { get; set; } public ItContext It(object target) { AssertionTarget = target; return this; } public ItContext Should(Func<ItContext, object> func) { _shouldQueue.Enqueue(new AssertionFunc<object> { ShouldDescription = "should return", Func = func }); return this; } public ItContext Should(string description, Action action) { _shouldQueue.Enqueue(new AssertionAction { ShouldDescription = description, Action = action }); return this; } public ItContext Return<T>() { AssertionFunc<T> func = (AssertionFunc<T>)_shouldQueue.Dequeue(); func.Execute(this); Assertions.Add(func); return this; } public ItContext WithoutThrowing() { return NotThrow(); } public ItContext NotThrow() { AssertionAction action = _shouldQueue.Dequeue(); Assertions.Add(action.Execute()); return this; } public ItContext IsA<T>() { string target = AssertionTarget == null ? "[null]" : AssertionTarget.ToString(); if (AssertionTarget is T) { AddSuccess($"{target} is a {typeof(T).Name}"); } else { AddFailure($"{target} was NOT a{typeof(T).Name}"); } return this; } public ItContext Is(object compareTo) { return Be(compareTo); } public ItContext IsEqualTo(object compareTo, string successMessage = null) { string target = AssertionTarget == null ? "[null]" : AssertionTarget.ToString(); string compare = compareTo == null ? "[null]" : compareTo.ToString(); if (AssertionTarget.Equals(compareTo)) { AddSuccess(successMessage ?? $"{target} equals {compare}"); } else { AddFailure($"{target} did not equal {compare}"); } return this; } public ItContext IsTrue(string message = null) { if(((bool)(AssertionTarget)) == true) { AddSuccess(message ?? $"{AssertionTarget.ToString()} was true"); } else { AddFailure(message ?? $"{AssertionTarget.ToString()} was true"); } return this; } public ItContext Be(object compareTo) { bool passed = AssertionTarget == compareTo; if (passed) { AddSuccess($"{AssertionTarget.ToString()} is {compareTo.ToString()}"); } else { AddFailure($"{AssertionTarget.ToString()} is NOT {compareTo.ToString()}"); } return this; } protected void AddSuccess(string message) { Assertions.Add(new Assertion { Passed = true, SuccessMessage = message }); } protected void AddFailure(string message) { Assertions.Add(new Assertion { Passed = false, FailureMessage = message }); } } }
b3afdb87c47ab673c6e82a64c072ead415e1a33d
C#
N3X15/Kerbal-Mod-Manager
/KMM/Repositories/Mod.cs
2.640625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Windows.Forms; using System.IO; namespace KMM.Repositories { /// <summary> /// Stores data regarding a mod. /// </summary> public class Mod:DataGridViewRow { public string Name = ""; public string Version = ""; public VersionMatcher KSPVersion = null; public string Description = ""; public List<string> ImageURLs = new List<string>(); public List<string> Files = new List<string>(); public string URL = ""; public string Author=""; public string Thread=""; public bool Installed = false; /// <summary> /// For loading a mod metadata file /// </summary> /// <param name="mod_data"></param> public Mod(string mod_data) { /* * Mission Aeronautics * by N3X15 * Version: 0.0.1 * URL: http://ci.nexisonline.net/mirror/kerbal/MissionPack0.0.1.zip * Requires KSP 0.13.0 to 0.13.1 * Description: Blah blah blah * Thumbnails: http... http... * Thread: http... */ foreach (string line in mod_data.Split('\n')) { if (line.Contains(":") && handleColon(line)) { ; } else if (line.StartsWith("by ")) { Author = line.Remove(0, 3).Trim(); } else if (line.StartsWith("Requires KSP ")) { KSPVersion = new VersionMatcher(line.Remove(0, 13).Trim()); } else { Name = line.Trim(); } } } public void findMyFiles() { Files.Clear(); do_filesearch(getFolder()); } private void do_filesearch(string folder) { DirectoryInfo dir = new DirectoryInfo(folder); foreach (FileSystemInfo fsi in dir.GetFileSystemInfos("*",SearchOption.TopDirectoryOnly)) { if (fsi is DirectoryInfo) { do_filesearch(Path.Combine(folder, fsi.Name)); } if (fsi is FileInfo) { Files.Add(Path.Combine(folder, fsi.Name).Replace(getFolder(),"")); } } } private string getFolder() { return Path.Combine("mods", Name.Replace(" ", "")); } /// <summary> /// For loading from a repository /// </summary> /// <param name="node"></param> public Mod(XmlNode node) { Name = node.Attributes["name"].Value; Version = node.Attributes["version"].Value; KSPVersion = new VersionMatcher(node.Attributes["kspversion"].Value); Description = node.Attributes["description"].Value; URL = node.Attributes["url"].Value; Author = node.Attributes["author"].Value; Thread = node.Attributes["thread"].Value; ImageURLs = new List<string>(); foreach (XmlNode imgnode in node.ChildNodes) { if(imgnode.NodeType == XmlNodeType.Element) { if (imgnode.Name.Equals("thumb")) { ImageURLs.Add(imgnode.Value); } if (imgnode.Name.Equals("file")) { Files.Add(imgnode.Value); } } } } public Mod() { // TODO: Complete member initialization } private bool handleColon(string line) { string[] chunks = line.Split(':'); string key = chunks[0]; string value = line.Remove(0,line.IndexOf(':')+1).Trim(); switch (key) { case "Version": this.Version = value; return true; case "URL": this.URL = value; return true; case "Description": this.Version = value; return true; case "Thumbnails": this.ImageURLs = new List<string>(value.Split(' ')); return true; case "Thread": this.Thread = value; return true; } return false; } /// <summary> /// For re-serializing to XML /// </summary> /// <param name="doc"></param> /// <returns></returns> public XmlNode toXML(XmlDocument doc) { /** * <mod * name="Range Safety Device" * version="0.0.1" * kspversion="0.13.0 to 0.13.1" * description="butts" * url="http..." * author="N3X15" * thread="http..."> * <thumb>img/thumbs/whatever.png</thumb> * <file>Parts/MISSION_Range%20Safety%20Device/part.cfg</file> * </mod> */ XmlElement mod = doc.CreateElement("mod"); mod.SetAttribute("name", Name); mod.SetAttribute("version", Version); mod.SetAttribute("kspversion", KSPVersion.ToString()); mod.SetAttribute("description", Description); mod.SetAttribute("url", URL); mod.SetAttribute("author", Author); mod.SetAttribute("thread", Thread); foreach (string thumb in ImageURLs) { XmlElement thumbnode = doc.CreateElement("thumb"); thumbnode.Value = thumb; mod.AppendChild(thumbnode); } foreach (string file in Files) { XmlElement filenode = doc.CreateElement("file"); filenode.Value = file; mod.AppendChild(filenode); } return mod; } } }
9de4df232ca770d574b7eb87a771275bdb508af9
C#
DangouHaim/AnalyticsTools
/AnalyticsTools/BLL/UniversalAnalitics.cs
2.671875
3
 namespace AnalyticsTools { class UniversalAnalytics { private readonly IGoogleAnalytics _googleAnalytics; private readonly IYandexDirect _yandexAnalytics; public UniversalAnalytics() { _googleAnalytics = new GoogleAnalytics(); _yandexAnalytics = new YandexDirect(); } public UniversalAnalytics(IGoogleAnalytics googleBehaviour, IYandexDirect yandexBehaviour) { _googleAnalytics = googleBehaviour; _yandexAnalytics = yandexBehaviour; } public void Report() { _googleAnalytics.Report(); _yandexAnalytics.Report(); ReportCore(); } protected virtual void ReportCore() { //Override for your own logic of report } public IGoogleAnalytics Google() { return _googleAnalytics; } public IYandexDirect Yandex() { return _yandexAnalytics; } } }
fc1f7040f1479c26651bab7dafdd41b7359fd2ae
C#
kepengProgramCode/User
/Hnt.StackTray/Hnt.StackTray/Hnt.Business/Common/ViewPages.cs
2.515625
3
using Hnt.Entity; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hnt.Business.Common { public class ViewPages : INotifyPropertyChanged { private int _number; public int Number { get { return _number; } set { _number = value; NotifyPropertyChanged("Number"); } } private int _currentSize; public int CurrentSize { get { return _currentSize; } set { _currentSize = value; NotifyPropertyChanged("CurrentSize"); } } private int _total; public int Total { get { return _total; } set { _total = value; NotifyPropertyChanged("Total"); } } private List<Page> _pages; public List<Page> Pages { get { return _pages; } set { _pages = value; NotifyPropertyChanged("Pages"); } } private List<StackTrays> _listRegDept; public List<StackTrays> ListRegDept { get { return _listRegDept; } set { _listRegDept = value; NotifyPropertyChanged("ListRegDept"); } } private List<StackTrays> _listBind; public List<StackTrays> ListBind { get { return _listBind; } set { _listBind = value; NotifyPropertyChanged("ListBind"); } } #region INotyfyPropertyChanged 成员 public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(string PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(PropertyName)); } } #endregion public ViewPages(List<StackTrays> listRegDept) { this.Number = 14;//设置每页显示数目 this.ListRegDept = listRegDept; this.Total = ListRegDept.Count() / this.Number + 1;//获取总页数 this.Pages = new List<Page>();//初始化所有页数数组 for (int i = 1; i <= this.Total; i++) { this.Pages.Add(new Page { Name = i.ToString(), PageSize = i }); } this.CurrentSize = 1;//设置当前显示页面 Fun_Pager(this.CurrentSize); } /// <summary> /// 分页方法 /// </summary> /// <param name="CurrentSize">当前页数</param> public void Fun_Pager(int CurrentSize) { this.CurrentSize = CurrentSize; this.ListBind = this.ListRegDept.Take(this.Number * this.CurrentSize) .Skip(this.Number * (this.CurrentSize - 1)).ToList(); } } public class Page { public string Name { get; set; } public int PageSize { get; set; } } }
09d01d6e62939045984716b4745af9e177b7006b
C#
Codeators/WebAPI-Test-Environment
/Servers/ASP.Net C#/WebAPI2/Controllers/EmployeesController.cs
2.65625
3
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Claims; using System.Web.Http; using WebAPI2.Models; namespace WebAPI2.Controllers { public class EmployeesController : ApiController { [AllowAnonymous] [HttpGet] public IEnumerable<Employee> Get() { return MyDatabase.Employees; } [Authorize] [HttpGet] [Route("api/Search/Employees/{id}")] // Change the Default Route public IEnumerable<Employee> Get(int id) { return MyDatabase.Employees.Where(x => x.ID == id); } [Authorize] [HttpPost] public void Post([FromBody]Employee value) { int NewID = 1; if (MyDatabase.Employees.Count > 0) NewID = MyDatabase.Employees.Max(x => x.ID) + 1; value.ID = NewID; MyDatabase.Employees.Add(value); } [Authorize(Roles = "User")] [HttpPut] public void Put(int id, [FromBody]Employee value) { Employee emp = MyDatabase.Employees.Where(x => x.ID == id).SingleOrDefault(); if (emp != null) { int index = MyDatabase.Employees.IndexOf(emp); value.ID = id; MyDatabase.Employees[index] = value; } } [Authorize(Roles = "Admin")] [HttpDelete] public void Delete(int id) { Employee emp = MyDatabase.Employees.Where(x => x.ID == id).SingleOrDefault(); if (emp != null) { MyDatabase.Employees.Remove(emp); } } } }
86ada46e37385425e03ab86b0184e56bd39d5925
C#
subrotocse/Web-App-Development-DOT-NET
/OOP Example1/OOP Example1/Person.cs
3.0625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OOP_Example1 { class Person { public string firstName; public string middleName; public string lastName; public string nId; public Person(string firstName,string middleName,string lastName) { this.firstName = firstName; this.middleName = middleName; this.lastName = lastName; } public Person(string firstName, string lastName) { this.firstName = firstName; this.lastName = lastName; } public Person() { } public string GetFullName() { return "First Name : "+firstName+"\nMiddle Name : "+middleName+"\nLast Name : "+lastName; } } }
2e0922f99e4d551c6eb7d553561bed186c82095d
C#
kr105/svn-dump
/Shaiya Tools/Shaiya Editor/Editor.Lib/ShaiyaDataWriterHelper.cs
2.515625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Editor.Lib { public class ShaiyaDataWriterHelper { public static byte[] GetHeader() { List<byte> headData = new List<byte>(); headData.AddRange( new byte[]{ 0x53, // S 0x41, // A 0x48, // H 0x00, // 3 0x00, 0x00, 0x00, 0xB0, // 7 0x4E, // 8 0x00, 0x00, // 10 0x53, // S 0x68, // h 0x61, // a 0x69, // i 0x6A, // j 0x61, // a 0x20, // 0x44, // D 0x61, // a 0x74, // t (20) 0x61, // a 0x45, // E 0x64, // d 0x69, // i 0x74, // t 0x6F, // o 0x72, // r 0x20, // 0x2D, // - 0x20, // (30) 0x62, // b 0x79, // y 0x20, // 0x47, // G 0x6F, // o 0x64, // d 0x4C, // L 0x65, // e 0x73, // s (40) 0x5A, // Z 0x00, // 42 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 50 0x00, 0x01, // 52 } ); // fill up for( int i = headData.Count; i < Editor.Lib.ShaiyaData.StartOffset; i++ ) headData.Add( 0x00 ); return headData.ToArray(); } } }
13f821c455e4962fc5f65f750f8001015dbc0c2b
C#
AlexCazan/IMR2
/IMR2_VRTK/Assets/VRTK/LegacyExampleFiles/ExampleResources/Scripts/DrawLines.cs
2.578125
3
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DrawLines : MonoBehaviour { private LineRenderer lineRenderer; public GameObject creta; void Update() { if (Input.GetMouseButtonDown(1)) { GameObject drawing = Instantiate(creta); lineRenderer = drawing.GetComponent<LineRenderer>(); drawing.GetComponent<Renderer>().enabled = false; } if (Input.GetMouseButton(1)) { Draw(); } } void Draw() { lineRenderer.startWidth = 0.2f; lineRenderer.endWidth = 0.2f; lineRenderer.positionCount++; lineRenderer.SetPosition(lineRenderer.positionCount-1, creta.transform.position); } }
5e154c2a5d5ab1aea1eda303cbb447f9b9d954be
C#
guraleks/FileManager
/LocalFileManager.cs
3.09375
3
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace FileManager { // Класс, реализующий методы для локальной работы с файлами public class LocalFileManager : IFileManager { private const string separator = "_version_"; public void CreateFile(string path) { if (File.Exists(path)) { UpdateFile(path); } else { File.Create(path); } } public void CreateFile(string srcPath, string path) { try { if (File.Exists(path)) { UpdateFile(srcPath, path); } else { CopyContent(srcPath, path); } } catch (Exception e) { Console.WriteLine("No such file in source directory"); } } public void DeleteFile(string path) { File.Delete(path); } public void UpdateFile(string path) { CreateFile(IncrementVersion(path)); } public void UpdateFile(string srcPath, string path) { CreateFile(srcPath, IncrementVersion(path)); } public string GetFile(string path) { var list = new List<string>(); foreach (var fileName in Directory.GetFiles(ExtractDirectoryNameFromPath(path))) { var fileNameNoExt = ExtractFileNameFromPath(fileName, false).Split(separator)[0]; if (fileNameNoExt.Equals(ExtractFileNameFromPath(path, false))) { list.Add(fileName); } } switch (list.Count) { case 0: return "Such file does not exist"; case 1: return list[0]; } var version = 0; var num = 0; for (var i = 0; i < list.Count; i++) { try { if (Convert.ToInt32(ExtractFileNameFromPath(list[i], true).Split(separator)[1]) > version) { version = Convert.ToInt32(ExtractFileNameFromPath(list[i], true).Split(separator)[1]); num = i; } } catch (Exception e) {} } return list[num]; } public void CopyContent(string srcPath, string destPath) { FileInfo fileName = new FileInfo(srcPath); fileName.CopyTo(destPath, true); } private string IncrementVersion (string path) { var words = path.Split(separator); if (words.Length > 1) { var version = 0; version = Convert.ToInt32(words[1].Split('.')[0]); version++; path = words[0] + separator + version.ToString() + '.' + words[1].Split('.')[1]; } else { path = path.Split('.')[0] + separator + "1." + path.Split('.')[1]; } return path; } private string ExtractDirectoryNameFromPath(string path) { var str = ""; var strings = path.Split('/'); Array.Resize(ref strings, strings.Length - 1); foreach (var s in strings) { str += s; str += "/"; } return str; } private string ExtractFileNameFromPath(string path, bool withVersion) { if (withVersion) { var arr = path.Split('/'); return arr.Last().Split('.')[0]; } else { var arr = path.Split('/'); return arr.Last().Split('.')[0].Split(separator)[0]; } } private string ExtractExtansionFromPath(string path) { return path.Split('.').Last(); } } }
8ebdb5c41fcfd169c6431ee5582ea367351bf568
C#
ColdMatter/EDMSuite
/ScanMaster/ProfileSet.cs
2.75
3
using System; using System.Collections; using System.Xml.Serialization; namespace ScanMaster { /// <summary> /// The class provides a convenient way to XmlSerialize and deserialize the set of profiles. /// That is it's only function. /// </summary> [Serializable] public class ProfileSet { public ProfileSet() { } private ArrayList profiles; [XmlArray] [XmlArrayItem(Type = typeof(Profile))] public ArrayList Profiles { get { return profiles; } set { profiles = value; } } } }
5536111c60b1971841dafda017505c5aa24a7754
C#
abhi62255/AmazonDream
/AmazonDream.BLL/ProductSuggestion_BLL.cs
2.65625
3
using AmazonDream.DAL; using AmazonDream.Entities; using AmazonDream.ViewModels; using AutoMapper; using System; using System.Collections.Generic; using System.Linq; namespace AmazonDream.BLL { public class ProductSuggestion_BLL { private readonly IMapper _mapper; public ProductSuggestion_BLL(IMapper mapper) { _mapper = mapper; } PreVisitDA _preVisitDA = new PreVisitDA(); ProductDA _productDA = new ProductDA(); WishlistDA _wishlistDA = new WishlistDA(); List<ProductModel> suggestedProductsList = new List<ProductModel>(); public List<ProductModel> GetSuggestedProductsKnownUser(long id) //product Suggession for for know user { var products = _productDA.TrendingProduct(); //by trending if (products != null) AddProductToSuggestionList(products); products = _preVisitDA.GetPrevistProducts(id); //by previst if (products != null) AddProductToSuggestionList(products); var wishlists = _wishlistDA.GetWishlist(id); //by wishlist products = null; foreach(var wish in wishlists) { var product = _productDA.GetProduct(wish.Product_ID); products.Add(product); } if (products != null) AddProductToSuggestionList(products); return suggestedProductsList; } public List<ProductModel> GetSuggestedProductsUnknownUser() //product Suggession for for unknow user { var products = _productDA.TrendingProduct(); //by trending if (products != null) AddProductToSuggestionList(products); return suggestedProductsList; } public void AddProductToSuggestionList(List<Product> products) { foreach (var product in products) { var productBySubCategoryList = _productDA.GetProductsBYSubCategory(product.ProductSubCategory); foreach (var pro in productBySubCategoryList) { var model = _mapper.Map<Product, ProductModel>(pro); if(suggestedProductsList.FirstOrDefault(p=>p.ID == model.ID) == null) suggestedProductsList.Add(model); } } } } }
9c2b97f613759ec0595a1f3bdc077fac86ede3d5
C#
javivi235/APICentral
/APICentral/Controllers/ProductController.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Services; using Services.Models; namespace APICentral.Controllers { [Route("crm-api/products")] public class ProductController : Controller { private IProductService _productService; private IConfiguration _configuration; public ProductController(IConfiguration configuration, IProductService productService) { _configuration = configuration; _productService = productService; } // GET: api/<controller> [HttpGet] public IActionResult Get() { return Ok(_productService.GetAllProductsAsync().Result); } [HttpGet] [Route("list")] public IActionResult Get([FromQuery]string ids) { return Ok(_productService.GetSomeProductsAsync(ids).Result); } // GET api/<controller>/5 [HttpGet("{id}")] public IActionResult GetOne(String id) { return Ok(_productService.GetProductAsync(id).Result); } // POST api/<controller> [HttpPost] public IActionResult Post([FromBody]ProductPostDTO product) { return Ok(_productService.CreateAsync(product).Result); } // PUT api/<controller>/5 [HttpPut("{id}")] public IActionResult Put(String id, [FromBody]ProductPutDTO product) { return Ok(_productService.UpdateAsync(product, id).Result); } // DELETE api/<controller>/5 [HttpDelete("{id}")] public IActionResult Delete(String id) { _productService.DeleteAsync(id); return Ok(); } } }
914b19843d0dc53aefa71a6ee42f37468dcd661b
C#
nxtman123/pupper-hunt
/pupper_hunt/Profile.cs
2.84375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; namespace pupper_hunt { public class Profile { public string Name { get; protected set; } public string Bio { get; protected set; } public ImageSource ImageSource { get; protected set; } public Profile() { Name = ""; Bio = ""; ImageSource = ImageManager.GetImageSource("userUnknownProfile"); } public Profile(string name, string bio, ImageSource source) { Name = name; Bio = bio; ImageSource = source; } public void UpdateInfo(string name, string bio) { Name = name; Bio = bio; } } public enum DogBreed { Corgi, Husky, Lab, NUM } public enum DogPersonality { Aggressive, Nervous, Friendly, NUM } public class DogProfile : Profile { public DogBreed Breed; public DogPersonality Personality; public DogProfile(DogBreed breed, DogPersonality personality, string name, string bio) : base(name, bio, ImageManager.GetImageSource(breed.ToString().ToLower() + "Profile")) { Breed = breed; Personality = personality; } public void UpdateInfo(DogBreed breed, DogPersonality personality, string name, string bio) { ImageSource = ImageManager.GetImageSource(breed.ToString().ToLower() + "Profile"); Breed = breed; Name = name; Bio = bio; Personality = personality; } } }
1d320b6b0147e709039898aec598dfb2b07a531a
C#
Divyashree-Muddagangaiah/LibraryManagement
/Library Management System/Training.LMS.App/Menu.cs
3.1875
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Training.LMS.Core; using Training.LMS.Core.Model; namespace Nalashaa.Training.LMS { static class Menu { static Business instance; static Business Instance { get { if (instance == null) instance = new Business(); return instance; } } public static void Show() { Console.WriteLine("Library Management System"); Console.WriteLine("*************************"); do { Console.WriteLine("1. Search"); Console.WriteLine("2. Issue"); Console.WriteLine("3. Return"); Console.WriteLine("4. Exit"); Console.WriteLine("Enter your option"); int option = Convert.ToInt32(Console.ReadLine()); ProcessOption(option); Console.WriteLine("--------------------------------------------------------------------------"); } while (true); } private static void ProcessOption(int option) { switch(option) { case 1: DoSearch(); break; case 2: IssueBook(); break; case 3: ProcessReturn(); break; case 4: Environment.Exit(0); break; default: Console.WriteLine("Enter a valid option"); break; } } private static void DoSearch() { Console.WriteLine("Enter book title (or a part)"); string title = Console.ReadLine(); Books books = Instance.Search(title); Console.WriteLine("BookId" + "\t\t"+ "Title" + "\t\t" + "Author" + "\t\t" + "Available"); foreach (Book book in books) { Console.WriteLine(book.Id + "\t\t" + book.Title + "\t" + book.Author + "\t" + book.Available); } } private static void IssueBook() { int bookId; if (ReadNumericInput("book id", out bookId) == false) return; int memberId; if (ReadNumericInput("member id", out memberId) == false) return; int issueId = Instance.Issue(bookId, memberId); if (issueId == -1) Console.WriteLine("We are sorry. This book is not available right now."); else if (issueId == 0) Console.WriteLine("We are sorry. Could not complete issue process. Please try after some time."); else Console.WriteLine("Issued book with issue id " + issueId + ". Please note it down as would be asked when return."); } private static void ProcessReturn() { int issueId; if (ReadNumericInput("issue id", out issueId) == false) return; int result = Instance.Return(issueId); if (result == -1) Console.WriteLine("We are sorry. Could not complete return process. Please try after some time."); else if (result == 0) Console.WriteLine("Return completed."); else Console.WriteLine("Return completed. Please collect a fine amount of " + result + " rupees calculated for the delay."); } private static bool ReadNumericInput(string key, out int value) { Console.WriteLine("Enter " + key + "."); if (int.TryParse(Console.ReadLine(), out value)) return true; else { Console.WriteLine("Please enter a valid " + key + "."); return false; } } } }
9831f0406ea6fc8dd09e5987ffffcf122582c647
C#
ZimCodes/self_learning_projects
/Design Patterns/Structural Pattern/Decorator/Decorator.cs
2.59375
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decorator { class Decorator:Sandwich { public Sandwich sandwich; public Decorator(Sandwich sandwich) { this.sandwich = sandwich; } public override string getDesc() { return base.getDesc(); } } }
e0c8416258534e0e5195b4edafe8b56574eb6336
C#
sidby/Sklad1
/SidBy.Common/Helpers/StringHelper.cs
3.109375
3
using System.Text; namespace SidBy.Common.Helpers { public static class StringHelper { public static string Transliterate(string source) { return Transliterate(source, true); } public static string Transliterate(string source, bool trimtolower) { const string chars_allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"; const string chars_ru = "абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"; string[] chars_translit_ruen = {"a", "b","v","g","d","e","yo","zh","z","i","j","k","l","m","n","o","p","r","s","t","u","f","h","c","ch","sh","sch","","y","", "e","yu", "ya", "A", "B","V","G","D","E","YO","ZH","Z","I","J","K","L","M","N","O","P","R","S","T","U","F","H","C","CH","SH","SCH","","Y","", "E","YU", "YA"}; StringBuilder sb = new StringBuilder(); if (trimtolower) { source = source.Trim().ToLower(); } foreach (char c in source) { if (c == ' ') { sb.Append('-'); } else if (chars_allowed.IndexOf(c) >= 0) { sb.Append(c); } else if (chars_ru.IndexOf(c) >= 0) { int index = chars_ru.IndexOf(c); sb.Append(chars_translit_ruen[index]); } } return sb.ToString(); } } }
55b7ad634dad1811d58a5acd9e9cc4d58ecb39bf
C#
AshV/Cracking-the-Code-P2P-App-Development
/C# Version/P2P/WorkingWithXML/clsXMLParser.cs
3.25
3
namespace WorkingWithXML { using System; // Provides the basic functionality of .NET using System.Net; // Provides the net related functionality using System.IO; // Provides the I/O functionality using System.Text; // Provides text based manipulations /// <summary> /// Generic structure used for parsing the XML data /// This structure composes of various sub structures /// Each sub structure represents and XML request in whole /// Every XML is parsed into its corresponding structure to /// fill its values TypeOfXMLRecieved() function of /// ServerCommunication class will determine that which structure /// has to be filled /// </summary> public struct XMLSTRUCT { /// <summary> /// This structure is used store the parsed /// values of the AUTH XML which is returned /// after login process /// </summary> public struct __AUTHENTICATION { /// <summary> /// Stores the Code value in it 0(successful) /// or 1(some error occured) /// </summary> public int iCode; /// <summary> /// This will stores the status of the login process /// and any error message if occured while login /// </summary> public string sStatus; /// <summary> /// This is used for cross checking the IP address /// which is send to the server that login is successful /// or not /// </summary> public string sIPAddress; } /// <summary> /// This structure is used to store the List of all /// the Listeners from the server that are currently /// The values are returned in the USERLIST response XML /// running /// </summary> public struct __USERLIST { /// <summary> /// Name by which the Listener has logged in /// </summary> public string sUsername; /// <summary> /// IP Address of that Listener /// </summary> public string sIPAddress; } /// <summary> /// This is use to store the values which are parsed /// from the SHOWFILES response XML from the Listener /// It containes the Files and Folders which are to /// be shown to the user /// </summary> public struct __SHOWFILES { /// <summary> /// Stores the Filename or Folder name /// </summary> public string sFilename; /// <summary> /// Stores the FileSize, 0 in case of folders /// </summary> public int iFileSize; /// <summary> /// Mask stores the mask value of a file or folder /// 0(readonly file/folder) 1(read/write access) /// </summary> public int iMask; } /// <summary> /// In case of any Error an ERROR response XML is /// thrown from the Listener. The values are parsed into /// this structure /// </summary> public struct __ERROR { /// <summary> /// Stores the error code /// </summary> public int iErrCode; /// <summary> /// Stores the severity of the error /// Message or Warning or Error /// </summary> public string sSeverity; /// <summary> /// The actual error description is stored in this /// variable /// </summary> public string sDescription; } /// <summary> /// no XML parser has been made for this structure, /// since it is not used in this version /// </summary> public struct __UPDNLOAD { public string sFilename; public int iMask; } /// <summary> /// no XML parser has been made for this structure, /// since it is not used in this version /// </summary> public struct __MESSAGE { public string sSenderName; public string sMessage; public string sIPAddress; } /// <summary> /// this structure stores the values from the /// SERVERSEARCH XML that is returned by the Server /// as the result of search /// </summary> public struct __SERVERSEARCH { /// <summary> /// IP address of the machine where the file or folder /// is found /// </summary> public string sIPAddress; /// <summary> /// Username i.e login name of the machine /// </summary> public string sUsername; /// <summary> /// Name of the file found for search criteria is /// in this variable /// </summary> public string sFilename; } /// <summary> /// Global varibales which are used /// in differents parts of the code /// for their specific structures /// </summary> public __AUTHENTICATION AUTH; public __USERLIST[] USERLIST; public __SHOWFILES[] SHOWFILES; public __SHOWFILES[] SEARCH; public __SERVERSEARCH[] SERVERSEARCH; public __ERROR ERROR; public __MESSAGE MESSAGE; } /// <summary> /// Summary description for clsXMLParser. /// This class is used to parse any XML that is recieved /// by the Listener of Browser(Client) /// and stores the values to their corresponding /// structures so that the application could use them /// </summary> public class XMLParser { /// <summary> /// Stores the Filename to write when login response /// when has arrived to the Browser /// </summary> public string LOGINXML; /// <summary> /// Stores the Filename to write when USERLIST response /// when has arrived to the Browser /// </summary> public string USERLISTXML; /// <summary> /// Stores the Filename to write when SERVERSEARCH response /// when has arrived to the Browser /// </summary> public string SERVERSEARCHRESULTXML; /// <summary> /// stores the number of tags that are found /// in the response XML /// </summary> protected int iTags; /// <summary> /// Used to store the counter that is how many time /// a loop is running /// </summary> protected int iCounter; /// <summary> /// This document variable points to the XML documet /// </summary> protected MSXML2.IXMLDOMDocument document; /// <summary> /// Points to the element of the XML document /// </summary> protected MSXML2.IXMLDOMElement element; /// <summary> /// Points to the node of the XML /// </summary> protected MSXML2.IXMLDOMNode node, ChildNode; /// <summary> /// points to the node list of the XML document /// Stores the node list of the XML /// </summary> protected MSXML2.IXMLDOMNodeList nodeList; /// <summary> /// Stores the node map of the XML document /// </summary> protected MSXML2.IXMLDOMNamedNodeMap nodeMap; /// <summary> /// Default constructor /// </summary> public XMLParser() { } /// <summary> /// Initialize some important variables /// </summary> protected void InitVariables() { iTags=0; iCounter = 0; document = new MSXML2.DOMDocument(); } /// <summary> /// This function is responsible for parsing the XML /// Actually this function will call the exact parse function /// depending upon the type of XML Recieved /// </summary> /// <param name="XMLFilename"> </param> /// <param name="outStruct"> </param> /// <param name="TagName"> </param> public int ParseXML(string XMLFilename, out XMLSTRUCT outStruct, string TagName) { // Declare and initializes the iElements to 0 int iElements = 0; // Initializes the outStruct variable of this function // this structure is used to store the values of parsed XML outStruct = new XMLSTRUCT(); // The following 12 lines of code checks the Type of XML recieved // and calls are made to there corresponding parser function // which actually are reponsible for parsing the XML // all the parse functions are user defined functions // the Number of Parsed records are stores in the iElements // variable which is returned by the function if( 0 == TagName.CompareTo("AUTH") ) iElements = ParseAUTHXML(XMLFilename, out outStruct); else if( 0 == TagName.CompareTo("USERLIST") ) iElements = ParseUSERLISTXML(XMLFilename, out outStruct); else if( 0 == TagName.CompareTo("SHOWFILES") ) iElements = ParseSHOWFILESXML(XMLFilename, out outStruct); else if( 0 == TagName.CompareTo("SEARCH") ) iElements = ParseSHOWFILESXML(XMLFilename, out outStruct); else if( 0 == TagName.CompareTo("ERROR") ) iElements = ParseERRORXML(XMLFilename, out outStruct); else if( 0 == TagName.CompareTo("SERVERSEARCH") ) iElements = ParseSERVERSEARCHXML(XMLFilename, out outStruct); else if( 0 == TagName.CompareTo("CHAT") ) iElements = ParseCHATXML(XMLFilename, out outStruct); // Returns the iElements variable to the calling function return iElements; } protected int ParseCHATXML(string Filename, out XMLSTRUCT outStruct) { // initializes all the required variables InitVariables(); // Initialize outStruct variable of this function outStruct = new XMLSTRUCT(); // Process the XML document syncronously document.async = false; // load the xml document in memory for parsing if(document.load(Filename)) { // get the first element of the XML element = document.documentElement; // get the first child of the element node = element.firstChild; // extracts the node list present under the node nodeList = node.childNodes; // iTags will assigns to the number of nodes present // in node list iTags = nodeList.length; // Initialize the AUTH sructure of the outStruct // variable outStruct.MESSAGE = new XMLSTRUCT.__MESSAGE(); // move the node to the next node of the nodelist node = nodeList.nextNode(); // Extract each value from its specific node for(iCounter = 0; iCounter < iTags; iCounter++ ) { // gets the attribute map that is how many attributes // are present in the node nodeMap = node.attributes; // extract the next node from the node map ChildNode = nodeMap.nextNode(); // The following 9 lines of code will extract the // various attribute values from the XML node // and fills it to the outStruct's corresponding // structure do { if( 0 == ChildNode.nodeName.CompareTo("sendername") ) outStruct.MESSAGE.sSenderName = ChildNode.nodeValue.ToString(); else if( 0 == ChildNode.nodeName.CompareTo("chatmsg") ) outStruct.MESSAGE.sMessage = ChildNode.nodeValue.ToString(); else if( 0 == ChildNode.nodeName.CompareTo("ip") ) outStruct.MESSAGE.sIPAddress = ChildNode.nodeValue.ToString(); } while( null != (ChildNode = nodeMap.nextNode()) ); // now move to next node node = nodeList.nextNode(); } } // Return the number of nodes parsed for the values return iCounter==iTags?iCounter:0; } /// <summary> /// Actual Parsing of AUTHENTICATION XML /// </summary> /// <param name="Filename"> </param> /// <param name="outStruct"> </param> protected int ParseAUTHXML(string Filename, out XMLSTRUCT outStruct) { // initializes all the required variables InitVariables(); // Initialize outStruct variable of this function outStruct = new XMLSTRUCT(); // Process the XML document syncronously document.async = false; // load the xml document in memory for parsing if(document.load(Filename)) { // get the first element of the XML element = document.documentElement; // get the first child of the element node = element.firstChild; // extracts the node list present under the node nodeList = node.childNodes; // iTags will assigns to the number of nodes present // in node list iTags = nodeList.length; // Initialize the AUTH sructure of the outStruct // variable outStruct.AUTH = new XMLSTRUCT.__AUTHENTICATION(); // move the node to the next node of the nodelist node = nodeList.nextNode(); // Extract each value from its specific node for(iCounter = 0; iCounter < iTags; iCounter++ ) { // gets the attribute map that is how many attributes // are present in the node nodeMap = node.attributes; // extract the next node from the node map ChildNode = nodeMap.nextNode(); // The following 9 lines of code will extract the // various attribute values from the XML node // and fills it to the outStruct's corresponding // structure do { if( 0 == ChildNode.nodeName.CompareTo("code") ) outStruct.AUTH.iCode = Convert.ToInt32(ChildNode.nodeValue); else if( 0 == ChildNode.nodeName.CompareTo("status") ) outStruct.AUTH.sStatus = ChildNode.nodeValue.ToString(); else if( 0 == ChildNode.nodeName.CompareTo("ip") ) outStruct.AUTH.sIPAddress = ChildNode.nodeValue.ToString(); } while( null != (ChildNode = nodeMap.nextNode()) ); // now move to next node node = nodeList.nextNode(); } } // Return the number of nodes parsed for the values return iCounter==iTags?iCounter:0; } /// <summary> /// Actual Parsing of USERLIST XML /// </summary> /// <param name="Filename"> </param> /// <param name="outStruct"> </param> protected int ParseUSERLISTXML(string Filename, out XMLSTRUCT outStruct) { // initializes all the required variables InitVariables(); // Initialize outStruct variable of this function outStruct = new XMLSTRUCT(); // Process the XML document syncronously document.async = false; // load the xml document in memory for parsing if(document.load(Filename)) { // get the first element of the XML element = document.documentElement; // get the first child of the element node = element.firstChild; // extracts the node list present under the node nodeList = node.childNodes; // iTags will assigns to the number of nodes present // in node list iTags = nodeList.length; // Initialize the USERLIST sructure of the outStruct // variable outStruct.USERLIST = new XMLSTRUCT.__USERLIST[iTags]; // move the node to the next node of the nodelist node = nodeList.nextNode(); // Extract each value from its specific node for(iCounter = 0; iCounter < iTags; iCounter++ ) { // gets the attribute map that is how many attributes // are present in the node nodeMap = node.attributes; // extract the next node from the node map ChildNode = nodeMap.nextNode(); // The following 9 lines of code will extract the // various attribute values from the XML node // and fills it to the outStruct's corresponding // structure do { if( 0 == ChildNode.nodeName.CompareTo("username") ) outStruct.USERLIST[iCounter].sUsername = ChildNode.nodeValue.ToString(); else if( 0 == ChildNode.nodeName.CompareTo("ip") ) outStruct.USERLIST[iCounter].sIPAddress = ChildNode.nodeValue.ToString(); } while( null != (ChildNode = nodeMap.nextNode()) ); // now move to next node node = nodeList.nextNode(); } } // Return the number of nodes parsed for the values return iCounter==iTags?iCounter:0; } /// <summary> /// Actual Parsing of SERVERSEARCH XML /// </summary> /// <param name="Filename"> </param> /// <param name="outStruct"> </param> protected int ParseSERVERSEARCHXML(string Filename, out XMLSTRUCT outStruct) { // initializes all the required variables InitVariables(); // Initialize outStruct variable of this function outStruct = new XMLSTRUCT(); // Process the XML document syncronously document.async = false; // load the xml document in memory for parsing if(document.load(Filename)) { // get the first element of the XML element = document.documentElement; // get the first child of the element node = element.firstChild; // extracts the node list present under the node nodeList = node.childNodes; // iTags will assigns to the number of nodes present // in node list iTags = nodeList.length; // Initialize the SERVERSEARCH sructure of the outStruct // variable outStruct.SERVERSEARCH = new XMLSTRUCT.__SERVERSEARCH[iTags]; // move the node to the next node of the nodelist node = nodeList.nextNode(); // Extract each value from its specific node for(iCounter = 0; iCounter < iTags; iCounter++ ) { // gets the attribute map that is how many attributes // are present in the node nodeMap = node.attributes; // extract the next node from the node map ChildNode = nodeMap.nextNode(); // The following 9 lines of code will extract the // various attribute values from the XML node // and fills it to the outStruct's corresponding // structure do { if( 0 == ChildNode.nodeName.CompareTo("ip") ) outStruct.SERVERSEARCH[iCounter].sIPAddress = ChildNode.nodeValue.ToString(); else if( 0 == ChildNode.nodeName.CompareTo("username") ) outStruct.SERVERSEARCH[iCounter].sUsername = ChildNode.nodeValue.ToString(); else if( 0 == ChildNode.nodeName.CompareTo("filename") ) outStruct.SERVERSEARCH[iCounter].sFilename = ChildNode.nodeValue.ToString(); } while( null != (ChildNode = nodeMap.nextNode()) ); // now move to next node node = nodeList.nextNode(); } } // Return the number of nodes parsed for the values return iCounter==iTags?iCounter:0; } /// <summary> /// Actual Parsing of SHOWFILES XML /// </summary> /// <param name="Filename"> </param> /// <param name="outStruct"> </param> protected int ParseSHOWFILESXML(string Filename, out XMLSTRUCT outStruct) { // initializes all the required variables InitVariables(); // Initialize outStruct variable of this function outStruct = new XMLSTRUCT(); // Process the XML document syncronously document.async = false; // load the xml document in memory for parsing if(document.load(Filename)) { // get the first element of the XML element = document.documentElement; // get the first child of the element node = element.firstChild; // extracts the node list present under the node nodeList = node.childNodes; // iTags will assigns to the number of nodes present // in node list iTags = nodeList.length; // Initialize the SHOWFILES sructure of the outStruct // variable outStruct.SHOWFILES = new XMLSTRUCT.__SHOWFILES[iTags]; // move the node to the next node of the nodelist node = nodeList.nextNode(); // Extract each value from its specific node for(iCounter = 0; iCounter < iTags; iCounter++ ) { // gets the attribute map that is how many attributes // are present in the node nodeMap = node.attributes; // extract the next node from the node map ChildNode = nodeMap.nextNode(); // The following 9 lines of code will extract the // various attribute values from the XML node // and fills it to the outStruct's corresponding // structure do { if( 0 == ChildNode.nodeName.CompareTo("filename") ) outStruct.SHOWFILES[iCounter].sFilename = ChildNode.nodeValue.ToString(); else if( 0 == ChildNode.nodeName.CompareTo("mask") ) outStruct.SHOWFILES[iCounter].iMask = Convert.ToInt32(ChildNode.nodeValue); else if( 0 == ChildNode.nodeName.CompareTo("filesize") ) outStruct.SHOWFILES[iCounter].iFileSize = Convert.ToInt32(ChildNode.nodeValue); } while( null != (ChildNode = nodeMap.nextNode()) ); // now move to next node node = nodeList.nextNode(); } } // Return the number of nodes parsed for the values return iCounter==iTags?iCounter:0; } /// <summary> /// Actual Parsing of ERROR XML /// </summary> /// <param name="Filename"> </param> /// <param name="outStruct"> </param> protected int ParseERRORXML(string Filename, out XMLSTRUCT outStruct) { // initializes all the required variables InitVariables(); // Initialize outStruct variable of this function outStruct = new XMLSTRUCT(); // Process the XML document syncronously document.async = false; // load the xml document in memory for parsing if(document.load(Filename)) { // get the first element of the XML element = document.documentElement; // get the first child of the element node = element.firstChild; // extracts the node list present under the node nodeList = node.childNodes; // iTags will assigns to the number of nodes present // in node list iTags = nodeList.length; // Initialize the ERROR sructure of the outStruct // variable outStruct.ERROR = new XMLSTRUCT.__ERROR(); // move the node to the next node of the nodelist node = nodeList.nextNode(); // Extract each value from its specific node for(iCounter = 0; iCounter < iTags; iCounter++ ) { // gets the attribute map that is how many attributes // are present in the node nodeMap = node.attributes; // extract the next node from the node map ChildNode = nodeMap.nextNode(); // The following 9 lines of code will extract the // various attribute values from the XML node // and fills it to the outStruct's corresponding // structure do { if( 0 == ChildNode.nodeName.CompareTo("errorcode") ) outStruct.ERROR.iErrCode = Convert.ToInt32(ChildNode.nodeValue); else if( 0 == ChildNode.nodeName.CompareTo("severity") ) outStruct.ERROR.sSeverity = ChildNode.nodeValue.ToString(); else if( 0 == ChildNode.nodeName.CompareTo("description") ) outStruct.ERROR.sDescription = ChildNode.nodeValue.ToString(); } while( null != (ChildNode = nodeMap.nextNode()) ); // now move to next node node = nodeList.nextNode(); } } // Return the number of nodes parsed for the values return iCounter==iTags?iCounter:0; } } }
7689200a1373c15b59bce71a21fb5a94d300052b
C#
ovpoddar/Shop
/Test/Shop.Tests/HandlersTests/WholesaleTest.cs
2.609375
3
using DataAccess.Entities; using DataAccess.Repositories; using Moq; using Shop.Handlers; using Shop.ViewModels; using System.Collections.Generic; using System.Linq; using Xunit; namespace Shop.Tests.HandlersTests { public class WholesaleTest { private readonly Mock<IGenericRepository<WholesaleSize>> _mock; private readonly Mock<IGenericRepository<ProductWholeSale>> _mockcon; private readonly WholesaleHandler _wholesaleHandler; public WholesaleTest() { _mock = new Mock<IGenericRepository<WholesaleSize>>(); _mockcon = new Mock<IGenericRepository<ProductWholeSale>>(); _wholesaleHandler = new WholesaleHandler(_mock.Object, _mockcon.Object); } [Theory] [InlineData(1, 1, 6)] [InlineData(5, 40, 90)] public void GetId_ReturnAll(int id, int size, int pack) { _mock .Setup(e => e.GetAll()) .Returns(new List<WholesaleSize> { new WholesaleSize() { Id = id, Size = size, Package = pack } }.AsQueryable()); var result = _wholesaleHandler.GetId(size, pack); Assert.Equal(result, id); } [Theory] [InlineData(1, 1, false)] [InlineData(6, 25, true)] public void Add_checkingbothSituation(int addsi, int addpa, bool type) { _mock .Setup(e => e.GetAll()) .Returns(new List<WholesaleSize> { new WholesaleSize() { Id = 1, Size = 1, Package = 1 }, new WholesaleSize() { Id = 2, Size = 2, Package = 2 }, }.AsQueryable()); _mock .Setup(e => e.Add(It.IsAny<WholesaleSize>())); if (type) Assert.True(_wholesaleHandler.Add(new WholeSaleViewModel() { Size = addsi, Package = addpa })); else Assert.False(_wholesaleHandler.Add(new WholeSaleViewModel() { Size = addsi, Package = addpa })); } } }
cc1d5b5d2a2a9bb364c22b491f2899a65fb592b0
C#
medjedovic/WpfCRUD
/WpfCRUD/MainWindow.xaml.cs
2.515625
3
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; /* Sistematizacija prvog dijela kursa iz C# WPF-a CRUD - unos, prikaz, izmjena, brisanje i pretraga podataka za artikle, urađen. CRUD za korisnike sa login provjerom ostala validacija sa FLUENTValidatorom da se imlementira u XAML-u */ namespace WpfCRUD { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window, INotifyPropertyChanged { //observable collection je mnogo bolji za komunikaciju i senzitivniji na promene u toj kolekciji //ObservableCollection<clsArtikal> lstArt = new ObservableCollection<clsArtikal>(); clsEF db = new clsEF(); private int _tSifra; public int tSifra { get => _tSifra; set { _tSifra = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("tSifra")); } } private int _tKol; public int tKol { get => _tKol; set { _tKol = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("tKol")); } } public event PropertyChangedEventHandler PropertyChanged; public clsRacun tRacun = new clsRacun(); private string _pretraga { get; set; } public string pretraga { get => _pretraga; set { _pretraga = value; if (string.IsNullOrWhiteSpace(_pretraga)) { dgArtikli.ItemsSource = db.artikals.ToList(); } else { dgArtikli.ItemsSource = db.artikals.Where(a => a.naziv.Contains(_pretraga.Trim())).ToList(); } } } clsArtikal sa = null; public MainWindow() { InitializeComponent(); //dgArtikli.ItemsSource = lstArt; DataContext = this; dgArtikli.ItemsSource = db.artikals.ToList(); //snimamo bazu kako bi kreirao id racuna //db.SaveChanges(); //foreach (clsArtikal a in db.artikals.ToList()) //{ // db.artkols.Add(new clsArtKol(a, 2)); //} //clsRacun r = new clsRacun(); //db.racuni.Add(r); //db.artkols.ToList().ForEach(ak => r.listaArt.Add(ak)); //db.SaveChanges(); //local observable collection //dgArtikli.ItemsSource = db.artikals.Local; //dgStavke.ItemsSource = tRacun.listaArt; UnosRac.BindingGroup = new BindingGroup(); db.racuni.ToList(); dgRacuni.ItemsSource = db.racuni.Local; } private void btnA(object sender, RoutedEventArgs e) { WinAE ae = new WinAE(); ae.Owner = this; //obzirom da bool nije nullabilan (ne može biti null) koristimo ? npr //ae.ShowDialog() == true ae.ShowDialog().Value if (ae.ShowDialog() == true) { //lstArt.Add(ae.DataContext as clsArtikal); db.artikals.Add(ae.DataContext as clsArtikal); //snimi podatke koji su dodani db.SaveChanges(); //učitaj ponovo u datageid listu artikala dataseta dgArtikli.ItemsSource = db.artikals.ToList(); } else MessageBox.Show("Odustali ste od unosa podataka!"); } private void btnE(object sender, RoutedEventArgs e) { if(sa != null) { WinAE ae = new WinAE(); ae.Owner = this; ae.DataContext = dgArtikli.SelectedItem; ae.ShowDialog(); db.SaveChanges(); //dgArtikli.ItemsSource = db.artikals.ToList(); } } private void btnD(object sender, RoutedEventArgs e) { if (sa != null) { MessageBoxResult result = MessageBox.Show("Da li stvarno želiš da obrišeš selektovani podatak?", "Delete", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes); if (result == MessageBoxResult.Yes) { //lstArt.Remove(dgArtikli.SelectedItem as clsArtikal); //kod asp.net-a //db.artikals.Remove(db.artikals.Where(a => a.Equals(dgArtikli.SelectedItem)).FirstOrDefault()); db.artikals.Remove(sa); db.SaveChanges(); dgArtikli.ItemsSource = db.artikals.ToList(); } } } private void btnKorisnik(object sender, RoutedEventArgs e) { WinKAELogin ae = new WinKAELogin(); ae.Owner = this; ae.ShowDialog(); } private void dgArtikliSelektovano(object sender, SelectionChangedEventArgs e) { if (dgArtikli.SelectedItem != null) { sa = dgArtikli.SelectedItem as clsArtikal; } else sa = null; } private void btnUnosStavke(object sender, RoutedEventArgs e) { if (UnosRac.BindingGroup.CommitEdit()) { var art = db.artikals.Find(tSifra); if (art != null) { var ak = new clsArtKol(art, tKol); tRacun.listaArt.Add(ak); //db.artkols.Add(ak); //db.racuni.Add(tRacun); //db.SaveChanges(); dgStavke.ItemsSource = null; dgStavke.ItemsSource = tRacun.listaArt; tKol = 0; tSifra = 0; //tRacun = new clsRacun(); } else { MessageBox.Show("Artikal ne postoji!"); } } else { MessageBox.Show("Proverite podatke!"); } } private void btnIzdajRacun(object sender, RoutedEventArgs e) { tRacun.vrijemeIzdavanja = DateTime.Now; tRacun.listaArt.ForEach(ak => db.artkols.Add(ak)); db.racuni.Add(tRacun); db.SaveChanges(); tRacun = new clsRacun(); dgStavke.ItemsSource = null; } } }
10e48756e5fe30973ea020ded7b5cc48b0a12284
C#
Anzzhhela98/CSharp-Fundamentals
/Data Types and Variables/Data Types and Variables - Lab/02. Pounds to Dollars/Program.cs
3.109375
3
using System; namespace _02._Pounds_to_Dollars { class Program { static void Main(string[] args) { decimal pouds = decimal.Parse(Console.ReadLine()); decimal leva = pouds *(decimal) 1.31; Console.WriteLine($"{leva:f3}"); } } }
885f54a57b3410934f42ad21bd8a289748b50e36
C#
Smoggert/BubbleShooter
/BubbleShooter/BubbleShooter/BubbleShooter/Classes/Side.cs
2.890625
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using BubbleShooter; namespace BubbleShooter.Classes { class Side { Vector2 normal; float distance; public Side(float distance , Vector2 normal) { this.distance = distance; this.normal = Vector2.Normalize(normal); } public virtual Vector2 Normal { get { return normal; } } public virtual float Distance { get { return distance; } } } class SpeedSide : Side { Vector2 speedSetter; public SpeedSide(float distance, Vector2 normal) : base(distance, normal) { this.speedSetter = new Vector2(0,0); } public SpeedSide(float distance, Vector2 normal, Vector2 speedSetter) : base(distance, normal) { this.speedSetter = speedSetter; } public Vector2 SpeedSetter { get { return speedSetter; } } } }
de1ef5223d07393c43de2371afef2dd3f22dc1de
C#
prasanjeetd/dotnet-core
/Practice.Classlibrary/Data Structures/TreeTraverseEfficient.cs
3.71875
4
using System; using System.Collections.Generic; using System.Text; namespace Practice.Classlibrary.Data_Structures { //https://www.geeksforgeeks.org/level-order-tree-traversal/ public class TreeTraverseEfficient { public void Traverse(Tree tree) { Queue<Tree> Q = new Queue<Tree>(); Q.Enqueue(tree); int h = 0; Queue<int> values = new Queue<int>(); while (Q.Count != 0) { Tree node = Q.Dequeue(); Console.WriteLine("Tree value ->" + node.value); //values.Enqueue(node.value); //h++; if (node.left != null) { Q.Enqueue(node.left); } if (node.right != null) { Q.Enqueue(node.right); } } } void PrintTree(Queue<int> treeVals, int h) { } } }
ff41d70f2cf8d78783ae89ff7ddcdcd4e774bc43
C#
mbarnes16/TicketingSystem-With-Classes
/Display.cs
3.390625
3
using System; using System.IO; namespace TicketingSystem { public class Display { public void menuChoice(){ Console.WriteLine("1) Read data from file."); Console.WriteLine("2) Create file from data."); Console.WriteLine("Enter any other key to exit."); } public void fileDoesNotExist() { Console.WriteLine("The file does not exsist. "); } public void newTicket() { Console.WriteLine("Would you like to create a new ticket? (Y/N): "); } public void ticketInformation(Ticket ticket) { Console.WriteLine("Ticket ID: {0}\nSummary: {1}\nStatus: {2}\nPriority: {3}\nSubmitter: {4}\nAssigned: {5}\nWatching: {6}\n",ticket.ticketID, ticket.summary, ticket.status, ticket.priority, ticket.submitter, ticket.assigned, ticket.watching); } } }
6b4b097acd58ed4833ef482f7fb026865513d429
C#
EdLichtman/HelloAzureCI
/HelloAzureCIUnitTests/ConnectionStrings.cs
2.671875
3
using System; using System.Configuration; using NUnit.Framework; namespace HelloAzureCIUnitTests { [TestFixture] public class ConnectionStrings { [Test] public void Should_not_be_null() { string testConnectionString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString; Assert.That(testConnectionString, Is.Not.EqualTo(null)); } [Test] public void Should_be_specific_to_Azure_environment() { string testConnectionString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString; Assert.That(testConnectionString, Is.Not.EqualTo("Azure")); } [Test] public void Should_run_Assert_That_and_Is_EqualTo_without_any_problems() { try { Assert.That(1, Is.EqualTo(1)); } catch (Exception e) { throw new Exception("Failed asserting that 1 Is.EqualTo(1), must be Assert.That or the Is.* that's failing", e.InnerException); } } [Test] public void Should_run_Assert_without_any_problems() { try { Assert.AreEqual(1, 1); } catch (Exception e) { throw new Exception("Failed asserting that AreEqual(1, 1), must be Assert that's failing", e.InnerException); } } } }
cd9ee854956b9dd2216fe5cf41552ba7f93fcb54
C#
a498497672/Code-TicketOTA2
/Ticket.Infrastructure.KouDaiLingQian/Lib/SecretUtilTools.cs
2.734375
3
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace Ticket.Infrastructure.KouDaiLingQian.Lib { public class SecretUtilTools { /// <summary> /// 加密 /// </summary> /// <param name="message"></param> /// <param name="key"></param> /// <returns></returns> public static string EncryptForDes(string message, string key) { using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte[] inputByteArray = Encoding.UTF8.GetBytes(message); des.Key = UTF8Encoding.UTF8.GetBytes(key); des.IV = UTF8Encoding.UTF8.GetBytes(key); des.Mode = System.Security.Cryptography.CipherMode.ECB; System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Convert.ToBase64String(ms.ToArray()); ms.Close(); return str; } } /// <summary> /// 解密 /// </summary> /// <param name="message"></param> /// <param name="key"></param> /// <returns></returns> public static string DecryptForDes(string message, string key) { byte[] inputByteArray = Convert.FromBase64String(message); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = UTF8Encoding.UTF8.GetBytes(key); des.IV = UTF8Encoding.UTF8.GetBytes(key); des.Mode = System.Security.Cryptography.CipherMode.ECB; System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return str; } } } }
8d08e208cfe9296ec823a8aa64b76c9feda79a1b
C#
dave/dontstayin
/Spotted/Js/Desktop/ClientControls/SuggestionsCollection.cs
2.796875
3
using System; using Js.Library; using Js.AutoCompleteLibrary; namespace Js.ClientControls { public delegate void SuggestionsChanged(); public class SuggestionsCollection { public SuggestionsChanged OnSuggestionsChanged = null; Array suggestions = new Array(); public void Add(Suggestion newSuggestion) { AddWithoutSortOrNotify(newSuggestion); Sort(); if (OnSuggestionsChanged != null) OnSuggestionsChanged(); } private void AddWithoutSortOrNotify(Suggestion newSuggestion) { int i = 0; for (i = 0; i < suggestions.Length; i++) { Suggestion current = (Suggestion)suggestions[i]; if (current.value == newSuggestion.value) { if (newSuggestion.priority < current.priority) { newSuggestion.priority = current.priority; } break; } } suggestions[i] = newSuggestion; } public void AddRange(Suggestion[] newSuggestions) { for (int i = 0; i < newSuggestions.Length; i++) { AddWithoutSortOrNotify(newSuggestions[i]); } Sort(); if (OnSuggestionsChanged != null) OnSuggestionsChanged(); } private void Sort() { suggestions.Sort ( delegate(object a, object b) { return ((Suggestion)b).priority - ((Suggestion)a).priority; } ); } public Suggestion this[int index] { get { return ((Suggestion)suggestions[index]); } } public void RemoveAt(int index) { int length = suggestions.Length; Array newSuggestions = new Array(); for (int i = 0; i < suggestions.Length; i++) { if (i == index) { continue; } newSuggestions[newSuggestions.Length] = suggestions[i]; } suggestions = newSuggestions; if (length != suggestions.Length && OnSuggestionsChanged != null) OnSuggestionsChanged(); } public void Clear() { suggestions = new Array(); } public int Count { get { return suggestions.Length; } } } }
4b53d901704635270d81126ae485ab5039314c06
C#
ehonda/Malefics
/MaleficsTest/Game/Dice/Mocks/DieMocks.cs
2.8125
3
using CyclicEnumerables; using Malefics.Game.Dice; using Moq; using System.Collections.Generic; namespace MaleficsTests.Game.Dice.Mocks { public static class DieMocks { public static Mock<IDie> Cyclic(IEnumerable<uint> rolls) { var mock = new Mock<IDie>(); // TODO: Why do we get ReSharper warning about disposing enumerator, do we need to fix it? var rollEnumerator = rolls.Cycle().GetEnumerator(); mock .Setup(die => die.Roll()) .Returns(() => { rollEnumerator.MoveNext(); return rollEnumerator.Current; }); return mock; } } }
2c76b4d48090e2fdf129f69af558ce71f1ee88ee
C#
samadhicsec/CipherSandbox
/UnitTests/RandomSwapImplTests.cs
2.875
3
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Security.Cryptography; using Ciphers; using NSubstitute; namespace UnitTests { [TestClass] public class RandomSwapImplTests { [TestMethod] [ExpectedException(typeof(ArgumentException), "A zero length input was allowed")] public void Test0LengthInput() { // Arrange byte[] input = new byte[0]; RandomSwapImpl rsi = new RandomSwapImpl(); // Act byte[] output = rsi.Swap(input, 0, input.Length); // Assert } [TestMethod] [ExpectedException(typeof(ArgumentException), "An odd length input was allowed")] public void TestOddLengthInput() { // Arrange byte[] input = new byte[1]; RandomSwapImpl rsi = new RandomSwapImpl(); // Act byte[] output = rsi.Swap(input, 0, input.Length); // Assert } [TestMethod] public void TestNoSwap() { // Arrange byte[] input = new byte[10]; (new RNGCryptoServiceProvider()).GetBytes(input); var _rng = Substitute.For<RandomNumberGenerator>(); _rng.When(x => x.GetBytes(Arg.Any<byte[]>())).Do(x => ((byte[])x[0])[0] = 0); RandomSwapImpl rsi = new RandomSwapImpl(_rng); // Act byte[] output = rsi.Swap(input, 0, input.Length); // Assert CollectionAssert.AreEqual(input, output, "Input was " + Environment.NewLine + Helper.ByteArrayToString(input) + Environment.NewLine + "Output was" + Environment.NewLine + Helper.ByteArrayToString(output)); } [TestMethod] public void TestSwap() { // Arrange byte[] input = new byte[10]; (new RNGCryptoServiceProvider()).GetBytes(input); var _rng = Substitute.For<RandomNumberGenerator>(); _rng.When(x => x.GetBytes(Arg.Any<byte[]>())).Do(x => ((byte[])x[0])[0] = 1); RandomSwapImpl rsi = new RandomSwapImpl(_rng); // Act byte[] output = rsi.Swap(input, 0, input.Length); byte[] input_firsthalf = new byte[input.Length / 2]; byte[] input_secondhalf = new byte[input.Length / 2]; Buffer.BlockCopy(input, 0, input_firsthalf, 0, input.Length / 2); Buffer.BlockCopy(input, input.Length / 2, input_secondhalf, 0, input.Length / 2); byte[] output_firsthalf = new byte[output.Length / 2]; byte[] output_secondhalf = new byte[output.Length / 2]; Buffer.BlockCopy(output, 0, output_firsthalf, 0, output.Length / 2); Buffer.BlockCopy(output, output.Length / 2, output_secondhalf, 0, output.Length / 2); // Assert CollectionAssert.AreEqual(input_firsthalf, output_secondhalf, "Input first half != Output second half. Input was " + Environment.NewLine + Helper.ByteArrayToString(input) + Environment.NewLine + "Output was" + Environment.NewLine + Helper.ByteArrayToString(output)); CollectionAssert.AreEqual(input_secondhalf, output_firsthalf, "Input second half != Output first half. Input was " + Environment.NewLine + Helper.ByteArrayToString(input) + Environment.NewLine + "Output was" + Environment.NewLine + Helper.ByteArrayToString(output)); } } }
b1bf78e92192399f2cb7224c08f8f0813af0f831
C#
imkaef/PakPs
/ПАК ПС/ПАК ПС/Manipulator.cs
3.203125
3
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; namespace ПАК_ПС { class Manipulator : Figure { public Figure selected; int active_point = -1; public override bool Touch(float ax, float ay)//Определяем куда ткнули в какую точку объекта { if (selected == null) { active_point = -1; return false; } if (Math.Abs(ax - X) < 3 && (Math.Abs(ay - Y) < 3)) { active_point = 1; return true; } if (Math.Abs(ax - W - X) < 3 && (Math.Abs(ay - Y) < 3)) { active_point = 2; return true; } if (Math.Abs(ax - X) < 3 && (Math.Abs(ay - H - Y) < 3)) { active_point = 3; return true; } if (Math.Abs(ax - W - X) < 3 && (Math.Abs(ay - H - Y) < 3)) { active_point = 4; return true; } if (selected.Touch(ax, ay)) { active_point = 0; return true; } active_point = -1; return false; } public void Drag(float dx, float dy)//Определяем за какую точку тянем { switch (active_point) { case 0: Move(X + dx, Y + dy); break; case 1: Move(X+dx , Y+dy); Resize(W-dx, H-dy); break; case 2: Move(X, Y + dy); Resize(W + dx, H - dy); break; case 3: Move(X + dx, Y); Resize(W-dx , H+dy ); break; case 4: Resize(W + dx, H + dy); break; } } public void Attach(Figure f)//Выделяем квадратом выделенный объект { selected = f; if (selected != null) { Move(f.X, f.Y); Resize(f.W, f.H); } } public void Update() { if (selected != null) { selected.Move(X, Y); selected.Resize(W, H); } } public override void Draw(Graphics g) { if (selected != null) g.DrawRectangle(new Pen(Color.Black), X - 2, Y - 2, W + 4, H + 4); } } }
00d99756c7873b29bb2bd6d1bb497ccaf9591954
C#
archangelmichael/CSharpPart2
/C Sharp Part 2 Homework/08. StringAndTextProcessing/12. URLExtraction/URLExtraction.cs
3.734375
4
using System; using System.Text.RegularExpressions; /* Write a program that parses an URL address given in the format: * [protocol]://[server]/[resource] * and extracts from it the [protocol], [server] and [resource] elements. * For example from the URL http://www.devbg.org/forum/index.php * the following information should be extracted: * [protocol] = "http" * [server] = "www.devbg.org" * [resource] = "/forum/index.php" */ class URLExtraction { static void GetURLElements(string input) { var elements = Regex.Match(input, "(.*)://(.*?)(/.*)").Groups; Console.WriteLine(elements[1]); Console.WriteLine(elements[2]); Console.WriteLine(elements[3]); } static void Main() { string url = Console.ReadLine(); GetURLElements(url); } }
55be62bb0550b4d06678b6252a548e428660a9f9
C#
mlwalters/csharp-lesson1-studio
/Class1Studio/Program.cs
3.921875
4
using System; namespace Class1Studio { public class Program { public static void Main() { Console.WriteLine("Enter a radius:"); string inputRadius = Console.ReadLine(); double radius = double.Parse(inputRadius); while (radius < 0) { Console.WriteLine("Enter a positive number for the radius:"); inputRadius = Console.ReadLine(); radius = double.Parse(inputRadius); } Console.WriteLine($"The area of a circle of radius {radius} is : {Math.PI * radius * radius}"); Console.WriteLine($"The circumference of radius {radius} is: {2 * Math.PI * radius}"); Console.WriteLine($"The diameter of the circle is: {2 * radius}"); Console.WriteLine("Enter your car's miles per gallon:"); string inputMpg = Console.ReadLine(); double mpg = double.Parse(inputMpg); Console.WriteLine($"Your car's mpg is {mpg}mpg."); double gallons = (2 * Math.PI * radius) / mpg; Console.WriteLine($"\nYour car will use {gallons} gallons of gas to go around a circle."); } } }
a86ed8a9d50176e144c2fa1b775c4c8939bfb609
C#
Sourav159/Bank-System
/Bank.cs
3.65625
4
using System; using System.Collections.Generic; using System.Text; namespace BankSystem { //Bank class class Bank { //Instance variable List<Transaction> _transactions; List<Account> _accounts; //Read-only property for _transactions public List<Transaction> Transactions { get { return _transactions; } } //Constructor public Bank() { _transactions = new List<Transaction>(); _accounts = new List<Account>(); } //Methods //Method to add an account into the _accounts list public void AddAccount(Account account) { _accounts.Add(account); } //Method to return the account for the given name public Account GetAccount(String name) { for (int i = 0; i < _accounts.Count; i++) { if (_accounts[i].Name == name) return _accounts[i]; } return null; } //Method to execute the transaction and print the result public void ExecuteTransaction(Transaction transaction) { _transactions.Add(transaction); transaction.Execute(); transaction.Print(); } //Method to rollback the transaction public void RollbackTransaction(Transaction transaction) { transaction.Rollback(); } //Method to print the transaction history public void PrintTransactionHistory() { for(int i = 0; i < _transactions.Count; i++) { Console.Write(i+1 + ": "); _transactions[i].Print(); Console.WriteLine(" - " + _transactions[i].DateStamp); } } } }
51757a73427416ac556eebd252ad713bf0cc8ddd
C#
Omar-Salem/Dijkstra-s-Algorithm
/DijkstrasAlgorithm/Services/ShortestPath.cs
3.1875
3
using System.Collections.Generic; using System.Linq; using Entities; namespace Services { public class ShortestPath : IShortestPath { #region Member Variables Dictionary<string, Node> _matrix; HashSet<Node> _visitedNodes; #endregion #region Constructor public ShortestPath(IEnumerable<Edge> graph) { _matrix = CreateMatrix(graph); _visitedNodes = new HashSet<Node>(); } #endregion #region Public Methods IList<List<Edge>> IShortestPath.GetShortestPath(string source, string destination) { _matrix[source].CostFromSource = 0; _visitedNodes.Add(_matrix[source]); Node destinationNode = _matrix[destination]; Node minimumNode = new Node(); var edges = new List<List<Edge>>(); while (!_visitedNodes.Contains(destinationNode)) { minimumNode = GetMinimumNode(); if (minimumNode.Label == null)//No Path exists { return edges; } _visitedNodes.Add(minimumNode); } edges.Add(new List<Edge>()); GetPaths(source, minimumNode, edges, edges.Count - 1); return edges; } #endregion #region Public Properties Dictionary<string, Node> IShortestPath.Matrix { get { return _matrix; } set { _matrix = value; ; } } #endregion #region Private Methods private Dictionary<string, Node> CreateMatrix(IEnumerable<Edge> graph) { var matrix = new Dictionary<string, Node>(); foreach (var edge in graph) { Node firstVertex; if (!matrix.ContainsKey(edge.Start)) { firstVertex = new Node { Label = edge.Start, Neighbors = new Dictionary<string, int>() }; matrix.Add(edge.Start, firstVertex); } firstVertex = matrix[edge.Start]; Node secondVertex; if (!matrix.ContainsKey(edge.End)) { secondVertex = new Node { Label = edge.End, Neighbors = new Dictionary<string, int>() }; matrix.Add(edge.End, secondVertex); } secondVertex = matrix[edge.End]; if (!firstVertex.Neighbors.ContainsKey(secondVertex.Label)) { firstVertex.Neighbors.Add(secondVertex.Label, edge.Cost); } if (!secondVertex.Neighbors.ContainsKey(firstVertex.Label)) { secondVertex.Neighbors.Add(firstVertex.Label, edge.Cost); } } return matrix; } private Node GetMinimumNode() { var minimumNodeSoFar = new Node(); foreach (Node currentNode in _visitedNodes) { IEnumerable<Node> unVisitedNeighbors = GetUnVisitedNeighbors(currentNode); if (unVisitedNeighbors.Any()) { RelaxNeighboringNodes(currentNode, unVisitedNeighbors); Node minimumNodeEndingHere = unVisitedNeighbors.Aggregate((a, b) => a.CostFromSource < b.CostFromSource ? a : b); if (!minimumNodeSoFar.CostFromSource.HasValue || minimumNodeSoFar.CostFromSource > minimumNodeEndingHere.CostFromSource) { minimumNodeSoFar = minimumNodeEndingHere; } } } return minimumNodeSoFar; } private IEnumerable<Node> GetUnVisitedNeighbors(Node currentNode) { IEnumerable<Node> unVisitedNeighbors = currentNode.Neighbors .Where(n => !_visitedNodes.Contains(new Node { Label = n.Key })) .Select(n => _matrix[n.Key]); return unVisitedNeighbors; } private void RelaxNeighboringNodes(Node currentNode, IEnumerable<Node> unVisitedNeighbors) { foreach (Node neighbor in unVisitedNeighbors) { int? newCost = currentNode.CostFromSource + currentNode.Neighbors[neighbor.Label]; if (neighbor.CostFromSource.HasValue) { if (newCost < neighbor.CostFromSource) { neighbor.CostFromSource = newCost; neighbor.Parents = new HashSet<Node> { currentNode }; } else if (newCost == neighbor.CostFromSource && !neighbor.Parents.Contains(currentNode))//in case of tie { neighbor.Parents.Add(currentNode); } } else { neighbor.CostFromSource = newCost; neighbor.Parents = new HashSet<Node> { currentNode }; } } } private void GetPaths(string source, Node destination, List<List<Edge>> edges, int level) { if (destination.Parents == null) { return; } int i = 0; List<Edge> routeCopy = new List<Edge>(edges[level]);//make a copy of the current route foreach (Node originNode in destination.Parents) { if (i > 0)//only branch after first edge, as first edge is added to default route { edges.Add(routeCopy); level++; } var edge = new Edge { Start = originNode.Label, End = destination.Label, Cost = _matrix[originNode.Label].Neighbors[destination.Label] }; edges[level].Add(edge); GetPaths(source, originNode, edges, level); i++; } } #endregion } }
3b46e34ff4cbbf6fbee121a6b34fa9b8e47238f4
C#
dixon01/Dev-Jasper
/backend/Center/Media/Source/Core/Converters/ResourceProgressConverter.cs
2.625
3
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ResourceProgressConverter.cs" company="Gorba AG"> // Copyright © 2011-2014 Gorba AG. All rights reserved. // </copyright> // <summary> // Defines the ResourceProgressConverter type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Gorba.Center.Media.Core.Converters { using System; using System.Globalization; using System.Linq; using System.Windows.Data; /// <summary> /// The ResourceProgressConverter /// </summary> public class ResourceProgressConverter : IMultiValueConverter { /// <summary> /// Returns the progress in percent /// </summary> /// <param name="values"> /// the values; value[0]: current resource number, value[1]: previous number, value[2]: total resources /// </param> /// <param name="targetType">the target type</param> /// <param name="parameter">the parameter</param> /// <param name="culture">the culture</param> /// <returns>The progress in percent; 0 if the values are not of type int</returns> public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { if (values.Count() >= 2 && values[0] is double && values[1] is int) { var currentResource = (double)values[0]; var total = (int)values[1]; if (total > 0) { var result = (currentResource * 100) / total; return result; } } return 0d; } /// <summary> /// not implemented /// </summary> /// <param name="value">the value</param> /// <param name="targetTypes">the target types</param> /// <param name="parameter">the parameter</param> /// <param name="culture">the culture</param> /// <returns>the result</returns> public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
9da5e1f63f0ff201684b834bee707c0eff03309f
C#
mattgwagner/Distance-Analyzer
/src/Distance-Analyzer/Models/Node.cs
3
3
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Distance_Analyzer.Models { public class Node { public string id { get; set; } = Guid.NewGuid().ToString(); /// <summary> /// A generic description, i.e. name, for the node /// </summary> public String Description { get; set; } /// <summary> /// The node's raw address entry /// </summary> public String Raw { get; set; } /// <summary> /// The node's scrubbed address /// </summary> public String Address { get; set; } public Double Latitude { get; set; } public Double Longitude { get; set; } /// <summary> /// A list of tags applied to this node for identification /// </summary> [NotMapped] public String[] Tags { get; set; } = new String[] { }; public String TagsList { get { return JsonConvert.SerializeObject(Tags); } set { Tags = JsonConvert.DeserializeObject<String[]>(value); } } /// <summary> /// True if the node should be considered a super node, where all other nodes are calculated in relation to /// </summary> [Display(Name = "Is a Super Node?")] public Boolean Is_Super_Node { get; set; } /// <summary> /// A list of distance mapping between this node and the super nodes /// </summary> [NotMapped] public ICollection<Distance> Mappings { get; set; } = new List<Distance>(); public String MappingsList { get { return JsonConvert.SerializeObject(Mappings); } set { Mappings = JsonConvert.DeserializeObject<List<Distance>>(value); } } } public sealed class Distance { /// <summary> /// Which node this mapped distance is in relation to /// </summary> public String To { get; set; } /// <summary> /// The calculated driving time under usual conditions to this node /// </summary [Display(Name = "Drive Time")] public TimeSpan Driving_Time { get; set; } /// <summary> /// The driving distance in miles to this node /// </summary> [Display(Name = "Distance (Meters)")] public Decimal Distance_Meters { get; set; } } }
74a9402603c9b7fe7be8d5d0d2c81739e2aa1c7d
C#
mahaisong/Batch
/BatchTestBL/Test2/Test2.cs
2.59375
3
using BatchFoundation.Worker; using Newtonsoft.Json; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace BatchTestBL.Test2 { public class MyWorker1 : Worker { public override void Run(BlockingCollection<object> Input, BlockingCollection<object> Output, ref object Data, bool IsTest) { Data = (object)((int)Data + 5); Console.WriteLine(DateTime.UtcNow + " - W1: " + Data); // just test that referencing Newtonsoft.JSON is not failing var json = JsonConvert.SerializeObject(null); } } public class MyWorker2 : Worker { public override void Run(BlockingCollection<object> Input, BlockingCollection<object> Output, ref object Data, bool IsTest) { Data = (object)((int)Data + 1); Console.WriteLine(DateTime.UtcNow + " - W2: " + Data); } } public class MyWorker3 : Worker { public override void Run(BlockingCollection<object> Input, BlockingCollection<object> Output, ref object Data, bool IsTest) { Data = (object)((int)Data + 1); Console.WriteLine(DateTime.UtcNow + " - W3: " + Data); } } public class MyWorker4 : Worker { public override void Run(BlockingCollection<object> Input, BlockingCollection<object> Output, ref object Data, bool IsTest) { Data = (object)((int)Data + 1); Console.WriteLine(DateTime.UtcNow + " - W4: " + Data); } } public class MyWorker5 : Worker { public override void Run(BlockingCollection<object> Input, BlockingCollection<object> Output, ref object Data, bool IsTest) { Data = (object)((int)Data + 1); Console.WriteLine(DateTime.UtcNow + " - W5: " + Data); } } public class MyWorker6 : Worker { public override void Run(BlockingCollection<object> Input, BlockingCollection<object> Output, ref object Data, bool IsTest) { //Thread.Sleep(3000); Data = (object)((int)Data + 1); Console.WriteLine(DateTime.UtcNow + " - W6: " + Data); } } }