text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Classes_1 { public class Operation : Expression { Expression left; char op; Expression right; public Operation(Expression left, char op, Expression right) { this.left = left; this.op = op; this.right = right; } public override double Evaluate(Dictionary<string, object> vars) { double x = left.Evaluate(vars); double y = right.Evaluate(vars); switch (op) { case '+': return x + y; case '-': return x - y; case '*': return x * y; case '/': return x / y; } throw new Exception("Unknown operator"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace PayRoll.BLL { public class InMemoryPayrollDatabase: PayrollDatabase { private static Hashtable employees = new Hashtable(); private static Hashtable unionMembers = new Hashtable(); public Employee GetEmployee(int id) { return employees[id] as Employee; } public void DeleteEmployee(int id) { employees.Remove(id); } public void AddUnionMember(int memberId, Employee emp) { unionMembers[memberId] = emp; } public Employee GetUnionMember(int memberId) { return unionMembers[memberId] as Employee; } public void RemoveUnionMember(int memberId) { unionMembers.Remove(memberId); } public void AddEmployee(Employee employee) { employees[employee.EmpId] = employee; } public ArrayList GetAllEmployeeIds() { return new ArrayList(employees.Keys); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication13 { class Program { public static void Main(string[] args) { Console.Write("Insert the radius of the circle in centimeters: "); double r = double.Parse(Console.ReadLine()); double diameterResult = Diameter(r); double circumferenceResult = (Circumference(diameterResult)); double areaResult = Area(r); Console.Write("The diameter of the circle is " + diameterResult +"cm"); Console.Write("\nThe circumference of the circle is " + circumferenceResult + "cm"); Console.Write("\nThe area of the circle is " + areaResult + "cm square"); Console.ReadKey(); } public static double Diameter(double radius) { return radius * 2; } public static double Circumference(double diameter) { return diameter * 3.14159; } public static double Area(double radius) { return radius * radius * 3.14159; } } }
/* Faça um programa que leia três números e mostre o maior deles. */ using System; namespace _2 { class Program { static void Main(string[] args) { Console.Write("Digite um número: "); double n1 = Double.Parse(Console.ReadLine()); Console.Write("Digite outro número: "); double n2 = Double.Parse(Console.ReadLine()); Console.Write("Digite mais um número: "); double n3 = Double.Parse(Console.ReadLine()); Console.WriteLine(); Console.Write("Dentre os três, o maior número digitado é: "); if ((n2<n1) && (n3<n1)) { Console.Write(n1); } else if ((n1<n2) && (n3<n2)) { Console.Write(n2); } else { Console.Write(n3); } } } }
using System; using System.Collections.Generic; using UnityEngine; public static class MonoUtil { public static Transform FindRecursively(this Transform transform, string name) { if (transform == null) { throw new ArgumentNullException("transform"); } return MonoUtil._FindRecursively(transform, name); } private static Transform _FindRecursively(Transform transform, string name) { if (transform.get_name() == name) { return transform; } for (int i = 0; i < transform.get_childCount(); i++) { Transform child = transform.GetChild(i); Transform transform2 = MonoUtil._FindRecursively(child, name); if (transform2 != null) { return transform2; } } return null; } public static void SetChildCount(this Transform transform, Transform childPrefab, int count) { count = Mathf.Max(0, count); int childCount = transform.get_childCount(); if (childCount == count) { return; } if (childCount > count) { for (int i = childCount - 1; i >= count; i--) { Object.DestroyImmediate(transform.GetChild(i).get_gameObject()); } } else { if (childPrefab == null) { if (childCount <= 0) { throw new ArgumentNullException("childPrefab"); } childPrefab = transform.GetChild(0); } for (int j = childCount; j < count; j++) { Transform transform2 = Object.Instantiate<Transform>(childPrefab); transform2.get_gameObject().set_name(childPrefab.get_gameObject().get_name()); transform2.set_parent(transform); transform2.set_localPosition(childPrefab.get_localPosition()); transform2.set_localRotation(childPrefab.get_localRotation()); transform2.set_localScale(childPrefab.get_localScale()); } } } public static T[] GetComponentsInImmediateChildren<T>(this GameObject go, bool activeOnly = false) where T : Component { return go.get_transform().GetComponentsInImmediateChildren(activeOnly); } public static T[] GetComponentsInImmediateChildren<T>(this Transform transform, bool activeOnly = false) where T : Component { List<T> list = new List<T>(); for (int i = 0; i < transform.get_childCount(); i++) { Transform child = transform.GetChild(i); if (!activeOnly || child.get_gameObject().get_activeSelf()) { T component = child.GetComponent<T>(); if (component != null) { list.Add(component); } } } return list.ToArray(); } public static Transform CreatePrefab(GameObject go, string objectName, Transform parentTrans) { GameObject gameObject = Object.Instantiate<GameObject>(go); gameObject.set_name(objectName); if (parentTrans != null) { NGUITools.SetLayer(gameObject, parentTrans.get_gameObject().get_layer()); } Transform transform = gameObject.get_transform(); transform.set_parent(parentTrans); transform.set_localPosition(Vector3.get_zero()); transform.set_localRotation(Quaternion.get_identity()); transform.set_localScale(Vector3.get_one()); return transform; } public static Transform CreatePrefab(GameObject go, string objectName, Transform parentTrans, Vector3 localPos) { GameObject gameObject = Object.Instantiate<GameObject>(go); gameObject.set_name(objectName); if (parentTrans != null) { NGUITools.SetLayer(gameObject, parentTrans.get_gameObject().get_layer()); } Transform transform = gameObject.get_transform(); transform.set_parent(parentTrans); transform.set_localPosition(localPos); transform.set_localRotation(Quaternion.get_identity()); transform.set_localScale(Vector3.get_one()); return transform; } public static T CreateBehaviour<T>(string objectName, Transform parentTrans) where T : MonoBehaviour { GameObject gameObject = new GameObject(objectName); gameObject.set_name(objectName); Transform transform = gameObject.get_transform(); transform.set_parent(parentTrans); transform.set_localPosition(Vector3.get_zero()); transform.set_localRotation(Quaternion.get_identity()); transform.set_localScale(Vector3.get_one()); return gameObject.AddComponent<T>(); } public static Component CreateBehaviour(Type type, Transform parentTrans) { GameObject gameObject = new GameObject(type.get_Name()); Transform transform = gameObject.get_transform(); transform.set_parent(parentTrans); transform.set_localPosition(Vector3.get_zero()); transform.set_localRotation(Quaternion.get_identity()); transform.set_localScale(Vector3.get_one()); return gameObject.AddComponent(type); } public static float[] Vector3ToArray(Vector3[] vecArr) { if (vecArr == null) { return new float[0]; } float[] array = new float[vecArr.Length * 3]; for (int i = 0; i < vecArr.Length; i++) { array[i * 3] = vecArr[i].x; array[i * 3 + 1] = vecArr[i].y; array[i * 3 + 2] = vecArr[i].z; } return array; } public static Vector3[] ArrayToVector3(float[] arr) { if (arr == null || arr.Length == 0 || arr.Length % 3 != 0) { return null; } Vector3[] array = new Vector3[arr.Length / 3]; for (int i = 0; i < array.Length; i++) { array[i].x = arr[i * 3]; array[i].y = arr[i * 3 + 1]; array[i].z = arr[i * 3 + 2]; } return array; } public static void Vibrate() { } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Gestion.Components.Estadistica; namespace Gestion.Forms { public partial class Estadistica_Main : OwnForm { public Estadistica_Main() { InitializeComponent(); } #region Descripcion (Para Mostrar en MainForm). private static string descripcion = "Permite Armar tabla de frecuencias, y calcular las formulas comunmente usadas." + Environment.NewLine + Environment.NewLine + "Sirve con Variables agrupadas, no agrupadas, y bidimensionales."; public static string Descripcion { get { return descripcion; } } #endregion Estadistica_panel panel; void panelsetup(int paneltype) { panel = new Estadistica_panel(paneltype); panel.Size = new Size(this.Width, this.Height - menuStrip1.Height); panel.Location = new Point(0, menuStrip1.Height); panel.Anchor = (AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right); this.Controls.Add(panel); } void panelclose() { if (panel != null) { DialogResult a = MessageBox.Show("Esta Seguro que desea Cerrar el Ejercicio, Su Progreso desde la ultima vez que guardo se perdera", "Seguro", MessageBoxButtons.OKCancel); if (a == DialogResult.OK) this.Controls.Remove(panel); } } private void New1_Click(object sender, EventArgs e) { panelclose(); panelsetup(1); } private void New2_Click(object sender, EventArgs e) { panelclose(); panelsetup(2); } private void New3_Click(object sender, EventArgs e) { panelclose(); panelsetup(3); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using DLL; namespace WebApplication { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } protected void Application_Error() { var exception = Server.GetLastError(); DLL.Logger logger = new DLL.Logger(); logger.Log(exception.Message ,1,exception); HttpContext.Current.ClearError(); Response.Redirect("~/Error", false); } } }
using System; using WMaper.Base; namespace WMaper.Meta.Radio { /// <summary> /// 事件消息类 /// </summary> public sealed class Msger { #region 变量 // 事件对象 private Event chan; // 消息内容 private Object info; #endregion #region 属性方法 public Event Chan { get { return this.chan; } } public Object Info { get { return this.info; } } #endregion #region 构造函数 /// <summary> /// 构造函数 /// </summary> /// <param name="chan">事件对象</param> /// <param name="info">消息内容</param> public Msger(Event chan, Object info) { this.chan = chan; this.info = info; } #endregion } }
//Problem 7. One system to any other• Write a program to convert from any numeral system of given base s to any other numeral system of base d (2 ≤ s , d ≤ 16). using System; class OneSystemToAnyOther { static void Main() { Console.WriteLine("Please,enter base s for system"); byte baseS = byte.Parse(Console.ReadLine()); Console.WriteLine("Please, enter number of any numeral system"); string numberOneSystem = Console.ReadLine(); Console.WriteLine("Convertion to decimal"); Console.WriteLine(BaseToDecimal(numberOneSystem, baseS)); Console.WriteLine("Please,enter base d for other numeral system"); byte baseD = byte.Parse(Console.ReadLine()); Console.WriteLine(); Console.WriteLine(OtherSystem(BaseToDecimal(numberOneSystem, baseS), baseD)); } static string OtherSystem(long decimalNumber, int numeralBase) { string result = ""; while (decimalNumber > 0) { long digit = decimalNumber % numeralBase; if (digit >= 0 && digit <= 9) { result = (char)(digit + '0') + result; } else if (digit >= 10 && digit <= 15) { result = (char)(digit - 10 + 'A') + result; } decimalNumber /= numeralBase; } return result; } static long BaseToDecimal(string number,int numeralSystem) { long decimalNumber = 0; for (int i = 0; i < number.Length; i++) { int digit = 0; if (number[i] >='0' && number[i]<='9') { digit = number[i] - '0'; } else if (number[i] >= 'A' && number[i] <= 'F') { digit = number[i] - 'A' + 10; } decimalNumber += digit * (long)Math.Pow(numeralSystem, number.Length - i - 1); } return decimalNumber; } }
using Xunit; namespace TreeStore.Model.Test { public class TagTest { [Fact] public void Tag_contains_facet_with_same_name() { // ACT var result = new Tag("tag"); // ASSERT Assert.Equal("tag", result.Facet.Name); } } }
using Discord.Commands; using Discord.WebSocket; using Mad_Bot_Discord.Core.UserAccounts; using Mad_Bot_Discord.Modules.DungeonGame; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Mad_Bot_Discord { /// <summary> /// You enter an infinite randomly-generated dungeon /// attempting to get the best score possible. You /// may leave the dungeon at any time, finalizing your score, /// or you can continue moving forward. If you die, only half /// your total score counts. /// /// You start with 0 gold your first run, and killing /// enemies and triggering certain events can give you /// gold. Then, events can give you ways to spend that /// gold. For example, a blacksmith can offer to repair /// your weapon for a price, or a shopkeeper can sell you /// weapons or ammo. When your run ends, you get to keep /// half the gold for your next run, and perhaps you can /// have a better starter weapon for gold when you start /// a run? Another idea for gold is events that can give /// or take gold. Like, some dude comes up offering to give /// you twice the gold you give him, then there's a 50% chance /// you'll actually get the gold or just get scammed. I dunno, /// just some random ideas I had. Maybe you shouldn't be able /// to keep some of the gold, idk. /// /// random events pls /// /// To Do Next: /// Damage System for weapons /// Random items on ground /// Custom Player Icon (map) /// Custom Color (map) ini = blue, css = red, /// Consumables that you can save between runs. /// MB as strongest boss? /// Multiple scores on the leaderboard such as most rooms explored in a single run or most weapons gathered in a single run. /// Themes and different modes (like wild-west only) /// enemy versions of other users whove played before, matching their stats and the current theme. /// when you die have it say "You died." along with some random text like "this is so sad alexa play despacito" /// /// </summary> public class DungeonGame : ModuleBase<SocketCommandContext> { // Tutorial message after each command to tell you what you can do. public string tutorialMessage = $"Reply with `{Config.bot.cmdPrefix}dg <direction>` to move, `{Config.bot.cmdPrefix}dg map` to view the map" + $", `{Config.bot.cmdPrefix}dg inv` to view your inventory, `{Config.bot.cmdPrefix}dg types` to view what room types do/appear like on the map, " + $"or `{Config.bot.cmdPrefix}dg leave` to leave the dungeon and finalize your score."; private static List<SaveData> saves; static string savePath = "Resources/dgsaves.json"; #region Data Handling void SaveData() { if (!File.Exists(savePath)) { saves = new List<SaveData>(); string json = JsonConvert.SerializeObject(saves, Formatting.Indented); File.WriteAllText(savePath, json); } else { string json = JsonConvert.SerializeObject(saves, Formatting.Indented); File.WriteAllText(savePath, json); } } void RefreshData() { string json = File.ReadAllText(savePath); JsonConverter[] converters = { new WeaponConverter() }; saves = JsonConvert.DeserializeObject<List<SaveData>>(json, new JsonSerializerSettings() { Converters = converters }); } SaveData CreateSaveData(ulong id) { SocketGuildUser user = (SocketGuildUser)Context.User; var newSave = new SaveData() { User = UserAccounts.GetAccount(user), Player = new Player() }; newSave.Player.Name = user.Username; newSave.Player.SaveData = newSave; saves.Add(newSave); SaveData(); return newSave; } SaveData GetOrCreateSaveData(ulong id) { RefreshData(); var result = from s in saves where s.User.ID == id select s; SaveData save = result.FirstOrDefault(); if (save == null) save = CreateSaveData(id); return save; } SaveData GetData(ulong id) { return GetOrCreateSaveData(id); } #endregion Data Handling Random r = new Random(); [Command("Dungeon"), Alias("dg")] public async Task Dungeon([Remainder] string options = "") { // Currently only works for me. if (Context.User.Id != 226223728076390410) return; #region Save File Interaction if (!File.Exists(savePath)) { // If it doesn't, create it. UserAccount user = UserAccounts.GetAccount(Context.User); saves = new List<SaveData> { new SaveData { User = user } }; string json = JsonConvert.SerializeObject(saves, Formatting.Indented); File.WriteAllText(savePath, json); } else { JsonConverter[] converters = { new WeaponConverter() }; // If it does, read it and save it to a variable. string json = File.ReadAllText(savePath); saves = JsonConvert.DeserializeObject<List<SaveData>>(json, new JsonSerializerSettings() { Converters = converters }); } #endregion Save File Interaction // Gets any arguments provided. string[] args = { }; if (!string.IsNullOrWhiteSpace(options)) args = options.Split(' '); // Gets the users save data. SaveData data = GetData(Context.User.Id); // Gets the player Player player = data.Player; // Starts a variable that stores what mb will say to you. string sentence = ""; // If the user doesn't have any save data, set up the game. if (!data.InGame) { // Creates a starting sword. Sword startingSword = new Sword() { BladeLength = DungeonWeaponParts.Sword_BladeLength[0], BladeThickness = DungeonWeaponParts.Sword_BladeThickness[0], BladeType = DungeonWeaponParts.Sword_BladeType[1], HiltGrip = DungeonWeaponParts.Sword_HiltGrip[0], HiltSize = DungeonWeaponParts.Sword_HiltSize[0], HiltType = DungeonWeaponParts.Sword_HiltType[1], WeightType = DungeonWeaponParts.Sword_WeightType[0], Name = DungeonWeaponParts.Sword_BladeType[1].NamePart + DungeonWeaponParts.Sword_BladeThickness[0].NamePart + DungeonWeaponParts.Sword_HiltType[1].NamePart + DungeonWeaponParts.Sword_HiltSize[0].NamePart }; // Sets the equipped weapon to the starting sword. player.EquippedWeapon = startingSword; // Creates a starting dungeon. DungeonRoom startingRoom = new DungeonRoom { Coordinates = new Coordinates { X = 0, Y = 0 }, RoomDoors = new List<Direction> { Direction.Left, Direction.Right, Direction.Front, Direction.Back }, Type = RoomType.Empty }; // Sets up a dictionary that stores every room visited. Dictionary<string, DungeonRoom> Rooms = new Dictionary<string, DungeonRoom> { { Coordinates.CoordsToString(0, 0), startingRoom } }; // Adds this to the beginning of the sentence to make sure you know you are starting over. sentence = sentence + $"**Dungeon Start.**\n\n"; // Sets the player's current room to the starting room we created earlier. data.CurrentRoom = startingRoom; // Sets the savedata's room dictionary to the dictionary we created earlier. data.Rooms = Rooms; // Sets the InGame variable to true, which means the game now knows we have started. data.InGame = true; // Sets up the player's inventory. player.Inventory = new List<Weapon> { startingSword }; // Makes sure they arent in a fight. data.InFight = false; // Saves all that new data. SaveData(); } #region Main if (!data.InFight) { if (args.Length > 0) { switch (args[0].ToLower()) { #region directions case "left": #region left if (data.CurrentRoom.RoomDoors.Contains(Direction.Left)) { data.CurrentRoom = RoomGenerator(new Coordinates { X = data.CurrentRoom.Coordinates.X - 1, Y = data.CurrentRoom.Coordinates.Y }, data); if (data.CurrentRoom.Type == RoomType.Enemy) { data.CurrentEnemy = EnemyGenerator(); data.InFight = true; sentence = sentence + "You walk into the room to the left of you and are attacked by a " + data.CurrentEnemy.Name + $"! Type `{Config.bot.cmdPrefix}dg` to start."; data.Rooms.Add(Coordinates.CoordsToString(data.CurrentRoom.Coordinates), data.CurrentRoom); SaveData(); await Context.Channel.SendMessageAsync(sentence); return; } if (!data.Rooms.ContainsKey(Coordinates.CoordsToString(data.CurrentRoom.Coordinates))) { sentence = sentence + "You walk into the room to your left. "; data.Rooms.Add(Coordinates.CoordsToString(data.CurrentRoom.Coordinates), data.CurrentRoom); } else { sentence = sentence + "You walk back into the room to your left. "; } SaveData(); } else { sentence = sentence + "You cannot do that.\n\n"; } break; #endregion left case "right": #region right if (data.CurrentRoom.RoomDoors.Contains(Direction.Right)) { data.CurrentRoom = RoomGenerator(new Coordinates { X = data.CurrentRoom.Coordinates.X + 1, Y = data.CurrentRoom.Coordinates.Y }, data); if (data.CurrentRoom.Type == RoomType.Enemy) { data.CurrentEnemy = EnemyGenerator(); data.InFight = true; sentence = sentence + "You walk into the room to the right of you and are attacked by a " + data.CurrentEnemy.Name + $"! Type `{Config.bot.cmdPrefix}dg` to start."; data.Rooms.Add(Coordinates.CoordsToString(data.CurrentRoom.Coordinates), data.CurrentRoom); SaveData(); await Context.Channel.SendMessageAsync(sentence); return; } if (!data.Rooms.ContainsKey(Coordinates.CoordsToString(data.CurrentRoom.Coordinates))) { sentence = sentence + "You walk into the room to your right. "; data.Rooms.Add(Coordinates.CoordsToString(data.CurrentRoom.Coordinates), data.CurrentRoom); } else { sentence = sentence + "You walk back into the room to your right. "; } SaveData(); } else { sentence = sentence + "You cannot do that.\n\n"; } break; #endregion right case "front": case "up": case "forward": case "forwards": #region front if (data.CurrentRoom.RoomDoors.Contains(Direction.Front)) { data.CurrentRoom = RoomGenerator(new Coordinates { X = data.CurrentRoom.Coordinates.X, Y = data.CurrentRoom.Coordinates.Y + 1 }, data); if (data.CurrentRoom.Type == RoomType.Enemy) { data.CurrentEnemy = EnemyGenerator(); data.InFight = true; sentence = sentence + "You walk into the room ahead of you and are attacked by a " + data.CurrentEnemy.Name + $"! Type `{Config.bot.cmdPrefix}dg` to start."; data.Rooms.Add(Coordinates.CoordsToString(data.CurrentRoom.Coordinates), data.CurrentRoom); SaveData(); await Context.Channel.SendMessageAsync(sentence); return; } if (!data.Rooms.ContainsKey(Coordinates.CoordsToString(data.CurrentRoom.Coordinates))) { sentence = sentence + "You walk into the room ahead. "; data.Rooms.Add(Coordinates.CoordsToString(data.CurrentRoom.Coordinates), data.CurrentRoom); } else { sentence = sentence + "You walk back into the room ahead. "; } SaveData(); } else { sentence = sentence + "You cannot do that.\n\n"; } break; #endregion front case "back": case "down": case "backward": case "backwards": #region back if (data.CurrentRoom.RoomDoors.Contains(Direction.Back)) { data.CurrentRoom = RoomGenerator(new Coordinates { X = data.CurrentRoom.Coordinates.X, Y = data.CurrentRoom.Coordinates.Y - 1}, data); if (data.CurrentRoom.Type == RoomType.Enemy) { if (!data.Rooms.ContainsKey(Coordinates.CoordsToString(data.CurrentRoom.Coordinates))) { data.CurrentEnemy = EnemyGenerator(); data.InFight = true; sentence = sentence + "You walk into the room behind you and are attacked by a " + data.CurrentEnemy.Name + $"! Type `{Config.bot.cmdPrefix}dg` to start."; data.Rooms.Add(Coordinates.CoordsToString(data.CurrentRoom.Coordinates), data.CurrentRoom); SaveData(); await Context.Channel.SendMessageAsync(sentence); return; } } if (!data.Rooms.ContainsKey(Coordinates.CoordsToString(data.CurrentRoom.Coordinates))) { sentence = sentence + "You walk into the room behind you. "; data.Rooms.Add(Coordinates.CoordsToString(data.CurrentRoom.Coordinates), data.CurrentRoom); } else { sentence = sentence + "You walk back into the room behind you. "; } SaveData(); } else { sentence = sentence + "You cannot do that.\n\n ... \n\n"; } break; #endregion back #endregion directions case "map": #region map //sentence = sentence + $"Current Room Type: [{data.CurrentRoom.Type}] \n\n"; List<double> allX = new List<double>(); List<double> allY = new List<double>(); foreach (KeyValuePair<string, DungeonRoom> r in data.Rooms) { DungeonRoom v = r.Value; allX.Add(v.Coordinates.X); allY.Add(v.Coordinates.Y); } allX.Sort(); allY.Sort(); string mp = "```ini\n"; for (double y = allY.Max() + 1; y >= allY.Min() - 1; y = y - 0.5) { for (double x = allX[0] - 1; x <= allX.Max() + 1; x = x + 0.5) { string c = Coordinates.CoordsToString(x, y); string TBA = ""; if (data.Rooms.ContainsKey(Coordinates.CoordsToString(x + 0.5, y))) { if (data.Rooms[Coordinates.CoordsToString(x + 0.5, y)].RoomDoors.Contains(Direction.Left)) { TBA = "==="; } } if (data.Rooms.ContainsKey(Coordinates.CoordsToString(x - 0.5, y))) { if (data.Rooms[Coordinates.CoordsToString(x - 0.5, y)].RoomDoors.Contains(Direction.Right)) { TBA = "==="; } } if (data.Rooms.ContainsKey(c)) { if (Coordinates.CoordsToString(data.CurrentRoom.Coordinates) == Coordinates.CoordsToString(x, y)) TBA = "<@>"; else { DungeonRoom nr = data.Rooms[c]; switch (nr.Type) { case RoomType.Boss: TBA = "[!]"; break; case RoomType.Empty: TBA = "[ ]"; break; case RoomType.Enemy: TBA = "[#]"; break; case RoomType.Loot: TBA = "[$]"; break; } } } else if (TBA != "===") TBA = " "; if (data.Rooms.ContainsKey(Coordinates.CoordsToString(x, y+0.5))) { if (data.Rooms[Coordinates.CoordsToString(x, y+0.5)].RoomDoors.Contains(Direction.Back)) { TBA = "| |"; } else { TBA = " "; } } if (data.Rooms.ContainsKey(Coordinates.CoordsToString(x, y-0.5))) { if (data.Rooms[Coordinates.CoordsToString(x, y-0.5)].RoomDoors.Contains(Direction.Front)) { TBA = "| |"; } else TBA = " "; } mp = mp + TBA; } mp = mp + "\n"; } mp = mp + "``` \n\n"; await Context.Channel.SendMessageAsync(mp); break; #endregion map case "inv": case "inventory": #region inventory string tba = "Your current inventory:\n\n**Swords:** \n\n"; List<Weapon> w = data.Player.Inventory; List<Sword> swords = new List<Sword>(); List<Gun> guns = new List<Gun>(); foreach (Weapon weapon in w) { if (weapon.WeaponType == WeaponType.Sword) swords.Add((Sword)weapon); if (weapon.WeaponType == WeaponType.Gun) guns.Add((Gun)weapon); } if (swords.Count > 0) { foreach (Sword s in swords) { tba = tba + s.Name + $" [Damage: {s.GetBaseDamage()} | Accuracy: {s.GetAccuracy()} | Stun Chance: {s.GetStunChance()}0% | Stun Amount: {s.GetStunAmount()} Turns] \n"; } } else tba = tba + "None!\n"; tba = tba + "\n**Guns:** \n\n"; if (guns.Count > 0) { foreach (Gun g in guns) { tba = tba + g.Name + $" [Damage: {g.GetBaseDamage()} | Accuracy: {g.GetAccuracy()} | Stun Chance: {g.GetStunChance()}0% | Stun Amount: {g.GetStunAmount()} Turns] \n"; } } else tba = tba + "None!\n"; sentence = sentence + tba + "\n\n"; break; #endregion inventory case "leave": case "exit": case "quit": #region quit string[] encouragingWords = { "Wow, you", "Incredible! You", "Good job, you", "Nice work, you", "That's crazy! You", "Meh, you", "**yawn** you" }; string word = encouragingWords[r.Next(encouragingWords.Length)]; sentence = $"You left the dungeon. {word} got [0] score."; await Context.Channel.SendMessageAsync(sentence); data.InGame = false; SaveData(); return; #endregion quit case "types": sentence = sentence + "Room Types:\n\nEmpty: An empty room. Appears as `[ ]` in the map.\nEnemy: A room that contains enemies. Appears as `[#]` in the map.\n" + "Loot: A room that gives you random loot. Appears as `[$]` in the map.\nBoss: A room that contains a boss. Appears as `[!]` in the map.\n" + "You: You appear as `<@>` on the map.\n\n"; await Context.Channel.SendMessageAsync(sentence); return; } } // RoomCount = amount of doors in a room. if (data.CurrentRoom.RoomCount > 1) { sentence = sentence + $"Current Room Type: [{data.CurrentRoom.Type}] \n\n"; string one = ""; for (int i = 0; i < data.CurrentRoom.RoomCount; i++) { if (i == data.CurrentRoom.RoomCount - 1) { one = one + ", and one to your **" + data.CurrentRoom.RoomDoors[i].ToString().ToLower() + "**."; } else { one = one + ", one to your **" + data.CurrentRoom.RoomDoors[i].ToString().ToLower() + "**"; } } sentence = sentence + $"There are {data.CurrentRoom.RoomCount} rooms{one} {tutorialMessage}"; } else { sentence = sentence + $"Current Room Type: [{data.CurrentRoom.Type}] \n\n"; sentence = sentence = $"There is one room to your **{data.CurrentRoom.RoomDoors[0].ToString().ToLower()}**. {tutorialMessage}"; } await Context.Channel.SendMessageAsync(sentence); } else { if (args.Length > 0) { switch (args[0].ToLower()) { case "attack": DungeonMethods.DealDamage(data.CurrentEnemy, 5); if (data.CurrentEnemy.Health <= 0) { sentence = sentence + $"\n\nYou defeated the {data.CurrentEnemy.Name} and gained [0] gold!"; data.CurrentRoom.Type = RoomType.Empty; data.Rooms[Coordinates.CoordsToString(data.CurrentRoom.Coordinates)].Type = RoomType.Empty; data.InFight = false; await Context.Channel.SendMessageAsync(sentence); SaveData(); return; } if (data.Player.Health <= 0) { sentence = sentence + $"You died! You got [0] score!"; data.InGame = false; SaveData(); return; } SaveData(); await Context.Channel.SendMessageAsync(sentence); break; case "item": break; case "check": sentence = sentence + $"The {data.CurrentEnemy.Name} has {data.CurrentEnemy.Health} HP left."; if (data.CurrentEnemy.StunLeft > 0) sentence = sentence + $" It has {data.CurrentEnemy.StunLeft} turns left until the stun wears off."; await Context.Channel.SendMessageAsync(sentence); break; case "status": sentence = sentence + $"You currently have `{player.Health}` HP and have the {player.EquippedWeapon.Name} [Damage: {player.EquippedWeapon.GetBaseDamage()}] equipped."; await Context.Channel.SendMessageAsync(sentence); break; } } else { sentence = sentence + $"You are fighting a `{data.CurrentEnemy.Name}` with `{data.CurrentEnemy.Health}` HP.\n\n**Options:** | Attack | Item | Check | Status |"; await Context.Channel.SendMessageAsync(sentence); } } #endregion Main } /* string weapon = $"You find a {rGun.FireType.Name} {rGun.BodyType.Name} that fires {rGun.Projectile.Name}. It is labelled *\"{rGun.Name}\"*\n" + $"Total Stats: [Damage: {rGun.FireType.Damage + rGun.BodyType.Damage + rGun.Projectile.Damage} | Accuracy: {rGun.FireType.Accuracy + rGun.BodyType.Accuracy + rGun.Projectile.Accuracy}" + $" | Stun Chance: {rGun.Projectile.StunChance}0% | Stun Amount: {rGun.Projectile.StunAmount} Rounds]"; */ // Random Room public DungeonRoom RoomGenerator(Coordinates coords, SaveData data) { if (data.Rooms.ContainsKey(Coordinates.CoordsToString(coords))) return data.Rooms[Coordinates.CoordsToString(coords)]; bool BossAvailable = (data.Rooms.Count > 14) ? true : false; DungeonRoom currentRoom = data.CurrentRoom; Array values = Enum.GetValues(typeof(RoomType)); RoomType randomType = (RoomType)values.GetValue(r.Next((BossAvailable) ? values.Length : values.Length - 1)); CanDirection canDir = new CanDirection(); DungeonRoom roomR = null; DungeonRoom roomL = null; DungeonRoom roomF = null; DungeonRoom roomB = null; List<Direction> rDoors = new List<Direction>(); if (data.Rooms.ContainsKey(Coordinates.CoordsToString(new Coordinates { X = coords.X + 1, Y = coords.Y }))) { roomR = data.Rooms[Coordinates.CoordsToString(new Coordinates { X = coords.X + 1, Y = coords.Y })]; if (roomR.RoomDoors.Contains(Direction.Left)) { rDoors.Add(Direction.Right); } } else canDir.CanRight = true; if (data.Rooms.ContainsKey(Coordinates.CoordsToString(new Coordinates { X = coords.X - 1, Y = coords.Y }))) { roomL = data.Rooms[Coordinates.CoordsToString(new Coordinates { X = coords.X - 1, Y = coords.Y })]; if (roomL.RoomDoors.Contains(Direction.Right)) { rDoors.Add(Direction.Left); } } else canDir.CanLeft = true; if (data.Rooms.ContainsKey(Coordinates.CoordsToString(new Coordinates { X = coords.X, Y = coords.Y + 1 }))) { roomF = data.Rooms[Coordinates.CoordsToString(new Coordinates { X = coords.X, Y = coords.Y + 1 })]; if (roomF.RoomDoors.Contains(Direction.Back)) { rDoors.Add(Direction.Front); } } else canDir.CanFront = true; if (data.Rooms.ContainsKey(Coordinates.CoordsToString(new Coordinates { X = coords.X, Y = coords.Y - 1 }))) { roomB = data.Rooms[Coordinates.CoordsToString(new Coordinates { X = coords.X, Y = coords.Y - 1 })]; if (roomB.RoomDoors.Contains(Direction.Front)) { rDoors.Add(Direction.Back); } } else canDir.CanBack = true; int totalDoors = 0; if (canDir.CanLeft && r.Next(2) == 1) if (!rDoors.Contains(Direction.Left)) { rDoors.Add(Direction.Left); totalDoors++; } if (canDir.CanRight && r.Next(2) == 1) if (!rDoors.Contains(Direction.Right)) { rDoors.Add(Direction.Right); totalDoors++; } if (canDir.CanFront && r.Next(2) == 1) if (!rDoors.Contains(Direction.Front)) { rDoors.Add(Direction.Front); totalDoors++; } if (canDir.CanBack && r.Next(2) == 1) if (!rDoors.Contains(Direction.Back)) { rDoors.Add(Direction.Back); totalDoors++; } DungeonRoom room = new DungeonRoom { Coordinates = coords, Type = randomType, RoomDoors = rDoors, }; return room; } // Specific Type public DungeonRoom RoomGenerator(Coordinates coords, SaveData data, RoomType roomType) { if (data.Rooms.ContainsKey(Coordinates.CoordsToString(coords))) return data.Rooms[Coordinates.CoordsToString(coords)]; DungeonRoom currentRoom = data.CurrentRoom; CanDirection canDir = new CanDirection(); DungeonRoom roomR = null; DungeonRoom roomL = null; DungeonRoom roomF = null; DungeonRoom roomB = null; List<Direction> rDoors = new List<Direction>(); if (data.Rooms.ContainsKey(Coordinates.CoordsToString(new Coordinates { X = coords.X + 1, Y = coords.Y }))) { roomR = data.Rooms[Coordinates.CoordsToString(new Coordinates { X = coords.X + 1, Y = coords.Y })]; if (roomR.RoomDoors.Contains(Direction.Left)) { canDir.CanRight = true; if (Coordinates.CoordsToString(roomR.Coordinates) == Coordinates.CoordsToString(currentRoom.Coordinates)) rDoors.Add(Direction.Right); } } else canDir.CanRight = true; if (data.Rooms.ContainsKey(Coordinates.CoordsToString(new Coordinates { X = coords.X - 1, Y = coords.Y }))) { roomL = data.Rooms[Coordinates.CoordsToString(new Coordinates { X = coords.X - 1, Y = coords.Y })]; if (roomL.RoomDoors.Contains(Direction.Right)) { canDir.CanLeft = true; if (Coordinates.CoordsToString(roomL.Coordinates) == Coordinates.CoordsToString(currentRoom.Coordinates)) rDoors.Add(Direction.Left); } } else canDir.CanLeft = true; if (data.Rooms.ContainsKey(Coordinates.CoordsToString(new Coordinates { X = coords.X, Y = coords.Y + 1 }))) { roomF = data.Rooms[Coordinates.CoordsToString(new Coordinates { X = coords.X, Y = coords.Y + 1 })]; if (roomF.RoomDoors.Contains(Direction.Back)) { canDir.CanFront = true; if (Coordinates.CoordsToString(roomF.Coordinates) == Coordinates.CoordsToString(currentRoom.Coordinates)) rDoors.Add(Direction.Front); } } else canDir.CanFront = true; if (data.Rooms.ContainsKey(Coordinates.CoordsToString(new Coordinates { X = coords.X, Y = coords.Y - 1 }))) { roomB = data.Rooms[Coordinates.CoordsToString(new Coordinates { X = coords.X, Y = coords.Y - 1 })]; if (roomB.RoomDoors.Contains(Direction.Front)) { canDir.CanBack = true; if (Coordinates.CoordsToString(roomB.Coordinates) == Coordinates.CoordsToString(currentRoom.Coordinates)) rDoors.Add(Direction.Back); } } else canDir.CanBack = true; int totalDoors = 0; if (canDir.CanLeft && r.Next(2) == 1) if (!rDoors.Contains(Direction.Left)) { rDoors.Add(Direction.Left); totalDoors++; } if (canDir.CanRight && r.Next(2) == 1) if (!rDoors.Contains(Direction.Right)) { rDoors.Add(Direction.Right); totalDoors++; } if (canDir.CanFront && r.Next(2) == 1) if (!rDoors.Contains(Direction.Front)) { rDoors.Add(Direction.Front); totalDoors++; } if (canDir.CanBack && r.Next(2) == 1) if (!rDoors.Contains(Direction.Back)) { rDoors.Add(Direction.Back); totalDoors++; } DungeonRoom room = new DungeonRoom { Coordinates = coords, Type = roomType, RoomDoors = rDoors, }; return room; } // Randomly generates a gun then returns it. public Gun GunGenerator() { // Selects a random value from the Gun_ProjectileType enum. Array values = Enum.GetValues(typeof(DungeonWeaponParts.Gun_ProjectileType)); DungeonWeaponParts.Gun_ProjectileType randomProj = (DungeonWeaponParts.Gun_ProjectileType)values.GetValue(r.Next(0, values.Length)); Attributes projectile = new Attributes(); // Selects different projectiles based on which enum was selected earlier. switch (randomProj) { case DungeonWeaponParts.Gun_ProjectileType.Bullet: int proj1 = r.Next(0, DungeonWeaponParts.Gun_BulletCaliber.Count); projectile = DungeonWeaponParts.Gun_BulletCaliber[proj1]; break; case DungeonWeaponParts.Gun_ProjectileType.Explosive: int proj2 = r.Next(0, DungeonWeaponParts.Gun_ExplosiveType.Count); projectile = DungeonWeaponParts.Gun_ExplosiveType[proj2]; break; case DungeonWeaponParts.Gun_ProjectileType.Primitive: int proj3 = r.Next(0, DungeonWeaponParts.Gun_PrimitiveType.Count); projectile = DungeonWeaponParts.Gun_PrimitiveType[proj3]; break; case DungeonWeaponParts.Gun_ProjectileType.Special: int proj4 = r.Next(0, DungeonWeaponParts.Gun_SpecialType.Count); projectile = DungeonWeaponParts.Gun_SpecialType[proj4]; break; } // Creates the gun. Gun rGun = new Gun { FireType = DungeonWeaponParts.Gun_FireType[r.Next(0, DungeonWeaponParts.Gun_FireType.Count)], BodyType = DungeonWeaponParts.Gun_BodyType[r.Next(0, DungeonWeaponParts.Gun_BodyType.Count)], ProjectileType = randomProj, Projectile = projectile, }; rGun.Name = rGun.BodyType.NamePart + rGun.Projectile.NamePart; return rGun; } // Randomly generates a sword then returns it. public Sword SwordGenerator() { // Creates the sword. Sword sword = new Sword { BladeLength = DungeonWeaponParts.Sword_BladeLength[r.Next(DungeonWeaponParts.Sword_BladeLength.Count)], BladeThickness = DungeonWeaponParts.Sword_BladeThickness[r.Next(DungeonWeaponParts.Sword_BladeThickness.Count)], BladeType = DungeonWeaponParts.Sword_BladeType[r.Next(DungeonWeaponParts.Sword_BladeType.Count)], HiltGrip = DungeonWeaponParts.Sword_HiltGrip[r.Next(DungeonWeaponParts.Sword_HiltGrip.Count)], HiltSize = DungeonWeaponParts.Sword_HiltSize[r.Next(DungeonWeaponParts.Sword_HiltSize.Count)], HiltType = DungeonWeaponParts.Sword_HiltType[r.Next(DungeonWeaponParts.Sword_HiltType.Count)], WeightType = DungeonWeaponParts.Sword_WeightType[r.Next(DungeonWeaponParts.Sword_WeightType.Count)] }; return sword; } // Randomly generates an enemy then return it. public Enemy EnemyGenerator() { Enemy enemy = new Enemy() { Name = "Placeholder Man", Health = r.Next(2,11), // Have this scale up with difficulty later. StunLeft = 0, Stats = new Stats() { AccuracyIncrease = r.Next(-10, 11), DamageIncrease = r.Next(-10, 16), CriticalChanceIncrease = r.Next(-10, 11), StunChanceIncrease = r.Next(-10, 11), StunAmountIncrease = r.Next(-10, 11) }, }; return enemy; } } public enum RoomType { Empty, Loot, Enemy, Boss }; public enum Direction { Front, Back, Left, Right }; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ast.Models { public partial class dt_users { /// <summary> /// 自增ID /// </summary> public int id { get; set; } /// <summary> /// /// </summary> public int group_id { get; set; } /// <summary> /// 用户名 /// </summary> public string user_name { get; set; } /// <summary> /// 用户密码 /// </summary> public string password { get; set; } /// <summary> /// 6位随机字符串,加密用到 /// </summary> public string salt { get; set; } /// <summary> /// 电子邮箱 /// </summary> public string email { get; set; } /// <summary> /// 用户昵称 /// </summary> public string nick_name { get; set; } /// <summary> /// 用户头像 /// </summary> public string avatar { get; set; } /// <summary> /// 用户性别 /// </summary> public string sex { get; set; } /// <summary> /// 生日 /// </summary> public DateTime birthday { get; set; } /// <summary> /// 联系电话 /// </summary> public string telphone { get; set; } /// <summary> /// 手机号码 /// </summary> public string mobile { get; set; } /// <summary> /// QQ号码 /// </summary> public string qq { get; set; } /// <summary> /// 联系地址 /// </summary> public string address { get; set; } /// <summary> /// 安全问题 /// </summary> public string safe_question { get; set; } /// <summary> /// 问题答案 /// </summary> public string safe_answer { get; set; } /// <summary> /// 预存款 /// </summary> public decimal amount { get; set; } /// <summary> /// 用户积分 /// </summary> public int point { get; set; } /// <summary> /// 经验值 /// </summary> public int exp { get; set; } /// <summary> /// 用户状态,0正常,1待验证,2待审核,3锁定 /// </summary> public byte status { get; set; } /// <summary> /// 注册时间 /// </summary> public DateTime reg_time { get; set; } /// <summary> /// 注册IP /// </summary> public string reg_ip { get; set; } /// <summary> /// 是否是微信号,1、是 0、不是 /// </summary> public byte isweixin { get; set; } /// <summary> /// 微信用户表主键Id /// </summary> public int wid { get; set; } /// <summary> /// /// </summary> public string wxOpenId { get; set; } /// <summary> /// /// </summary> public string wxName { get; set; } /// <summary> /// 推荐者Id /// </summary> public int recommendId { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CameraController : MonoBehaviour { public bool isInverted; public Transform playerTrans; public float rotationSpeed = 100f; float mousex; float mousey; Quaternion camAngle; // Start is called before the first frame update void Start() { if (PlayerPrefs.GetInt("invertedY") == 1) { isInverted = true; } else { isInverted = false; } } // Update is called once per frame void LateUpdate() { mousex += Input.GetAxis("Mouse X") * rotationSpeed * Time.deltaTime; mousey += Input.GetAxis("Mouse Y") * rotationSpeed * Time.deltaTime * (isInverted ? -1 : 1); Vector3 direct = new Vector3(0, 1f, -4f); mousey = Mathf.Clamp(mousey, -20f, 20f); camAngle = Quaternion.Euler(mousey, mousex, 0); transform.position = playerTrans.position + camAngle * direct; transform.LookAt(playerTrans); } }
using System; using System.IO; using System.Text; namespace PathfindingVisualisation { public static class MapWriter { public static void WriteDataToFile(string path, MapData mapData) { try { using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write)) using (var ms = new MemoryStream()) using (var sw = new StreamWriter(ms, Encoding.UTF8)) { mapData.Serialize(sw); sw.Flush(); ms.Seek(0, SeekOrigin.Begin); ms.CopyTo(fs); } } catch (Exception e) { throw new Exception($"Could not save map data to file '{path}'", e); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DependencyInjection { public class Sword : IWeapon { public bool Attack(double distance) { if (distance < 1.5) return true; else return false; } public void Reload() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Liddup.Models; using SpotifyAPI.Web; using SpotifyAPI.Web.Models; using Xamarin.Forms; using SpotifyAPI.Web.Enums; namespace Liddup.Services { public static class SpotifyApiManager { private static readonly SpotifyWebAPI Spotify; private static readonly PrivateProfile Profile; static SpotifyApiManager() { Spotify = new SpotifyWebAPI { UseAuth = true, TokenType = "Bearer", AccessToken = DependencyService.Get<ISpotifyApi>()?.AccessToken }; Profile = Spotify.GetPrivateProfile(); Profile.Id = Uri.EscapeDataString(Profile.Id); } public static async Task<List<SimplePlaylist>> GetUserPlaylistsAsync(CancellationToken token) { token.ThrowIfCancellationRequested(); var playlists = await Spotify.GetUserPlaylistsAsync(Profile.Id); token.ThrowIfCancellationRequested(); var list = playlists.Items.ToList(); while (playlists.Next != null) { token.ThrowIfCancellationRequested(); playlists = await Spotify.GetUserPlaylistsAsync(Profile.Id, 20, playlists.Offset + playlists.Limit); token.ThrowIfCancellationRequested(); list.AddRange(playlists.Items); } return list; } public static async Task<List<FullTrack>> GetUserPlaylistSongsAsync(string profileId, string playlistId, CancellationToken token) { token.ThrowIfCancellationRequested(); var savedTracks = await Spotify.GetPlaylistTracksAsync(profileId, playlistId); token.ThrowIfCancellationRequested(); var list = savedTracks.Items.Select(track => track.Track).ToList(); while (savedTracks.Next != null) { token.ThrowIfCancellationRequested(); savedTracks = await Spotify.GetPlaylistTracksAsync(profileId, playlistId, "", 20, savedTracks.Offset + savedTracks.Limit); token.ThrowIfCancellationRequested(); list.AddRange(savedTracks.Items.Select(track => track.Track)); } return list; } public static async Task<List<FullTrack>> GetSavedTracks(CancellationToken token) { token.ThrowIfCancellationRequested(); var savedTracks = await Spotify.GetSavedTracksAsync(); token.ThrowIfCancellationRequested(); var list = savedTracks.Items.Select(track => track.Track).ToList(); while (savedTracks.Next != null) { token.ThrowIfCancellationRequested(); savedTracks = await Spotify.GetSavedTracksAsync(20, savedTracks.Offset + savedTracks.Limit); token.ThrowIfCancellationRequested(); list.AddRange(savedTracks.Items.Select(track => track.Track)); } return list; } public static async Task<List<FullTrack>> GetSearchResults(string query, CancellationToken token) { token.ThrowIfCancellationRequested(); var searchResults = (await Spotify.SearchItemsAsync(query, SearchType.Track)).Tracks; token.ThrowIfCancellationRequested(); //while (searchResults.Next != null) //{ // token.ThrowIfCancellationRequested(); // searchResults = (await Spotify.SearchItemsAsync(query, SearchType.Track, 20, searchResults.Offset + searchResults.Limit)).Tracks; // token.ThrowIfCancellationRequested(); // searchResults.Items.AddRange(searchResults.Items); //} return searchResults.Items; } public static void AddSongToQueue(Song song, ISongProvider sender) { //var song = new Song //{ // Uri = ((FullTrack)item).Uri, // Source = "Spotify", // Title = ((FullTrack)item).Name, // Votes = 0 //}; try { song.AddToQueueCommand.Execute(null); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); } } public static void PlayTrack(string uri) { DependencyService.Get<ISpotifyApi>().PlayTrack(uri); } public static void ResumeTrack() { DependencyService.Get<ISpotifyApi>().ResumeTrack(); } public static void PauseTrack() { DependencyService.Get<ISpotifyApi>().PauseTrack(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace CT.Data { [CreateAssetMenu(fileName = "New Turret", menuName = "Faction/Building/Turret")] public class DefensiveData : BuildingData { public override BuildingType Type => BuildingType.Turret; public enum DefenseType { Turret, UnitLauncher } public enum TurretType { Hit, Projectile, Laser } //may do other turret types public VersionData original; public VersionData[] upgrades; public override BaseVersionData Original => original; public override BaseVersionData[] Upgrades => upgrades; [System.Serializable] public class VersionData : BaseVersionData { public DefenseType defenseType; //[Header("Turret")] public UnitData.CanAttack canAttack; public float AttackRate => defenseType == DefenseType.UnitLauncher ? (1f / spawnDelta) : fireRate; public float Damage => turretType == TurretType.Projectile ? projectile.GetComponent<Projectile>().damage : nonProjectileDamage; public float ExplosionRange => turretType == TurretType.Projectile ? projectile.GetComponent<Projectile>().splashRadius : nonProjectileDamage; public float ExplosionDamage => turretType == TurretType.Projectile ? projectile.GetComponent<Projectile>().splashDamage : nonProjectileDamage; [Header("Turret")] public TurretType turretType; public float range; [Range(0, 180)] public float hitAngle = 30; public GameObject projectile; public float nonProjectileDamage; public float fireRate; [Header("UnitLauncher")] public UnitData unit; public int amount; public int capacity; public float firstSpawnTime; public float spawnDelta; } } }
using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; namespace OmniSharp.Extensions.DebugAdapter.Protocol.Client { /// <summary> /// Gives your class or handler an opportunity to interact with /// the <see cref="InitializeRequestArguments" /> and <see cref="InitializeResponse" /> before it is processed by the client. /// </summary> public delegate Task OnDebugAdapterClientInitializedDelegate( IDebugAdapterClient client, InitializeRequestArguments request, InitializeResponse response, CancellationToken cancellationToken ); }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; namespace HOANGTUYEN_LAND { public partial class test_csdl : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btn_connect_Click(object sender, EventArgs e) { DatabaseConnection db = new DatabaseConnection(); try { db.Create_connect(); Response.Write("Conected success!"); DataSet ds = new DataSet(); ds = db.Get_data("Select * from NGUOIDUNG"); GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); } catch(Exception E) { Response.Write("Conected fail!"); } } } }
using D_API.SettingsTypes; using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; namespace D_API.Configurer.Lib { public class APISettingsConfigBuilder : NotifyPropertyChanged { private long? eventChannelId; private string? telegramKey; public virtual ObservableCollection<long> AllowedUsers { get; } = new(); public virtual APISettingsSecurityBuilder Security { get; } = new(); public virtual APISettingsDbConnectionBuilder Database { get; } = new(); public virtual long? EventChannelId { get => eventChannelId; set => NotifySet(ref eventChannelId, value); } public virtual string? TelegramAPIKey { get => telegramKey; set => NotifySet(ref telegramKey, value); } public virtual APISettings Build() => new() { AllowedUsers = new(AllowedUsers), EventChannelId = eventChannelId, Security = Security.Build(), TelegramAPIKey = telegramKey, UserDataDbConnectionSettings = Database.Build() }; public class APISettingsDbConnectionBuilder : NotifyPropertyChanged { private DbEndpoint endpoint; private string? connstring; public virtual DbEndpoint Endpoint { get => endpoint; set => NotifySet(ref endpoint, value); } public virtual string? ConnectionString { get => connstring; set => NotifySet(ref connstring, value); } public virtual DbConnectionSettings Build() => new(endpoint, connstring); } public class APISettingsSecurityBuilder : NotifyPropertyChanged { private string? audience; private string? issuer; private string? encryptioniv; private string? encryptionkey; private string? jwtKey; private string? hashKey; public virtual string? JWTKey { get => jwtKey; set => NotifySet(ref jwtKey, value); } public virtual string? EncryptionIV { get => encryptioniv; set => NotifySet(ref encryptioniv, value); } public virtual string? EncryptionKey { get => encryptionkey; set => NotifySet(ref encryptionkey, value); } public virtual string? HashKey { get => hashKey; set => NotifySet(ref hashKey, value); } public virtual string? Audience { get => audience; set => NotifySet(ref audience, value); } public virtual string? Issuer { get => audience; set => NotifySet(ref issuer, value); } public virtual Security Build() => new(audience, issuer, jwtKey, HashKey, encryptioniv, encryptioniv); } } }
using System; using SIS.MvcFramework; namespace MishMash { class Program { static void Main() { WebHost.Start(new StartUp()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.DomesticTicket.Platform.Plugin { /// <summary> /// 接口平台绑定的代付方式 /// </summary> public enum EnumPaidMethod { 未知 = -1, 支付宝 = 0, 快钱 = 1, 财付通 = 2, 汇付 = 3, 预存款 = 4 } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Windows.Forms; using CafeMana.DTO; namespace CafeMana.DAL { class DataAccess { private static DataAccess _Instance; internal static DataAccess Instance { get { if (_Instance == null) _Instance = new DataAccess(); return _Instance; } private set { _Instance = value; } } private DataAccess() { } #region Product public List<Product> RetreiveAllProducts() { List<Product> ProductsList = new List<Product>(); using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { SqlCommand command = new SqlCommand("SELECT * FROM Products;", connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { int _ID = reader.GetInt32(0); string _Name = reader.GetString(1); decimal _Price = reader.GetDecimal(2); int _CatagoryID = reader.GetInt32(3); string _Description = reader.GetString(4); byte[] _Image = (byte[])reader[5]; ProductsList.Add(new Product() { ID = _ID, Name = _Name, Description = _Description, Image = _Image, CatagoryID = _CatagoryID, Price = _Price }); } } reader.Close(); return ProductsList; } } public bool AddNewProduct(Product product) { using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.Parameters.AddWithValue("@ProductName", product.Name); command.Parameters.AddWithValue("@ProductPrice", product.Price); command.Parameters.AddWithValue("@ProductCategoryID", product.CatagoryID); command.Parameters.AddWithValue("@ProductDescription", product.Description); command.Parameters.AddWithValue("@ProductImage", product.Image); command.CommandText = "Insert Into Products(ProductName, ProductPrice, ProductCategoryID, ProductDescription, ProductImage) Values (@ProductName,@ProductPrice,@ProductCategoryID,@ProductDescription,@ProductImage)"; if (command.ExecuteNonQuery() > 0) return true; return false; } } public bool UpdateProduct(Product product) { using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.Parameters.AddWithValue("@ProductName", product.Name); command.Parameters.AddWithValue("@ProductPrice", product.Price); command.Parameters.AddWithValue("@ProductCategoryID", product.CatagoryID); command.Parameters.AddWithValue("@ProductDescription", product.Description); command.Parameters.AddWithValue("@ProductImage", product.Image); command.CommandText = "Update Products Set ProductName=@ProductName,ProductPrice=@ProductPrice,ProductCategoryID=@ProductCategoryID,ProductDescription=@ProductDescription,ProductImage=@ProductImage Where ID="+product.ID+" "; if (command.ExecuteNonQuery() > 0) return true; return false; } } public int RetreiveIdentityProduct() { int Identity = 0; using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { SqlCommand command = new SqlCommand("SELECT IDENT_CURRENT('Products')", connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { Identity = Convert.ToInt32(reader[0].ToString()); } } reader.Close(); return Identity; } } #endregion #region Sale public List<Sale> RetreiveAllSales() { List<Sale> SalesList = new List<Sale>(); try { using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { SqlCommand command = new SqlCommand("SELECT * FROM Sales;", connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { int _ID = reader.GetInt32(0); DateTime _Time = reader.GetDateTime(1); int _SalesmanID = reader.GetInt32(2); decimal _CashGiven = reader.GetDecimal(3); decimal _Total = reader.GetDecimal(4); decimal _CashReturn = reader.GetDecimal(5); SalesList.Add(new Sale() { ID = _ID, Time = _Time, SalesManID = _SalesmanID, Total = _Total, CashGiven = _CashGiven, CashReturn = _CashReturn }); } } reader.Close(); return SalesList; } } catch (Exception er) { MessageBox.Show(er.Message); return null; } } public bool AddNewSale(Sale sale) { using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.Parameters.AddWithValue("@SaleTime", sale.Time); command.Parameters.AddWithValue("@SalesManID", sale.SalesManID); command.Parameters.AddWithValue("@CashGiven", sale.CashGiven); command.Parameters.AddWithValue("@TotalBill", sale.Total); command.Parameters.AddWithValue("@CashReturn", sale.CashReturn); command.CommandText = "Insert Into Sales(SaleTime, SalesManID, CashGiven, TotalBill, CashReturn) Values (@SaleTime,@SalesManID,@CashGiven,@TotalBill,@CashReturn)"; if (command.ExecuteNonQuery() > 0) return true; return false; } } #endregion #region SaleItem public List<SaleItem> RetreiveAllSaleItems() { List<SaleItem> SaleItemsList = new List<SaleItem>(); using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { SqlCommand command = new SqlCommand("SELECT * FROM SaleItems;", connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { int _ID = reader.GetInt32(0); string _ProductName = reader.GetString(1); decimal _ProductPrice = reader.GetDecimal(2); int _ProductQuantity = reader.GetInt32(3); decimal _ProductTotal = reader.GetDecimal(4); int _SaleID = reader.GetInt32(5); SaleItemsList.Add(new SaleItem() { ID = _ID, ProductName = _ProductName, ProductPrice = _ProductPrice, ProductQuantity = _ProductQuantity, ProductTotal = _ProductTotal, SaleID = _SaleID }); } } reader.Close(); return SaleItemsList; } } public bool AddNewSaleItem(SaleItem saleItem) { using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.Parameters.AddWithValue("@ProductName", saleItem.ProductName); command.Parameters.AddWithValue("@ProductPrice", saleItem.ProductPrice); command.Parameters.AddWithValue("@ProductQuantity", saleItem.ProductQuantity); command.Parameters.AddWithValue("@ProductTotal", saleItem.ProductTotal); command.Parameters.AddWithValue("@SaleID", saleItem.SaleID); command.CommandText = "Insert Into SaleItems(ProductName, ProductPrice, ProductQuantity, ProductTotal, SaleID) Values (@ProductName,@ProductPrice,@ProductQuantity,@ProductTotal,@SaleID)"; if (command.ExecuteNonQuery() > 0) return true; return false; } } #endregion #region Category public List<Category> RetreiveAllCategories() { List<Category> CategoriesList = new List<Category>(); using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { SqlCommand command = new SqlCommand("SELECT * FROM Categories;", connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { int _ID = reader.GetInt32(0); string _Name = reader.GetString(1); string _Description = reader.GetString(2); byte[] _Image = (byte[])reader[3]; CategoriesList.Add(new Category() { ID = _ID, Name = _Name, Description = _Description, Image = _Image }); } } reader.Close(); return CategoriesList; } } public bool AddNewCategory(Category category) { using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.Parameters.AddWithValue("@CategoryName", category.Name); command.Parameters.AddWithValue("@CategoryDescription", category.Description); command.Parameters.AddWithValue("@CategoryPicture", category.Image); command.CommandText = "Insert Into Categories(CategoryName, CategoryDescription, CategoryPicture) Values (@CategoryName,@CategoryDescription,@CategoryPicture)"; if (command.ExecuteNonQuery() > 0) return true; return false; } } public bool UpdateCategory(Category category) { using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.Parameters.AddWithValue("@CategoryName", category.Name); command.Parameters.AddWithValue("@CategoryDescription", category.Description); command.Parameters.AddWithValue("@CategoryPicture", category.Image); command.Parameters.AddWithValue("@CategoryID", category.ID); command.CommandText = "Update Categories set CategoryName=@CategoryName , CategoryDescription= @CategoryDescription , CategoryPicture=@CategoryPicture where ID= @CategoryID"; if (command.ExecuteNonQuery() > 0) return true; return false; } } public int RetreiveIdentityCategory() { int Identity = 0; using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { SqlCommand command = new SqlCommand("SELECT IDENT_CURRENT('Categories')", connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { Identity = Convert.ToInt32(reader[0].ToString()); } } reader.Close(); return Identity; } } #endregion #region User public List<User> RetreiveAllUsers() { List<User> UsersList = new List<User>(); using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { SqlCommand command = new SqlCommand("SELECT * FROM Users;", connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { int _ID = reader.GetInt32(0); string _Name = reader.GetString(1); string _Role = reader.GetString(2); string _Email = reader.GetString(3); string _Password = reader.GetString(4); UsersList.Add(new User() { ID = _ID, Name = _Name, Role = _Role, Email = _Email, Password = _Password }); } } reader.Close(); return UsersList; } } public bool AddNewUser(User user) { using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.Parameters.AddWithValue("@Name", user.Name); command.Parameters.AddWithValue("@Role", user.Role); command.Parameters.AddWithValue("@Email", user.Email); command.Parameters.AddWithValue("@Password", user.Password); command.CommandText = "Insert Into Users(Name, Role, Email,Password) Values (@Name,@Role,@Email,@Password)"; if (command.ExecuteNonQuery() > 0) return true; return false; } } public bool UpdateUser(User user) { using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.Parameters.AddWithValue("@ID", user.ID); command.Parameters.AddWithValue("@Name", user.Name); command.Parameters.AddWithValue("@Role", user.Role); command.Parameters.AddWithValue("@Email", user.Email); command.Parameters.AddWithValue("@Password", user.Password); command.CommandText = "Update Users Set Name=@Name , Role= @Role , Email=@Email ,Password=@Password Where ID= @ID"; if (command.ExecuteNonQuery() > 0) return true; return false; } } public int RetreiveIdentityUser() { int Identity = 0; using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { SqlCommand command = new SqlCommand("SELECT IDENT_CURRENT('Users')", connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { Identity = Convert.ToInt32(reader[0].ToString()); } } reader.Close(); return Identity; } } #endregion public bool DeleteSomething(int ID, string s) { try { using (SqlConnection connection = new SqlConnection(ConnectionString.connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandText = "Delete " + s + " Where ID=" + ID + " "; command.ExecuteNonQuery(); connection.Close(); return true; } } catch { return false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using GameOnTheHouse.Data; using Microsoft.AspNetCore.Mvc; namespace GameOnTheHouse.Controllers { public class UserController : Controller { private readonly AppDbContext _db; public UserController(AppDbContext context) { _db = context; } // GET: /<controller>/ public IActionResult Index(string color="black") { string img = "https://www.freeiconspng.com/uploads/controller-game-icon-10.png"; ViewData["img"] = img; ViewData["color"] = color; return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MGL_API.Model.Entity.GameDetail { public class ArmazenamentoEntity { } }
/*using System; //header file .NET used in namespace namespace Basiceg { class Hello_world { static void Main() { //to print in console window Console.Write("Hello, world!"); //to print in proper format Console.WriteLine("Hello, world!"); //Print your name string myname = "Hitarsh",Fathername = "Prakash"; Console.WriteLine(myname); //Concatenation Console.WriteLine("Concatenation"); Console.WriteLine("MyName:"+ myname); Console.WriteLine("----------------------------------------------"); //PlaceHolder Console.WriteLine("Placeholder"); Console.WriteLine("MyName:{0}", myname); Console.WriteLine("MyName:{0}, Fathername:{1}", myname, Fathername); Console.WriteLine("Fathername:{1}-MyName:{0}", myname, Fathername); //to read from console Console.Read(); } } } */
using System; using System.Collections.Generic; namespace exemplo1 { class Program { static void Main(string[] args) { // Exemplo com HashSet HashSet<string> conjuntoHSet = new HashSet<string>(); conjuntoHSet.Add("TV"); conjuntoHSet.Add("Notebook"); conjuntoHSet.Add("Tablet"); conjuntoHSet.Add("Smartphone"); // Verifica se no conjunto existe o objeto do parâmetro Console.WriteLine(conjuntoHSet.Contains("Notebook")); // Utiliza-se o foreach porque não é possível utilizar o for, pois os elementos de um conjunto ão têm posição foreach (string item in conjuntoHSet) { Console.WriteLine(item); } } } }
using System; namespace PropOhGate.Runner { using PropOhGate.Collection; using PropOhGate.Receive; using PropOhGate.Receive.Test; using PropOhGate.Send.Test; using PropOhGate.WebSockets.Receive; using PropOhGate.WebSockets.Send; class Program { static void Main(string[] args) { var repository = new PlanetRepository(); var childRepository = new PlanetRepository(); var collection = new RepositoryObservableCollection<Planet>(childRepository); /* var sendListener = new TestSendListener(repository); var receiver = new TestReceiver(); var receiveListener = new ReceiveListener(childRepository, receiver); receiveListener.Start(); sendListener.Listen(receiver); */ childRepository.SubscribeToRowAdded(r => Console.WriteLine("Row Added with Id {0}", r.RowId)); childRepository.SubscribeToRowRemoved(r => Console.WriteLine("Row Removed with Id {0}", r.RowId)); childRepository.SubscribeToCellUpdated(u => Console.WriteLine("Cell" + "Updated {0}:{1}:{2}", u.RowId, u.ColumnId, u)); var mercury = repository.AddRow("Mercury", 57900000, TimeSpan.FromDays(59), 0.38); var venus = repository.AddRow("Venus", 108160000, TimeSpan.FromDays(243), 0.9); var earth = repository.AddRow("Earth", 149600000, TimeSpan.FromHours(23) + TimeSpan.FromMinutes(56), 1); var mars = repository.AddRow("Mars", 141700000, TimeSpan.FromHours(24) + TimeSpan.FromMinutes(37), 0.38); var jupiter = repository.AddRow("Jupiter", 778369000, TimeSpan.FromHours(9) + TimeSpan.FromMinutes(55), 2.64); var saturn = repository.AddRow("Saturn", 1427034000, TimeSpan.FromHours(10) + TimeSpan.FromMinutes(39), 1.16); var uranus = repository.AddRow("Uranus", 2870658186, TimeSpan.FromHours(17) + TimeSpan.FromMinutes(14), 1.11); var neptune = repository.AddRow("Neptune", 4496976000, TimeSpan.FromHours(16) + TimeSpan.FromMinutes(7), 1.21); var sendListener = new WebSocketSendListener(repository); var receiver = new WebSocketReceiver("ws://localhost:8080/planet", childRepository.GetRepositoryHash()); var receiveListener = new ReceiveListener(childRepository, receiver); receiveListener.Start(); sendListener.Start("ws://0.0.0.0:8080/planet"); Console.ReadKey(); Console.WriteLine(childRepository.ToString()); venus.Set(repository.Gravity,0.88); saturn.Set(repository.DistanceFromSun, 1427034111); repository.RemoveRow(uranus); var uranus2 = repository.AddRow("Uranus II", 2870658186, TimeSpan.FromHours(17) + TimeSpan.FromMinutes(14), 1.11); Console.WriteLine(); Console.WriteLine(childRepository.ToString()); Console.ReadKey(); } } }
using System; namespace IoUring { [Flags] public enum SubmissionOption : byte { /// <summary> /// No option selected. /// </summary> None = 0x00, /// <summary> /// When this flag is specified, fd is an index into the files array registered with /// the <see cref="Ring"/> instance. <seealso cref="Ring.RegisterFiles"/> /// </summary> /// <remarks>Available since 5.1</remarks> FixedFile = 1 << 0, // IOSQE_FIXED_FILE /// <summary> /// When this flag is specified, the SQE will not be started before previously /// submitted SQEs have completed, and new SQEs will not be started before this /// one completes. /// </summary> /// <remarks>Available since 5.2.</remarks> Drain = 1 << 1, // IOSQE_IO_DRAIN /// <summary> /// When this flag is specified, it forms a link with the next SQE in the /// submission ring. That next SQE will not be started before this one completes. /// This, in effect, forms a chain of SQEs, which can be arbitrarily long. The tail /// of the chain is denoted by the first SQE that does not have this flag set. /// This flag has no effect on previous SQE submissions, nor does it impact SQEs /// that are outside of the chain tail. This means that multiple chains can be /// executing in parallel, or chains and individual SQEs. Only members inside the /// chain are serialized. A chain of SQEs will be broken, if any request in that /// chain ends in error. io_uring considers any unexpected result an error. This /// means that, eg, a short read will also terminate the remainder of the chain. /// If a chain of SQE links is broken, the remaining unstarted part of the chain /// will be terminated and completed with <code>-ECANCELED</code> as the error code. /// </summary> /// <remarks>Available since 5.3.</remarks> Link = 1 << 2, // IOSQE_IO_LINK /// <summary> /// Like IOSQE_IO_LINK, but it doesn't sever regardless of the completion result. /// Note that the link will still sever if we fail submitting the parent request, /// hard links are only resilient in the presence of completion results for /// requests that did submit correctly. <see cref="HardLink"/> implies <see cref="Link"/>. /// </summary> /// <remarks>Available since 5.5.</remarks> HardLink = 1 << 3, // IOSQE_IO_HARDLINK /// <summary> /// Normal operation for io_uring is to try and issue an sqe as non-blocking first, /// and if that fails, execute it in an async manner. To support more efficient /// overlapped operation of requests that the application knows/assumes will /// always (or most of the time) block, the application can ask for an sqe to be /// issued async from the start. /// </summary> /// <remarks>Available since 5.6</remarks> Async = 1 << 4, // IOSQE_ASYNC } }
using UnityEngine; using System.Collections; namespace Ai { public class EngineerAi : ICharacterAi { protected override void CreateBehaviours() { base.CreateBehaviours(); Behaviours[AiState.Skill] = new EngineerSkillBehaviour(this); } } }
 /* Part of Saboteur Remake * * Changes: * 0.22, 01-jun-2018, Nacho: Items in first plane are read from the (big) map * and drawn using "DrawItems" * 0.21, 01-jun-2018, Nacho: Enemies and dogs are read from the (big) map * 0.19, 01-jun-2018, Nacho: A few more tiles are displayed * 0.18, 31-may-2018, Nacho: Can move left, right, up & down in big map * Row and column switched in GetRoomData * Bricks are represented with "+" in the map * 0.17, 31-may-2018, Nacho: Only one big map, first approach * 0.15, 29-may-2018, Nacho: Added CanMoveEnemyTo(x1, y1, x2, y2) * 0.13, 24-may-2018, Nacho: Player can move upstairs and downstairs, * even to different rooms (remaining: collisions on end of stairs) * 0.12, 23-may-2018, Nacho: IsThereVerticalStair implemented (bouncing boxes) * 0.10, 21-may-2018, Nacho: * try-catch for error handling in LoadRoom * The room can contain enemies and dogs * 0.09, 18-may-2018, Nacho: Fine tuned right and left margins for the player * 0.08, 17-may-2018, Nacho: CanMoveTo implemented (bouncing boxes) * 0.07, 14-may-2018, Nacho: Retro/updated look changeable * 0.06, 12-may-2018, Nacho: room data was loaded in Draw, now in constructor * LoadRoom receives room number, instead of filename * 0.05b, 11-may-2018, Daniel Miquel, Luis Martin: Room with stairs. * 0.05, 11-may-2018, Santana, Saorin, Sabater: Save data info of close rooms from a file. * 0.04. 11-may-2018, Nacho: Rooms with more detailed definition can be read from file * 0.03, 10-may-2018, Pestana, Saorin: Load map from a file. * * 0.02, 09-may-2018, Santana,Saorin: Replace with tiles for the real map * of the room (started) * 0.01, 09-may-2018, Nacho: First version, almost empty skeleton */ using System.Collections.Generic; using System.IO; using System; /// Room - Represents one of the rooms that the user can visit class Room { Image tmpBackground; char[,] background; Image brick, brickD, brickL; Image ground; Image window; Image door; Image tileStairLeft; Image tileStairRight; List<Enemy> enemies; List<Dog> dogs; List<Sprite> items; int roomWidth; int roomHeight; int currentRoom; int currentCol; int currentRow; int leftRoom; int rightRoom; int upRoom; int bottomRoom; int screenWidth = 1024; Complex myComplex; public Room(Complex c, bool retroLook) { roomWidth = 32; roomHeight = 17; string folder = "imgRetro"; if (!retroLook) folder = "imgUpdated"; tmpBackground = new Image("data/" + folder + "/exampleRoom.png"); background = new char[roomWidth, roomHeight]; brick = new Image("data/" + folder + "/tileWall1.png"); ground = new Image("data/" + folder + "/tileFloor.png"); brickD = new Image("data/" + folder + "/tileWall2.png"); brickL = new Image("data/" + folder + "/tileWall4.png"); door = new Image("data/" + folder + "/tileWall3.png"); tileStairLeft = new Image("data/" + folder + "/tileStairLeft.png"); tileStairRight = new Image("data/" + folder + "/tileStairRight.png"); currentCol = 6; // Starting room currentRow = 9; myComplex = c; Load(myComplex, currentCol, currentRow); } public void Load(Complex c, int col, int row) { background = c.GetRoomData(col, row); enemies = new List<Enemy>(); dogs = new List<Dog>(); items = new List<Sprite>(); GenerateEnemiesAndItems(); } public void MoveToRoomRight() { currentCol++; Load(myComplex, currentCol, currentRow); } public void MoveToRoomLeft() { currentCol--; Load(myComplex, currentCol, currentRow); } public void MoveToRoomUp() { currentRow--; Load(myComplex, currentCol, currentRow); } public void MoveToRoomDown() { currentRow++; Load(myComplex, currentCol, currentRow); } public void GenerateEnemiesAndItems() { for (int i = 0; i < roomWidth; i++) { for (int j = 0; j < roomHeight; j++) { if (background[i, j] == '1') { background[i, j] = background[i+1, j]; Dog d = new Dog(); int x = i * 32; int y = j * 32; dogs.Add(d); d.MoveTo(x, y); } if (background[i, j] == '2') { background[i, j] = background[i + 1, j]; Enemy e = new Enemy(); int x = i * 32; int y = j * 32; enemies.Add(e); e.MoveTo(x, y); } if (background[i, j] == 'P') { background[i, j] = background[i + 1, j]; Sprite s = new Sprite(); s.LoadImage("data\\imgRetro\\objPlates5.png"); int x = i * 32; int y = j * 32; items.Add(s); s.MoveTo(x, y); } if (background[i, j] == 'p') { background[i, j] = background[i + 1, j]; Sprite s = new Sprite(); s.LoadImage("data\\imgRetro\\objPlates3.png"); int x = i * 32; int y = j * 32; items.Add(s); s.MoveTo(x, y); } } } } /* /// <summary> /// Loads the data for a room from file /// </summary> /// <param name="n">Number of room</param> public void Load(int n) { try { string levelFileName = "data/room" + n.ToString("000") + ".dat"; StreamReader input = new StreamReader(levelFileName); string line = ""; int row = 0; for (int l = 0; l < roomHeight; l++) { line = input.ReadLine(); if (line != null) { for (int col = 0; col < line.Length; col++) { switch (line[col]) { case 'b': background[col, row] = 'b'; break; case 'g': background[col, row] = 'g'; break; case 'w': background[col, row] = 'w'; break; case 'd': background[col, row] = 'd'; break; case '<': background[col, row] = '<'; break; case '>': background[col, row] = '>'; break; default: break; } } row++; } } // Read and parse extra room details string roomNumber = input.ReadLine().Split('=')[1]; currentRoom = int.Parse(roomNumber); roomNumber = input.ReadLine().Split('=')[1]; if (roomNumber.ToUpper() != "NOT") leftRoom = int.Parse(roomNumber); else leftRoom = -1; roomNumber = input.ReadLine().Split('=')[1]; if (roomNumber.ToUpper() != "NOT") rightRoom = int.Parse(roomNumber); else rightRoom = -1; roomNumber = input.ReadLine().Split('=')[1]; if (roomNumber.ToUpper() != "NOT") upRoom = int.Parse(roomNumber); else upRoom = -1; roomNumber = input.ReadLine().Split('=')[1]; if (roomNumber.ToUpper() != "NOT") bottomRoom = int.Parse(roomNumber); else bottomRoom = -1; dogs = new List<Dog>(); string[] dogDetails = input.ReadLine().Split('='); int numDogs = Convert.ToInt32(dogDetails[1]); for (int i = 0; i < numDogs; i++) { Dog d = new Dog(); string[] posDetails = dogDetails[2 + i].Split(','); int x = Convert.ToInt32(posDetails[0]); int y = Convert.ToInt32(posDetails[1]); dogs.Add(d); d.MoveTo(x, y); } enemies = new List<Enemy>(); string[] enemiesDetails = input.ReadLine().Split('='); int numEnemies = Convert.ToInt32(enemiesDetails[1]); for (int i = 0; i < numEnemies; i++) { Enemy e = new Enemy(); string[] posDetails = enemiesDetails[2 + i].Split(','); int x = Convert.ToInt32(posDetails[0]); int y = Convert.ToInt32(posDetails[1]); enemies.Add(e); e.MoveTo(x, y); } input.Close(); } catch (Exception e) { File.WriteAllLines("roomError.log", new string[] { "Error loading room: ", e.Message }); } } */ public void Draw() { for (int i = 0; i < roomWidth; i++) { for (int j = 0; j < roomHeight; j++) { switch (background[i,j]) { case '+': SdlHardware.DrawHiddenImage(brick, i * 32, j * 32); break; case 'D': SdlHardware.DrawHiddenImage(brickD, i * 32, j * 32); break; case 'L': SdlHardware.DrawHiddenImage(brickL, i * 32, j * 32); break; case 'g': SdlHardware.DrawHiddenImage(ground, i * 32, j * 32); break; case 'w': SdlHardware.DrawHiddenImage(window, i * 32, j * 32); break; case 'd': SdlHardware.DrawHiddenImage(door, i * 32, j * 32); break; case '<': SdlHardware.DrawHiddenImage(tileStairLeft, i * 32, j * 32); break; case '>': SdlHardware.DrawHiddenImage(tileStairRight, i * 32, j * 32); break; default: break; } } } } public void DrawItems() { foreach (Sprite s in items) { s.DrawOnHiddenScreen(); } } public bool CanMoveEnemyTo(int x1, int y1, int x2, int y2) { if (x1 < 0) return false; if (x2 > screenWidth) return false; return CanMoveTo(x1, y1, x2, y2); } public bool CanMoveTo(int x1, int y1, int x2, int y2) { // Let's assume only background (tile "g") cannot be crossed now for (int i = 0; i < roomWidth; i++) { for (int j = 0; j < roomHeight; j++) { char tile = background[i, j]; if (tile == 'g') { int x1t = i * 32; int y1t = j * 32; int x2t = x1t + 32; int y2t = y1t + 32; if ((x1t < x2) && (x2t > x1) && (y1t < y2) && (y2t > y1) // Collision as bouncing boxes ) return false; } } } return true; } public bool IsThereVerticalStair(int x1, int y1, int x2, int y2) { // "<" and ">" are the symbols for the stairs for (int i = 0; i < roomWidth; i++) { for (int j = 0; j < roomHeight; j++) { char tile = background[i, j]; if ((tile == '<') || (tile == '>')) { int x1t = i * 32; int y1t = j * 32; int x2t = x1t + 32; int y2t = y1t + 32; if ((x1t < x2) && (x2t > x1) && (y1t < y2) && (y2t > y1) // Collision as bouncing boxes ) return true; } } } return false; } /// Return the number of the next room if is accesible, if it is not return -1. public int CheckIfNewRoom(Player player) { if (player.GetX() >= roomWidth * 32 - player.GetWidth()) return rightRoom; else if (player.GetX() < 0) return leftRoom; else if (player.GetY() <= 20) return upRoom; else if(player.GetY() >= roomHeight * 32 - player.GetHeight()) return bottomRoom; else return -1; } public List<Dog> GetDogs() { return dogs; } public List<Enemy> GetEnemies() { return enemies; } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Voronov.Nsudotnet.BuildingCompanyIS.Interfaces { interface IWorkProcedure { string Name { get; } DateTime? StartTime { get; } DateTime? EndTime { get; } } }
namespace _3.DependencyInversion.Strategies { public class DivideStrategy : IStrategy { public int Calculate(int first, int second) { return first / second; } } }
using System; using System.Collections.Generic; 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; using System.Windows.Threading; using System.Diagnostics; namespace OPTI_Experiment { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private Boolean IsQWERTY_First = true; private Boolean IsOPTI_Turn; private DispatcherTimer TaskTimer = new DispatcherTimer(); private Stopwatch TaskStopWatch; private String CurrTimeLabel = String.Empty; private TimeSpan CurrTimeSpan; private Int32 Stage = 0; private Int32 CurrInputIndex = 0; private String CurrPhrase; private MediaPlayer MP_tick; private MediaPlayer MP_beep; public MainWindow() { InitializeComponent(); MainController.Instance._MainWindow = this; MainController.Instance._OPTI = OPTI_Control; MainController.Instance._QWERTY = QWERTY_Control; SessionManager.Instance.ReadSamples(); InitializeMediaPlayers(); TaskTimer.Tick += new EventHandler(TaskTimer_Tick); TaskTimer.Interval = new TimeSpan(0, 0, 0, 0, 1); } private void InitializeMediaPlayers() { MP_tick = new MediaPlayer(); MP_beep = new MediaPlayer(); MP_tick.Open(new Uri("./tick.mp3", UriKind.Relative)); MP_beep.Open(new Uri("./beep.mp3", UriKind.Relative)); } protected override void OnSourceInitialized(EventArgs e) { WindowStyleHelper.RemoveIcon(this); } public void ApplyKeyStrokeInput(String input) { // 준비 상태이면 글자 체크 및 수치 계산 등을 하지 않음 if (Stage == 0) return; MP_tick.Stop(); MP_beep.Stop(); MP_tick.Position = TimeSpan.Zero; MP_beep.Position = TimeSpan.Zero; if (input == "SPACE") input = " "; InputText.Text += input; String answer = CurrPhrase.Substring(CurrInputIndex, 1); if (input != answer) { // 틀린 글자 입력시 SessionManager.Instance.ErrorLetterNum++; MP_beep.Play(); } else { // 알맞은 글자 입력시 MP_tick.Play(); } SessionManager.Instance.LetterNum++; CurrInputIndex++; // 현재 문장을 모두 입력하였으면 새로운 문장을 불러온다. if (InputText.Text.Length == TaskText.Text.Length) { CurrPhrase = SessionManager.Instance.GetSamplePhrase(); InputText.Text = ""; CurrInputIndex = 0; InitializeMediaPlayers(); } RefreshTaskPhrase(); } public void RefreshTaskPhrase() { String first = CurrPhrase.Substring(0, CurrInputIndex); String highlight = CurrPhrase.Substring(CurrInputIndex, 1); if (highlight == " ") highlight = "_"; String last = CurrPhrase.Substring(CurrInputIndex + 1, CurrPhrase.Length - CurrInputIndex - 1); TaskText.Inlines.Clear(); TaskText.Inlines.Add(new Run(first)); Run highlightRun = new Run(); highlightRun.Foreground = Brushes.Red; highlightRun.Text = highlight; highlightRun.FontWeight = FontWeights.Bold; TaskText.Inlines.Add(highlightRun); TaskText.Inlines.Add(new Run(last)); } public void RefreshStage() { if (Stage == 0) // READY { QWERTYRecord.Content = "QWERTY : "; OPTIRecord.Content = "OPTI : "; QWERTYError.Content = "QWERTY : "; OPTIError.Content = "OPTI : "; InputText.Text = ""; InfoText.Visibility = Visibility.Visible; CurrTimeSpan = SessionManager.Instance.ReadyTimeSpan; } else if (Stage == 1) // TASK 1 { InfoText.Visibility = Visibility.Collapsed; InitializeKeyBoardLayout(true); SessionManager.Instance.InitializeSession(); CurrInputIndex = 0; CurrPhrase = SessionManager.Instance.GetSamplePhrase(); RefreshTaskPhrase(); CurrTimeSpan = SessionManager.Instance.TaskTimeSpan; TaskStopWatch.Restart(); } else if (Stage == 2) // REST { Double record = SessionManager.Instance.GetWordPerMinute(); Double record2 = SessionManager.Instance.GetErrorRate(); MessageBox.Show("Entry Speed: " + record + " wpm\n" + "Error Rate : " + record2 + "%", "Session Result"); if (IsOPTI_Turn == true) { OPTIRecord.Content = "OPTI : " + record.ToString(); OPTIError.Content = "OPTI : " + record2.ToString(); } else { QWERTYRecord.Content = "QWERTY : " + record.ToString(); QWERTYError.Content = "QWERTY : " + record2.ToString(); } InfoText.Visibility = Visibility.Visible; ClearKeyBoardLayout(); TaskText.Text = ""; InputText.Text = ""; CurrTimeSpan = SessionManager.Instance.RestTimeSpan; TaskStopWatch.Restart(); } else if (Stage == 3) // TASK 2 { InfoText.Visibility = Visibility.Collapsed; InitializeKeyBoardLayout(false); SessionManager.Instance.InitializeSession(); CurrInputIndex = 0; CurrPhrase = SessionManager.Instance.GetSamplePhrase(); RefreshTaskPhrase(); CurrTimeSpan = SessionManager.Instance.TaskTimeSpan; TaskStopWatch.Restart(); } else { Double record = SessionManager.Instance.GetWordPerMinute(); Double record2 = SessionManager.Instance.GetErrorRate(); MessageBox.Show("Entry Speed: " + record + " wpm\n" + "Error Rate : " + record2 + "%", "Session Result"); if (IsOPTI_Turn == true) { OPTIRecord.Content = "OPTI : " + record.ToString(); OPTIError.Content = "OPTI : " + record2.ToString(); } else { QWERTYRecord.Content = "QWERTY : " + record.ToString(); QWERTYError.Content = "QWERTY : " + record2.ToString(); } ClearKeyBoardLayout(); TaskText.Text = ""; InputText.Text = ""; TaskStopWatch.Stop(); } } private void TaskTimer_Tick(object sender, EventArgs e) { if (TaskStopWatch.IsRunning == true) { TimeSpan ts = CurrTimeSpan - TaskStopWatch.Elapsed; StopWatchLabel.Content = CurrTimeLabel; CurrTimeLabel = String.Format("{0:00}:{1:00}", ts.Minutes, ts.Seconds); if (CurrTimeLabel == "00:00") { InfoText.Content = "START!"; } else { InfoText.Content = "READY ( " + CurrTimeLabel + " )"; } if (ts.Ticks < 0) { Stage++; RefreshStage(); } } } private void InitializeKeyBoardLayout(Boolean isFirst) { IsOPTI_Turn = IsQWERTY_First ^ isFirst; if (IsOPTI_Turn == true) { QWERTY_Control.Visibility = Visibility.Collapsed; OPTI_Control.Visibility = Visibility.Visible; } else { QWERTY_Control.Visibility = Visibility.Visible; OPTI_Control.Visibility = Visibility.Collapsed; } } private void ClearKeyBoardLayout() { QWERTY_Control.Visibility = Visibility.Collapsed; OPTI_Control.Visibility = Visibility.Collapsed; } private void QWERTY_Practice_Activate(object sender, RoutedEventArgs e) { QWERTY_Control.Visibility = Visibility.Visible; OPTI_Control.Visibility = Visibility.Collapsed; } private void OPTI_Practice_Activate(object sender, RoutedEventArgs e) { QWERTY_Control.Visibility = Visibility.Collapsed; OPTI_Control.Visibility = Visibility.Visible; } private void Clear_Practice_Activate(object sender, RoutedEventArgs e) { InputText.Text = ""; ClearKeyBoardLayout(); } private void Session_Start(object sender, RoutedEventArgs e) { QWERTY_Practice.IsEnabled = false; OPTI_Practice.IsEnabled = false; Clear_Practice.IsEnabled = false; TaskStopWatch = new Stopwatch(); TaskStopWatch.Start(); Stage = 0; ClearKeyBoardLayout(); RefreshStage(); TaskTimer.Start(); } private void Session_Stop(object sender, RoutedEventArgs e) { if (TaskStopWatch.IsRunning) { TaskStopWatch.Stop(); TaskStopWatch.Reset(); InfoText.Visibility = Visibility.Collapsed; ClearKeyBoardLayout(); TaskText.Text = ""; InputText.Text = ""; } QWERTY_Practice.IsEnabled = true; OPTI_Practice.IsEnabled = true; Clear_Practice.IsEnabled = true; } private void Layout_First_Checked(object sender, RoutedEventArgs e) { RadioButton rb = (RadioButton)sender; String id = (String) rb.Tag; if (id == "0" || id == null) { IsQWERTY_First = true; } else { IsQWERTY_First = false; } } } }
using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.DebugAdapter.Protocol { namespace Requests { [Parallel] [Method(RequestNames.SetVariable, Direction.ClientToServer)] [GenerateHandler] [GenerateHandlerMethods] [GenerateRequestMethods] public record SetVariableArguments : IRequest<SetVariableResponse> { /// <summary> /// The reference of the variable container. /// </summary> public long VariablesReference { get; init; } /// <summary> /// The name of the variable in the container. /// </summary> public string Name { get; init; } = null!; /// <summary> /// The value of the variable. /// </summary> public string Value { get; init; } = null!; /// <summary> /// Specifies details on how to format the response value. /// </summary> [Optional] public ValueFormat? Format { get; init; } } public record SetVariableResponse { /// <summary> /// The new value of the variable. /// </summary> public string Value { get; init; } = null!; /// <summary> /// The type of the new value.Typically shown in the UI when hovering over the value. /// </summary> [Optional] public string? Type { get; init; } /// <summary> /// If variablesReference is > 0, the new value is structured and its children can be retrieved by passing variablesReference to the VariablesRequest. /// </summary> [Optional] public long? VariablesReference { get; init; } /// <summary> /// The number of named child variables. /// The client can use this optional information to present the variables in a paged UI and fetch them in chunks. /// </summary> [Optional] public long? NamedVariables { get; init; } /// <summary> /// The number of indexed child variables. /// The client can use this optional information to present the variables in a paged UI and fetch them in chunks. /// </summary> [Optional] public long? IndexedVariables { get; init; } } } }
namespace Belot.Engine.Tests.GameMechanics { using System.Collections.Generic; using Belot.Engine.Game; using Belot.Engine.GameMechanics; using Belot.Engine.Players; using Moq; using Xunit; public class RoundManagerTests { [Theory] [InlineData(BidType.AllTrumps, BidType.Pass, BidType.Pass, BidType.Pass, 26)] [InlineData(BidType.NoTrumps, BidType.Pass, BidType.Pass, BidType.Pass, 26)] [InlineData(BidType.Clubs, BidType.Pass, BidType.Pass, BidType.Pass, 16)] [InlineData(BidType.Pass, BidType.Pass, BidType.Pass, BidType.Pass, 0)] public void PlayTricksShouldReturnValidSouthNorthAndEastWesPoints( BidType southBidType, BidType eastBidType, BidType northBidType, BidType westBidType, int expectedTotalPoints) { var southPlayer = this.MockObject(southBidType); var eastPlayer = this.MockObject(eastBidType); var northPlayer = this.MockObject(northBidType); var westPlayer = this.MockObject(westBidType); var roundManager = new RoundManager(southPlayer, eastPlayer, northPlayer, westPlayer); var roundResult = roundManager.PlayRound(1, PlayerPosition.South, 0, 0, 0); var acutalTotalPoints = roundResult.EastWestPoints + roundResult.SouthNorthPoints; Assert.True(acutalTotalPoints >= expectedTotalPoints); } private IPlayer MockObject(BidType southBidType) { var player = new Mock<IPlayer>(); player.Setup(x => x.GetBid(It.IsAny<PlayerGetBidContext>())) .Returns(southBidType); player.Setup(x => x.GetAnnounces(It.IsAny<PlayerGetAnnouncesContext>())) .Returns(() => new List<Announce>()); player.Setup(x => x.PlayCard(It.IsAny<PlayerPlayCardContext>())) .Returns<PlayerPlayCardContext>(x => new PlayCardAction(x.AvailableCardsToPlay.RandomElement())); return player.Object; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Sterowanie : MonoBehaviour { public Rigidbody rb; public ConfigurableJoint CFJ; public float predkoscObrotu = 20; // Use this for initialization void Start () { } // Update is called once per frame void Update() { if (CFJ != null) { rb.constraints = RigidbodyConstraints.None; float r = Input.GetAxis("Obrot") * predkoscObrotu * Time.deltaTime; //qe obrot float z = Input.GetAxis("Horizontal") * predkoscObrotu * Time.deltaTime;//ad lewo prawo float x = Input.GetAxis("Vertical") * predkoscObrotu * Time.deltaTime;//ws gora dol transform.Rotate(x, z, r); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Data.SqlServerCe; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Security.Permissions; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Win32; /* * TODO: add search feature * TODO: text export of server list */ namespace Switchex { public partial class frmMain: Form { frmOptions frmOptions = new frmOptions(); frmProfiles frmProfiles = new frmProfiles(); frmAdd frmAdd = new frmAdd(); frmEdit frmEdit = new frmEdit(); frmAbout frmAbout = new frmAbout(); frmCreateRealmlist frmCreateRealmlist = new frmCreateRealmlist(); #region Main Events public frmMain() { InitializeComponent(); } private void frmMain_Load(object sender, EventArgs e) { string wowInstall = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); if(Properties.Settings.Default.firstRun) { using(RegistryKey key = Registry.LocalMachine.OpenSubKey(@"HKEY_LOCAL_MACHINE\SOFTWARE\Blizzard Entertainment\World of Warcraft")) { // if the registry key does not exist or InstallPath is blank if(key == null || key.GetValue("InstallPath").ToString() == "") { CheckForMainProfile(wowInstall); } // if the registry key exists else if(key != null) { wowInstall = key.GetValue("InstallPath").ToString(); CheckForMainProfile(wowInstall); if(!File.Exists(wowInstall + "\\Data\\enUS\\realmlist.wtf") && !File.Exists(wowInstall + "\\Data\\enGB\\realmlist.wtf")) { frmCreateRealmlist.ShowDialog(); } } } Properties.Settings.Default.firstRun = false; Properties.Settings.Default.Save(); } if(!Directory.Exists(Application.StartupPath + "\\Backups")) { Directory.CreateDirectory(Application.StartupPath + "\\Backups"); } CheckForMainProfile(wowInstall); Globals.GetProfiles(); AddProfilesToDropDown(); dgvServers.DefaultCellStyle.SelectionBackColor = Color.Gainsboro; dgvServers.DefaultCellStyle.SelectionForeColor = Color.Black; LoadColumnWidths(); LoadWindowSize(); RefreshList(); } private void dgvServers_CellContentClick(object sender, DataGridViewCellEventArgs e) { if(e.ColumnIndex == 3 && e.RowIndex != -1) { try { Process.Start(dgvServers.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()); } catch(Exception ex) { Globals.frmError.ShowDialog(ex); } } } private void btnAdd_Click(object sender, EventArgs e) { frmAdd.ShowDialog(); RefreshList(); } private void btnEdit_Click(object sender, EventArgs e) { if(dgvServers.SelectedRows.Count > 0) { frmEdit.ShowDialog(); RefreshList(); } else { MessageBox.Show("There is no row selected.", "Error"); } } private void btnSet_Click(object sender, EventArgs e) { if(dgvServers.SelectedRows.Count > 0) { try { Profile profile = Globals.profiles.SingleOrDefault(item => item.ProfileName == cmbProfiles.Text); if(profile != null) { string fileUS = profile.ProfilePath + "\\Data\\enUS\\realmlist.wtf", fileGB = profile.ProfilePath + "\\Data\\enGB\\realmlist.wtf", exec32 = profile.ProfilePath + "\\Wow.exe", exec64 = profile.ProfilePath + "\\Wow-64.exe", file = "", text = ""; // If realmlist.wtf does not exist if(!File.Exists(fileUS) && !File.Exists(fileGB)) { frmCreateRealmlist.ShowDialog(); } // If realmlist.wtf and WoW executables exist else { // If realmlist.wtf is in the US folder if(File.Exists(fileUS)) { file = fileUS; } // If realmlist.wtf is in the GB folder else if(File.Exists(fileGB)) { file = fileGB; } // Read from the file and replace text text = File.ReadAllText(file); text = text.Remove(14, text.Substring(14, text.IndexOf(Environment.NewLine) - 14).Length); text = text.Insert(14, dgvServers.SelectedRows[0].Cells[2].Value.ToString()); // Write the replaced text to a local file File.WriteAllText(Application.StartupPath + "\\realmlist.wtf", text); // And move it to the correct directory string[] args = { "true", Application.StartupPath + "\\realmlist.wtf", file }; int fileAction = Globals.RunActionsExecutable(Globals.FileAction.CopyFile, args); if(fileAction == 0) { // If they want to open WoW after setting a server if(Properties.Settings.Default.openWow) { OpenWow(); } else { MessageBox.Show("Server changed successfully.", "Success"); } ToolstripInfo(false); } else if(fileAction != 5) { MessageBox.Show("Could not set server.", "Error"); } } } else { MessageBox.Show("Cannot find a World of Warcraft installation with your current profile.", "Error"); } } catch(Exception ex) { if(!ex.Message.Contains("canceled by the user")) { Globals.frmError.ShowDialog(ex); } } } else { MessageBox.Show("There is no row selected.", "Error"); } } private void btnDelete_Click(object sender, EventArgs e) { if(dgvServers.SelectedRows.Count > 0) { DialogResult delete = MessageBox.Show("Are you sure you want to delete " + dgvServers.SelectedRows[0].Cells[1].Value + "?", "Delete", MessageBoxButtons.YesNo); if(delete == DialogResult.Yes) { DeleteServer(dgvServers.SelectedRows[0].Cells[1].Value.ToString(), dgvServers.SelectedRows[0].Cells[2].Value.ToString()); } RefreshList(); } else { MessageBox.Show("There are no rows selected.", "Error"); } } private void btnOpenWow_Click(object sender, EventArgs e) { OpenWow(); } private void btnCheckOnline_Click(object sender, EventArgs e) { CheckOnline(); } private void btnAddons_Click(object sender, EventArgs e) { frmAddons frmAddons = new frmAddons(); try { frmAddons.ShowDialog(); } catch(Exception ex) { Globals.frmError.ShowDialog(ex); } } private void cmbProfiles_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e) { if(e.ClickedItem != null) { cmbProfiles.Text = e.ClickedItem.Text; } } private void cmbProfiles_TextChanged(object sender, EventArgs e) { Properties.Settings.Default.currentProfile = cmbProfiles.Text; Globals.currentProfile = cmbProfiles.Text; if(cmbProfiles.Text == "All") { btnSet.Enabled = false; btnOpenWow.Enabled = false; btnAddons.Enabled = false; fileGameFolder.Enabled = false; fileAddonsFolder.Enabled = false; fileOpenRealmlist.Enabled = false; } else { btnSet.Enabled = true; btnOpenWow.Enabled = true; btnAddons.Enabled = true; fileGameFolder.Enabled = true; fileAddonsFolder.Enabled = true; fileOpenRealmlist.Enabled = true; } RefreshList(); } private void btnExit_Click(object sender, EventArgs e) { Application.Exit(); } private void frmMain_FormClosing(object sender, FormClosingEventArgs e) { if(!Globals.resetSettings) { Properties.Settings.Default.currentProfile = cmbProfiles.Text; Properties.Settings.Default.windowSize = Width + "," + Height; Properties.Settings.Default.columnWidths = dgvServers.Columns[0].Width + "," + dgvServers.Columns[1].Width + "," + dgvServers.Columns[2].Width + "," + dgvServers.Columns[3].Width + "," + dgvServers.Columns[4].Width + "," + dgvServers.Columns[5].Width + "," + dgvServers.Columns[6].Width + "," + dgvServers.Columns[7].Width; Properties.Settings.Default.Save(); } } private void dgvServers_SelectionChanged(object sender, EventArgs e) { if(dgvServers.Rows.Count > 0) { if(dgvServers.SelectedRows.Count > 0) { Globals.selectedName = dgvServers.SelectedRows[0].Cells[1].Value.ToString(); Globals.selectedIP = dgvServers.SelectedRows[0].Cells[2].Value.ToString(); Globals.selectedWebsite = dgvServers.SelectedRows[0].Cells[3].Value.ToString(); Globals.selectedPatch = dgvServers.SelectedRows[0].Cells[4].Value.ToString(); Globals.selectedRating = dgvServers.SelectedRows[0].Cells[5].Value.ToString(); Globals.selectedNotes = dgvServers.SelectedRows[0].Cells[6].Value.ToString(); Globals.selectedProfile = dgvServers.SelectedRows[0].Cells[7].Value.ToString(); Globals.selectedID = dgvServers.SelectedRows[0].Cells[8].Value.ToString(); } else { Globals.selectedName = null; Globals.selectedIP = null; Globals.selectedWebsite = null; Globals.selectedPatch = null; Globals.selectedRating = null; Globals.selectedNotes = null; Globals.selectedProfile = null; Globals.selectedID = null; } } } #endregion #region File Menu private void fileOptions_Click(object sender, EventArgs e) { frmOptions.ShowDialog(); RefreshList(); } private void fileProfiles_Click(object sender, EventArgs e) { frmProfiles.ShowDialog(); AddProfilesToDropDown(); RefreshList(); } private void fileGameFolder_Click(object sender, EventArgs e) { Profile profile = Globals.profiles.SingleOrDefault(item => item.ProfileName == Globals.currentProfile); if(profile != null) { Process.Start(profile.ProfilePath); } else { MessageBox.Show("Cannot find a World of Warcraft installation with the current profile.", "Error"); } } private void fileAddonsFolder_Click(object sender, EventArgs e) { Profile profile = Globals.profiles.SingleOrDefault(item => item.ProfileName == Globals.currentProfile); if(profile != null) { string addonsPath = profile.ProfilePath + "\\Interface\\Addons\\"; if(Directory.Exists(addonsPath)) { Process.Start(addonsPath); } else { MessageBox.Show("Cannot find a World of Warcraft addons folder with the current profile.", "Error"); } } else { MessageBox.Show("Cannot find a World of Warcraft addons folder with the current profile.", "Error"); } } private void fileOpenRealmlist_Click(object sender, EventArgs e) { Profile profile = Globals.profiles.SingleOrDefault(item => item.ProfileName == Globals.currentProfile); if(profile != null) { if(File.Exists(profile.ProfilePath + "\\Data\\enUS\\realmlist.wtf")) { Process.Start("notepad.exe", profile.ProfilePath + "\\Data\\enUS\\realmlist.wtf"); } else if(File.Exists(profile.ProfilePath + "\\Data\\enGB\\realmlist.wtf")) { Process.Start("notepad.exe", profile.ProfilePath + "\\Data\\enGB\\realmlist.wtf"); } else { if(frmCreateRealmlist.ShowDialog() == DialogResult.Yes) { if(File.Exists(profile.ProfilePath + "\\Data\\enUS\\realmlist.wtf")) { Process.Start("notepad.exe", profile.ProfilePath + "\\Data\\enUS\\realmlist.wtf"); } else if(File.Exists(profile.ProfilePath + "\\Data\\enGB\\realmlist.wtf")) { Process.Start("notepad.exe", profile.ProfilePath + "\\Data\\enGB\\realmlist.wtf"); } } } } else { MessageBox.Show("Cannot find realmlist.wtf with your current profile.", "Error"); } } private void fileRefresh_Click(object sender, EventArgs e) { RefreshList(); } private void fileExit_Click(object sender, EventArgs e) { Application.Exit(); } #endregion #region Server Lists Menu private void slGamesTop100_Click(object sender, EventArgs e) { Process.Start("http://www.gtop100.com/"); } private void slTop100Arena_Click(object sender, EventArgs e) { Process.Start("http://wow.top100arena.com/"); } private void slXtremeTop100_Click(object sender, EventArgs e) { Process.Start("http://xtremetop100.com/world-of-warcraft"); } private void slGameSites200_Click(object sender, EventArgs e) { Process.Start("http://www.gamesites200.com/wowprivate/"); } private void slMmorpgTL_Click(object sender, EventArgs e) { Process.Start("http://www.mmorpgtoplist.com/world-of-warcraft"); } private void slWowServers_Click(object sender, EventArgs e) { Process.Start("http://wows.top-site-list.com/"); } private void slTop1000_Click(object sender, EventArgs e) { Process.Start("http://wow.top-site-list.com/"); } #endregion #region Guides and Wikis Menu private void webWowWiki_Click(object sender, EventArgs e) { Process.Start("http://www.wowwiki.com/"); } private void webThottbot_Click(object sender, EventArgs e) { Process.Start("http://thottbot.com/"); } private void webZamWow_Click(object sender, EventArgs e) { Process.Start("http://wow.allakhazam.com/"); } private void webGotWarcraft_Click(object sender, EventArgs e) { Process.Start("http://gotwarcraft.com/"); } private void webFreeWarcraftGuides_Click(object sender, EventArgs e) { Process.Start("http://freewarcraftguides.com/"); } private void webOnlineMultiplayer_Click(object sender, EventArgs e) { Process.Start("http://www.online-multiplayer.com/wow/"); } private void webWowProfessions_Click(object sender, EventArgs e) { Process.Start("http://www.wow-professions.com/"); } private void webWowPopular_Click(object sender, EventArgs e) { Process.Start("http://www.wowpopular.com/"); } #endregion #region Help Menu private void helpWebSwitchex_Click(object sender, EventArgs e) { Process.Start("http://switchex.abluescarab.us/"); } private void helpWebAbluescarab_Click(object sender, EventArgs e) { Process.Start("http://www.abluescarab.us/"); } private void helpWebSourceForge_Click(object sender, EventArgs e) { Process.Start("http://sourceforge.net/projects/switchex/"); } private void helpWebGitHub_Click(object sender, EventArgs e) { Process.Start("http://github.com/abluescarab/Switchex/releases"); } private void helpWebWow_Click(object sender, EventArgs e) { Process.Start("http://us.battle.net/wow/en/"); } private void helpWebBattlenet_Click(object sender, EventArgs e) { Process.Start("http://us.battle.net/en/"); } private void helpUpdates_Click(object sender, EventArgs e) { Globals.blnUpdates = true; CheckUpdates(); } private void helpChangelog_Click(object sender, EventArgs e) { try { Process.Start("notepad.exe", Globals.changelogFile); } catch(Exception ex) { Globals.frmError.ShowDialog(ex); } } private void helpHelpTopics_Click(object sender, EventArgs e) { try { Process.Start(Globals.helpFile); } catch(Exception ex) { Globals.frmError.ShowDialog(ex); } } private void helpAbout_Click(object sender, EventArgs e) { frmAbout.ShowDialog(); } #endregion #region Methods /// <summary> /// Check for updates and open the updates confirmation form. /// </summary> private void CheckUpdates() { Cursor = Cursors.WaitCursor; frmConfirmUpdate frmConfirmUpdate = new frmConfirmUpdate(); string versionFile = Application.StartupPath + "\\version.txt"; string readmeFile = Application.StartupPath + "\\readme.txt"; string currentVersion = Application.ProductVersion; WebClient webClient = new WebClient(); if(File.Exists(versionFile)) { File.Delete(versionFile); } webClient.DownloadFile("http://www.abluescarab.us/updates/switchex/version.txt", versionFile); Globals.downloadVersion = File.ReadAllText(versionFile); if(Globals.CompareVersions(currentVersion, Globals.downloadVersion) >= 0) { if(Globals.blnUpdates) { MessageBox.Show("There are no updates available at this time.", "Updates"); } } else if(Globals.CompareVersions(currentVersion, Globals.downloadVersion) == -1) { webClient.DownloadFile("http://www.abluescarab.us/updates/switchex/" + Globals.downloadVersion + ".txt", readmeFile); frmConfirmUpdate.ShowDialog(); } File.Delete(versionFile); File.Delete(readmeFile); Globals.blnUpdates = false; Cursor = Cursors.Default; } /// <summary> /// Refresh the server list. /// </summary> private void RefreshList() { try { using(SqlCeConnection conn = new SqlCeConnection(Properties.Settings.Default.switchexConnectionString)) { using(DataTable dt = new DataTable()) { using(SqlCeDataAdapter adapter = new SqlCeDataAdapter("SELECT * FROM Servers", conn)) { Globals.servers.Clear(); dgvServers.Rows.Clear(); adapter.Fill(dt); foreach(DataRow row in dt.Rows) { Globals.servers.Add(new Server( Convert.ToInt32(row.ItemArray[0]), row.ItemArray[1].ToString(), row.ItemArray[2].ToString(), row.ItemArray[3].ToString(), row.ItemArray[4].ToString(), Convert.ToInt32(row.ItemArray[5]), row.ItemArray[6].ToString(), row.ItemArray[7].ToString())); } if(cmbProfiles.Text != "All") { var query = Globals.servers.Where(item => item.ServerProfile == cmbProfiles.Text); foreach(Server server in query) { dgvServers.Rows.Add(null, server.ServerName, server.ServerIP, server.ServerWebsite, server.ServerPatch, server.ServerRating, server.ServerNotes, server.ServerProfile, server.ServerID); } } else { foreach(Server server in Globals.servers) { dgvServers.Rows.Add(null, server.ServerName, server.ServerIP, server.ServerWebsite, server.ServerPatch, server.ServerRating, server.ServerNotes, server.ServerProfile, server.ServerID); } } } } } Globals.rowCount = dgvServers.Rows.Count; if(cmbProfiles.Text != "All") { ToolstripInfo(false); } else { ToolstripInfo(true); } } catch(Exception ex) { Globals.frmError.ShowDialog(ex); } } /// <summary> /// Load column widths from user settings. /// </summary> private void LoadColumnWidths() { string[] widths = { "43", "133", "100", "133", "60", "63", "133", "133" }; if(Properties.Settings.Default.columnWidths.Contains(' ')) { widths = Properties.Settings.Default.columnWidths.Split(' '); } else if(Properties.Settings.Default.columnWidths.Contains(',')) { widths = Properties.Settings.Default.columnWidths.Split(','); } for(int i = 0; i < widths.Count(); i++) { dgvServers.Columns[i].Width = Convert.ToInt32(widths[i]); } } /// <summary> /// Load the window size from user settings. /// </summary> private void LoadWindowSize() { string[] size = { "914", "410" }; if(Properties.Settings.Default.windowSize.Contains(' ')) { size = Properties.Settings.Default.windowSize.Split(' '); } else if(Properties.Settings.Default.windowSize.Contains(',')) { size = Properties.Settings.Default.windowSize.Split(','); } Width = Convert.ToInt32(size[0]); Height = Convert.ToInt32(size[1]); } /// <summary> /// Update the toolstrip information based on the current profile. /// </summary> /// <param name="clear">Clear all information or not</param> private void ToolstripInfo(bool clear) { if(!clear) { try { Profile profile = Globals.profiles.SingleOrDefault(item => item.ProfileName == cmbProfiles.Text); if(profile != null) { string exec32 = profile.ProfilePath + "\\Wow.exe", exec64 = profile.ProfilePath + "\\Wow-64.exe", realmUS = profile.ProfilePath + "\\Data\\enUS\\realmlist.wtf", realmGB = profile.ProfilePath + "\\Data\\enGB\\realmlist.wtf", currentPatch = null, currentServer = null; if(File.Exists(exec32)) { currentPatch = FileVersionInfo.GetVersionInfo(exec32).FileVersion; } else if(File.Exists(exec64)) { currentPatch = FileVersionInfo.GetVersionInfo(exec64).FileVersion; } if(File.Exists(realmUS)) { using(StreamReader realmlist = new StreamReader(realmUS)) { string line = realmlist.ReadLine(); if(line != null && line.Length > 0) { currentServer = line.Substring(14); } } } else if(File.Exists(realmGB)) { using(StreamReader realmlist = new StreamReader(realmGB)) { string line = realmlist.ReadLine(); if(line != null && line.Length > 0) { currentServer = line.Substring(14); } } } if(currentPatch != null) { currentPatch = currentPatch.Replace(", ", "."); statusPatch.Text = "Patch " + currentPatch; } else { statusPatch.Text = "No patch specified."; } if(currentServer != null) { statusServer.Text = currentServer; } else { statusServer.Text = "No server specified."; } statusLocation.Text = profile.ProfilePath; } } catch(Exception ex) { Globals.frmError.ShowDialog(ex); } } else { statusPatch.Text = "No patch specified."; statusServer.Text = "No server specified."; statusLocation.Text = "None."; } } /// <summary> /// Delete a server from the server list. /// </summary> /// <param name="serverName">The server name</param> /// <param name="serverIP">The server IP</param> private void DeleteServer(string serverName, string serverIP) { try { using(SqlCeConnection conn = new SqlCeConnection(Properties.Settings.Default.switchexConnectionString)) { using(SqlCeCommand cmd = new SqlCeCommand("DELETE FROM Servers WHERE ID=@id", conn)) { cmd.Parameters.AddWithValue("@id", dgvServers.SelectedRows[0].Cells[8].Value.ToString()); conn.Open(); cmd.ExecuteNonQuery(); } } MessageBox.Show(serverName + " deleted successfully.", "Deletion Success"); } catch(Exception ex) { Globals.frmError.ShowDialog(ex); } } /// <summary> /// Check if all servers are online. /// </summary> private void CheckOnline() { try { if(dgvServers.Rows.Count > 0) { Cursor = Cursors.WaitCursor; int curRow = 0, rowCount = dgvServers.RowCount; bool rtn; while(curRow < rowCount) { dgvServers.Rows[curRow].Selected = true; rtn = PingServer(dgvServers.SelectedRows[0].Cells[2].Value.ToString()); if(rtn) { dgvServers.SelectedRows[0].Cells[0].Value = CheckState.Checked; } else { dgvServers.SelectedRows[0].Cells[0].Value = CheckState.Unchecked; } dgvServers.ClearSelection(); curRow += 1; } Cursor = Cursors.Default; } else { MessageBox.Show("The server list is empty. Please add more servers by clicking the Add button.", "Error"); } } catch(Exception ex) { Globals.frmError.ShowDialog(ex); } } /// <summary> /// Check if the Main profile exists. If it does not and there are no other profiles, create it. /// </summary> private void CheckForMainProfile(string path) { try { using(SqlCeConnection conn = new SqlCeConnection(Properties.Settings.Default.switchexConnectionString)) { using(SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM Profiles", conn)) { using(DataSet ds = new DataSet()) { using(SqlCeDataAdapter adapter = new SqlCeDataAdapter(cmd)) { adapter.SelectCommand = cmd; adapter.Fill(ds); if(ds.Tables[0].Rows.Count == 0) { cmd.CommandText = "INSERT INTO Profiles (ProfileName, ProfilePath, ProfileDescription, ProfileType, ProfileDefault) " + "VALUES ('Main', @path, 'Main profile.', 32, 1)"; cmd.Parameters.AddWithValue("@path", path); conn.Open(); cmd.ExecuteNonQuery(); Properties.Settings.Default.currentProfile = "Main"; } } } } } Globals.GetProfiles(); } catch(Exception ex) { Globals.frmError.ShowDialog(ex); } } /// <summary> /// Add all the profiles to the dropdown in the statusStrip. /// </summary> private void AddProfilesToDropDown() { try { cmbProfiles.DropDownItems.Clear(); cmbProfiles.DropDownItems.Add("All"); foreach(Profile profile in Globals.profiles) { cmbProfiles.DropDownItems.Add(profile.ProfileName); } if(Globals.profiles.SingleOrDefault(item => item.ProfileName == Properties.Settings.Default.currentProfile) == null) { cmbProfiles.Text = cmbProfiles.DropDownItems[0].Text; } else { cmbProfiles.Text = Properties.Settings.Default.currentProfile; } } catch(Exception ex) { Globals.frmError.ShowDialog(ex); } } /// <summary> /// Opens World of Warcraft. /// </summary> private void OpenWow() { Profile profile = Globals.profiles.SingleOrDefault(item => item.ProfileName == cmbProfiles.Text); if(profile != null) { string exec32 = profile.ProfilePath + "\\Wow.exe", exec64 = profile.ProfilePath + "\\Wow-64.exe"; // If the current profile calls Wow.exe if(profile.ProfileType == 32) { if(File.Exists(exec32)) { Process.Start(exec32); } else { MessageBox.Show("Wow.exe does not exist in your profile location. Are you sure it is " + "a valid World of Warcraft installation?", "Error"); } } // If the current profile calls Wow-64.exe else { if(File.Exists(exec64)) { Process.Start(exec64); } else { MessageBox.Show("Wow-64.exe does not exist in your profile location. Are you sure it is " + "a valid World of Warcraft installation?", "Error"); } } } else { MessageBox.Show("Cannot find World of Warcraft executables with the current profile.", "Error"); } } /// <summary> /// Ping a server to see if it's online. /// </summary> /// <param name="address">The IP of the server</param> /// <returns></returns> public bool PingServer(string address) { Ping ping = new Ping(); PingReply pingReply; try { pingReply = ping.Send(address, 1000); if(pingReply.Status == IPStatus.Success) { return true; } else { return false; } } catch { return false; } } #endregion } }
/* * Created By: Evan Combs * Created On: 8/19/2015 * Modified On: 8/19/2015 * File Name: ParcelableCreator.cs * Full Namespace: DeadDodo.Droid.ParcelableCreator * Inherites: Java.Lang.Object * Interfaces: IParcelableCreator * Purpose: Allows an object to turn itself into a Parcel in Android * Fields: * Delegates: * Methods: * ToDo: * Proposed Changes: */ using System; using Android.OS; namespace DeadDodo.Droid { public class ParcelableCreator<T> : Java.Lang.Object, IParcelableCreator where T : Java.Lang.Object, new() { #region ReadOnlyFields private readonly Func<Parcel, T> createFunc; #endregion #region Initialization public ParcelableCreator(Func<Parcel, T> createFromParcelFunc) { createFunc = createFromParcelFunc; } #endregion #region IParcelableCreator Implementation public Java.Lang.Object CreateFromParcel(Parcel source) { return createFunc(source); } public Java.Lang.Object[] NewArray(int size) { return new T[size]; } #endregion } }
namespace MOBAChallenger { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class Program { public static void Main() { var players = new Dictionary<string, Player>(); string input; while ((input = Console.ReadLine()) != "Season end") { var items = input.Split("->").ToArray(); if (items.Length == 3) { string name = items[0].Trim(); string position = items[1].Trim(); int skill = int.Parse(items[2]); if (!players.Keys.Contains(name)) { var player = new Player(name); player.position.Add(position, skill); players.Add(name, player); } else { if (!players[name].position.Keys.Contains(position)) { players[name].position.Add(position, skill); } else if(players[name].position[position] < skill) { players[name].position[position] = skill; } } } else { var playerItems = input.Split(new[] { " ", "vs" }, StringSplitOptions.RemoveEmptyEntries).ToArray(); string firstPlayerName = playerItems[0]; string secondPlayerName = playerItems[1]; if (players.ContainsKey(firstPlayerName) && players.ContainsKey(secondPlayerName)) { var playerOne = players.FirstOrDefault(n => n.Key == firstPlayerName).Value; var playerTwo = players.FirstOrDefault(n => n.Key == secondPlayerName).Value; int playerOneSumAllSkills = playerOne.position.Values.Sum(); int playerTwoSumAllSkills = playerTwo.position.Values.Sum(); if (playerOneSumAllSkills != playerTwoSumAllSkills) { foreach (var pos in playerOne.position) { if (playerTwo.position.ContainsKey(pos.Key)) { int playerTwoSkillPoint = playerTwo.position[pos.Key]; if (playerOneSumAllSkills > playerTwoSumAllSkills) { players.Remove(secondPlayerName); } else if (playerOneSumAllSkills < playerTwoSumAllSkills) { players.Remove(firstPlayerName); } else { break; } } } } } } } var sortedPlayers = players.OrderByDescending(s => s.Value.SumSkils()).ThenBy(n => n.Key); foreach (var player in sortedPlayers) { Console.WriteLine(player.Value); } } } public class Player { public string name; public Dictionary<string, int> position; public Player(string name) { this.name = name; this.position = new Dictionary<string, int>(); } public int SumSkils() { int sum = 0; foreach (var item in this.position) { sum += item.Value; } return sum; } public override string ToString() { var sb = new StringBuilder(); string name = this.name; int sumSkils = this.SumSkils(); sb.AppendLine($@"{name}: {sumSkils} skill"); foreach (var item in this.position.OrderByDescending(s => s.Value).ThenBy(n => n.Key)) { sb.AppendLine($"- {item.Key} <::> {item.Value}"); } return sb.ToString().Trim(); } } }
/* ************************************************************** * Copyright(c) 2014 Score.web, All Rights Reserved. * File : AppHelper.cs * Description : 初始化数据库连接,配置数据底层访问{ ClownFish } * Author : zhaotianyu * Created : 2014-09-25 * Revision History : ******************************************************************/ namespace App.Score.Data { using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using ClownFish; using System.Net; /// <summary> /// 数据底层访问 /// </summary> public class AppHelper { /// <summary> /// 数据访问初始化 /// </summary> public static void Init() { //// 设置配置参数:当成功执行数据库操作后,如果有输出参数,则自动获取返回值并赋值到实体对象的对应数据成员中。 DbContextDefaultSetting.AutoRetrieveOutputValues = true; //// 注册编译失败事件,用于检查在编译实体加载器时有没有失败。 BuildManager.OnBuildException += new BuildExceptionHandler(BuildManager_OnBuildException); //// 开始准备向ClownFishSQLProfiler发送所有的数据库访问操作日志 ////Profiler.ApplicationName = "ScoreAnalyze"; ////Profiler.TryStartClownFishProfiler(); //// 注册SQLSERVER数据库连接字符串 ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["iSchoolConnectionString"]; //IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName()); //if (IpEntry.HostName.Equals("devWin-PC") || IpEntry.HostName.Equals("shujianhua")) //{ // setting = ConfigurationManager.ConnectionStrings["iSchoolConnectionStringF"]; //} DbContext.RegisterDbConnectionInfo("Sqlserver", setting.ProviderName, "@", setting.ConnectionString); //// 启动自动编译数据实体加载器的工作模式。 //// 编译的触发条件:请求实体加载器超过2000次,或者,等待编译的类型数量超过100次 BuildManager.StartAutoCompile(() => BuildManager.RequestCount > 2000 || BuildManager.WaitTypesCount > 100); //// 注意:StartAutoCompile只能调用一次,第二次调用时,会引发异常。 ////BuildManager.StartAutoCompile(() => true, 10000); //// 手动提交要编译加载器的数据实体类型。 //// 说明:手动提交与自动编译不冲突,不论是同步还是异步。 Type[] models = BuildManager.FindModelTypesFromCurrentApplication(t => t.FullName.StartsWith(" App.Score.Entity.")); ////BuildManager.CompileModelTypesSync(models, true); BuildManager.CompileModelTypesAsync(models); } /// <summary> /// SafeLogException /// </summary> /// <param name="message">异常消息内容</param> public static void SafeLogException(string message) { try { string logfilePath = @"c:\ErroLogs\ErrorLog.txt"; File.AppendAllText(logfilePath, "=========================================\r\n" + message, System.Text.Encoding.UTF8); } catch { } } /// <summary> /// OnBuildException /// </summary> /// <param name="ex">异常</param> private static void BuildManager_OnBuildException(Exception ex) { CompileException ce = ex as CompileException; if (ce != null) { SafeLogException(ce.GetDetailMessages()); } else { //// 未知的异常类型 SafeLogException(ex.ToString()); } } } }
using Faux.Banque.Domain.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Faux.Banque.Domain.Storage { public interface IEventStore { EventStream LoadEventStream(IIdentity id); void AppendToStream(IIdentity id, long expectedVersion, ICollection<IEvent> events); IList<IEvent> LoadEvents(DateTimeOffset afterVersion, int maxCount); event EventStore.NewEventsArrivedHandler NewEventsArrived; } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSConsoleTestForPart1 { class Program { static void DoBasicListTest() { try { Type type = Type.GetTypeFromProgID("UnmanagedIListImpl.MyObjectList"); Object obj = Activator.CreateInstance(type); IList pList = (IList)obj; // Do standard adding of items to pList. pList.Add((object)"John Lennon"); pList.Add((object)"Paul McCartney"); pList.Add((object)"George Harrison"); pList.Insert(3, "Ringo Starr"); pList.Add((object)((int)100)); pList.Add((object)((bool)false)); pList.Add((object)((float)10.123)); // Check for existence of a specific item. bool bRetTemp = pList.Contains((object)"George Martin"); if (bRetTemp == false) { // If not found, add the item. pList.Add((object)"George Martin"); } // Check again. This time bRetTemp must be "true". bRetTemp = pList.Contains((object)"George Martin"); // Modify an existing item's value. pList[4] = 101; // Get that item. object objTemp = pList[4]; // Display its type and value. Console.WriteLine("Type : [{0:S}] Value : [{1}]", objTemp.GetType().ToString(), objTemp); // We remove "George Martin" and "John Lennon" from pList. pList.Remove("George Martin"); pList.RemoveAt(0); // Now display current items in pList. // All previously added items will be there // except "George Martin" and "John Lennon". foreach (object item in pList) { Console.WriteLine("Type : [{0:S}] Value : [{1}]", item.GetType().ToString(), item); } // Uncomment the following code to trigger ArgumentOutOfRangeException // exception. //pList.Insert(-1, "Billy Preston"); } catch (ArgumentOutOfRangeException argex) { Console.WriteLine("{0:S}", argex.Message); Console.WriteLine("{0:S}", argex.Source); } catch (Exception ex) { Console.WriteLine("{0:S}", ex.ToString()); } } static void Main(string[] args) { DoBasicListTest(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net.Http; using City_Center.Services; using Xamarin.Forms; using static City_Center.Models.FavoritosResultado; using City_Center.Clases; namespace City_Center.ViewModels { public class FavoritosViewModel:BaseViewModel { #region Services private ApiService apiService; #endregion #region Attributes private string muestraPaginador = "false"; private ObservableCollection<FavoritoItemViewModel> favoritoDetalle; #endregion #region Properties public ObservableCollection<FavoritoItemViewModel> FavoritoDetalle { get { return this.favoritoDetalle; } set { SetValue(ref this.favoritoDetalle, value); } } public string MuestraPaginador { get { return this.muestraPaginador; } set { SetValue(ref this.muestraPaginador, value); } } #endregion #region Commands #endregion #region Methods private async void LoadEventos() { var connection = await this.apiService.CheckConnection(); if (!connection.IsSuccess) { await Mensajes.Alerta("Verificá tu conexión a Internet"); return; } var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("gua_id_usuario", Application.Current.Properties["IdUsuario"].ToString()), }); var response = await this.apiService.Get<FavoritoReturn>("/guardados", "/index", content); if (!response.IsSuccess) { await Mensajes.Alerta("Ha habido un error en tu solicitud, por favor volvé a intentarlo"); return; } MainViewModel.GetInstance().listFavoritos = (FavoritoReturn)response.Result; FavoritoDetalle = new ObservableCollection<FavoritoItemViewModel>(this.ToEventosItemViewModel()); if (MainViewModel.GetInstance().listFavoritos.resultado.Count == 0) { await Mensajes.Alerta("Parece que no tenés Guardados"); } } private IEnumerable<FavoritoItemViewModel> ToEventosItemViewModel() { return MainViewModel.GetInstance().listFavoritos.resultado.Select(l => new FavoritoItemViewModel { gua_id = l.gua_id, gua_id_usuario = l.gua_id_usuario, gua_id_evento = l.gua_id_evento, gua_id_promocion = l.gua_id_promocion, gua_id_torneo = l.gua_id_torneo, gua_id_destacado = l.gua_id_destacado, gua_id_usuario_creo = l.gua_id_usuario_creo, gua_fecha_hora_creo = l.gua_fecha_hora_creo, gua_id_usuario_modifico = l.gua_id_usuario_modifico, gua_fecha_hora_modifico = l.gua_fecha_hora_modifico, nombre = l.nombre, descripcion = l.descripcion, imagen = VariablesGlobales.RutaServidor + l.imagen, imagen_2 = VariablesGlobales.RutaServidor + l.imagen_2, link = l.link, fecha = l.fecha, ocultallamada = (string.IsNullOrEmpty(l.telefono) ? false : true), ocultaonline = (string.IsNullOrEmpty(l.link) ? false : true), ocultatorneo = l.gua_id_torneo == 0 ? false : true, }); } #endregion #region Contructors public FavoritosViewModel() { this.apiService = new ApiService(); this.LoadEventos(); } #endregion } }
using System; using System.Collections.Generic; using LMS.Domain.Concrete; using LMS.Domain.Abstract; using LMS.Domain.Entities; using System.Web.Mvc; using Ninject; namespace LMS.WebUI.Infrastructure { public class NinjectDependencyResolver : IDependencyResolver { private IKernel kernel; public NinjectDependencyResolver(IKernel kernelParam) { kernel = kernelParam; AddBindings(); } public object GetService(Type serviceType) { return kernel.TryGet(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { return kernel.GetAll(serviceType); } private void AddBindings() { // put bindings here kernel.Bind<ICourseRepository>().To<EFCourseRepository>(); } } }
using FaceHelp.Service.Library.Entities; using FaceHelp.Service.Library.Repositories; using System; using System.Collections.Generic; using System.Text; namespace FaceHelp.Service.Library.Domains { public class Patient { public bool ValidateData(PatientEntity patient) { // only allow people over the age of 50 to be validated if (patient.Age > 50) { return true; } return false; } public PatientEntity SignIn(string username, string password) { // Send username and password to Data Access return new PatientDataAccess().PullByUP(username, password); } public void AddFaceByID(string id, FaceEntity face) { // Check Data Quality //... // send to the addFaceByIDfunction In PatientDataAccess PatientDataAccess dataAccess = new PatientDataAccess(); dataAccess.AddFaceByID(id, face); } } }
namespace LINQ { enum ExamplesEnumeration { BasicSyntax, GenderCondition, ExtensionMethodSyntax, DefferedExecution, WhereBasicSyntax, WhereExtensionSyntax, OrderByBasicSyntax, OrderByExtensionSyntax, GroupByBasicSyntax, GroupByExtensionSyntax, GroupByInto, AnonymousTypes, AnonymousTypesTryChangeProperty, AnonymousTypesPropertyNamesInheritance, ExplicitSelectClause, ExplicitSelectAnonymousType, DynamicTypes, JoinWithQuerySyntax, JoinWithExtensionMethodsSyntax, JoinByMultipleFields, JoinByMultipleFieldsWithTuple, LeftJoinQuerySyntax, LeftJoinExtensionMethodsSyntax, ExclusionWithWhere } }
namespace Game.ConsoleUI.Interfaces.Services { using Game.Models; public interface IChallengeService { GameChallenge Challenge { get; } void Resolved(); bool IsResolutionValid(); void CreateChallenge(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Infra { public class TreeNode { public int Value { get; set; } public TreeNode LeftChild { get; set; } public TreeNode RightChild { get; set; } public TreeNode(int value) { Value = value; LeftChild = null; RightChild = null; } #region deserialize Tree public static int index; /// <summary> /// Deserialize a tree from a string /// </summary> /// <param name="inputstring">input string</param> /// <param name="t">separator charator such as "1, 2, 3, 4" here ',' is a separator</param> /// <returns>result tree</returns> public static TreeNode DeserializeTree(string inputstring, char t) { string[] stringArray = inputstring.Split(t); index = 0; return CreatTree(stringArray); } /// <summary> /// Working method of the recursive. /// </summary> /// <param name="inputArray"></param> /// <returns></returns> public static TreeNode CreatTree(string[] inputArray) { if (index > inputArray.Length - 1 || inputArray[index] == "#") { index++; return null; } if (index < inputArray.Length) { TreeNode node = new TreeNode(int.Parse(inputArray[index])); index++; node.LeftChild = CreatTree(inputArray); node.RightChild = CreatTree(inputArray); return node; } else { return null; } } #endregion #region serialize Tree /// <summary> /// Serialize a tee to string. /// </summary> /// <param name="root"></param> /// <returns></returns> public static string SeriallizeTree(TreeNode root) { StringBuilder sb = new StringBuilder(); printOutTree(root, sb); return sb.ToString(); } /// <summary> /// recursive method for serialize tree. /// </summary> /// <param name="node"></param> /// <param name="sb"></param> public static void printOutTree(TreeNode node, StringBuilder sb) { if (sb.Length != 0) sb.Append(","); if (node == null) { sb.Append("#"); } else { sb.Append(node.Value); printOutTree(node.LeftChild, sb); printOutTree(node.RightChild, sb); } } #endregion #region Verify Trees /// <summary> /// Verify if a tree is a BST. /// </summary> /// <param name="root">root of the tree</param> /// <returns></returns> public static bool VerifyIfATreeIsABST(TreeNode root) { if (root.LeftChild == null && root.RightChild == null) return true; if (root.LeftChild != null && root.RightChild == null) { if (root.LeftChild.Value <= root.Value) { return VerifyIfATreeIsABST(root.LeftChild); } else { return false; } } if (root.RightChild != null && root.LeftChild == null) { if (root.RightChild.Value >= root.Value) { return VerifyIfATreeIsABST(root.RightChild); } else { return false; } } if (root.LeftChild != null && root.RightChild != null) { if (root.LeftChild.Value <= root.Value && root.Value <= root.RightChild.Value) { return VerifyIfATreeIsABST(root.LeftChild) && VerifyIfATreeIsABST(root.RightChild); } else { return false; } } return false; } /// <summary> /// Verifyis a tree is a BST /// </summary> /// <param name="root"></param> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool VerifyBST(TreeNode root, int left, int right) { if (root.Value < left || root.Value > right) { return false; } else { if (root.LeftChild == null && root.RightChild == null) { return true; } else if (root.RightChild != null) { return VerifyBST(root.RightChild, root.Value, right); } else if (root.LeftChild != null) { return VerifyBST(root.LeftChild, left, root.Value); } else { return VerifyBST(root.LeftChild, left, root.Value) && VerifyBST(root.RightChild, root.Value, right); } } } /// <summary> /// Verify if a tree is balanced. a balance tree's leaves's max depth difference should be less or equal to 1. /// </summary> /// <param name="root">The tree need to be verified</param> /// <returns>true if the tree is balanced</returns> public static bool VerifyIfBalanced(TreeNode root) { if (Math.Abs(MaxDepth(root.LeftChild) - MaxDepth(root.RightChild)) > 1) { return false; } else { return true; } } /// <summary> /// Find the max depth of the tree. /// </summary> /// <param name="root">the tree</param> /// <returns>the max depth.</returns> private static int MaxDepth(TreeNode root) { if (root == null) return 0; return Math.Max(MaxDepth(root.LeftChild), MaxDepth(root.RightChild)) + 1; } #endregion #region inroder travel /// <summary> /// Given a binary tree, return the inorder traversal of its nodes' values. ///For example: ///Given binary tree {1,#,2,3}, ///return [1,3,2]. /// </summary> /// <param name="root">the tree</param> public static string TreeTravelInorder(TreeNode root) { if (root == null) return string.Empty; StringBuilder sb = new StringBuilder(); Stack<TreeNode> s = new Stack<TreeNode>(); s.Push(root); TreeNode node; node = s.Peek(); while (node.LeftChild != null) { s.Push(node.LeftChild); node = node.LeftChild; } while (s.Count != 0) { node = s.Pop(); if (sb.Length > 0) { sb.Append(","); } sb.Append(node.Value.ToString()); if (node.RightChild != null) { s.Push(node.RightChild); node = node.RightChild; } if (s.Count == 0) continue; if (node == s.Peek().LeftChild) continue; node = s.Peek(); while (node.LeftChild != null) { s.Push(node.LeftChild); node = node.LeftChild; } } return sb.ToString(); } /// <summary> /// Given a binary tree, return the inorder traversal of its nodes' values. /// Same as last method, used a backtrack /// </summary> /// <param name="root">The Tree</param> /// <returns>string output of in order travel.</returns> public static string BinaryTreeInorderTravel2(TreeNode root) { if (root == null) return null; Stack<TreeNode> s = new Stack<TreeNode>(); StringBuilder sb = new StringBuilder(); s.Push(root); bool backTrack = false; while (!(s.Count == 0)) { TreeNode tmp = s.Peek(); if (tmp.LeftChild != null && !backTrack) { s.Push(tmp.LeftChild); backTrack = false; continue; } if (sb.Length > 0) { sb.Append(","); } sb.Append(tmp.Value.ToString()); s.Pop(); backTrack = true; if (tmp.RightChild != null) { s.Push(tmp.RightChild); backTrack = false; } } return sb.ToString(); } #endregion #region post order travel /// <summary> /// Travel a tree post order interatively. /// </summary> /// <param name="root">the tree</param> /// <returns>trace.</returns> public static string TreeTravelPostOrder(TreeNode root) { if (root == null) return string.Empty; StringBuilder sb = new StringBuilder(); Stack<TreeNode> s = new Stack<TreeNode>(); TreeNode previous = null; TreeNode cur; s.Push(root); while (!(s.Count == 0)) { cur = s.Peek(); if (cur.LeftChild == null && cur.RightChild == null) { cur = s.Pop(); if (sb.Length != 0) sb.Append(","); sb.Append(cur.Value.ToString()); } else if (previous == cur.LeftChild) { if (cur.RightChild != null) { s.Push(cur.RightChild); } else { cur = s.Pop(); if (sb.Length != 0) sb.Append(","); sb.Append(cur.Value.ToString()); } } else if (previous == cur.RightChild) { cur = s.Pop(); if (sb.Length != 0) sb.Append(","); sb.Append(cur.Value.ToString()); } else { s.Push(cur.LeftChild); } previous = cur; } return sb.ToString(); } #endregion #region sub tree /// <summary> /// If a tree is a sub tree of another tree. this method check the value of the treenode. /// </summary> /// <param name="t1">parent tree</param> /// <param name="t2">sub tree to be</param> /// <returns>if it is a sub tree</returns> public static bool IsASubTree(TreeNode t1, TreeNode t2) { // null tree is sub tree of any tree. if (t2 == null) return true; // t2 != null but t1 == null, then it is not a sub tree. if (t1 == null) return false; if (t1.Value == t2.Value && IsASubTree(t1.LeftChild, t2.LeftChild) && IsASubTree(t1.RightChild, t2.RightChild)) { return true; } else { return IsASubTree(t1.LeftChild, t2) || IsASubTree(t1.RightChild, t2); } } /// <summary> /// If a tree is a sub tree of another tree. this method check the value of the treenode. /// </summary> /// <param name="t1">parent tree</param> /// <param name="t2">sub tree to be</param> /// <returns>if it is a sub tree</returns> public static bool IsASubTreeRef(TreeNode t1, TreeNode t2) { // null tree is sub tree of any tree. if (t2 == null) return true; // t2 != null but t1 == null, then it is not a sub tree. if (t1 == null) return false; return (t1 == t2) || (t1.LeftChild == t2) || (t1.RightChild == t2); } #endregion #region print tree border private static StringBuilder sb; public static string PrintOutBorder(TreeNode root) { sb = new StringBuilder(); PrintOutleft(root); PrintOutBottom(root); PrintOutRight(root); return sb.ToString(); } /// <summary> /// Working method for print out border, left /// </summary> /// <param name="root"></param> private static void PrintOutleft(TreeNode root) { if (root == null) return; if (!(root.LeftChild == null && root.RightChild == null)) { sb.Append(root.Value + ", "); } PrintOutleft(root.LeftChild); } /// <summary> /// Working method for print out border, bottom /// </summary> /// <param name="root"></param> private static void PrintOutBottom(TreeNode root) { if (root == null) return; PrintOutBottom(root.LeftChild); if (root.LeftChild == null && root.RightChild == null) { sb.Append(root.Value + ", "); } PrintOutBottom(root.RightChild); } /// <summary> /// Woring method for print out border, right /// </summary> /// <param name="root"></param> private static void PrintOutRight(TreeNode root) { if (root == null) return; PrintOutRight(root.RightChild); if (!(root.LeftChild == null && root.RightChild == null)) { sb.Append(root.Value + ", "); } } #endregion #region contruct tree from preorder and in order /// <summary> /// Construct a binary tree from pre order traversal and in order traversal. /// the element in /// </summary> /// <param name="preOrder"></param> /// <param name="inOrder"></param> /// <returns></returns> public static TreeNode ContructTreeFromPreaAndIn(int[] preOrder, int[] inOrder) { if (preOrder.Length == 0 || inOrder.Length == 0) return null; if (preOrder.Length != inOrder.Length) return null; return ContructTree(preOrder, inOrder, 0, preOrder.Length - 1, 0, inOrder.Length - 1); } private static TreeNode ContructTree(int[] preOrder, int[] inOrder, int preStart, int preEnd, int inStart, int inEnd) { if (preStart > preEnd || inStart > inEnd) return null; int pivot = -1; for (int i = inStart; i <= inEnd; i++) { if (preOrder[preStart] == inOrder[i]) { pivot = i; break; } } if (pivot == -1) return null; TreeNode node = new TreeNode(preOrder[preStart]); node.LeftChild = ContructTree(preOrder, inOrder, preStart + 1, preStart + pivot - inStart, inStart, pivot - 1); node.RightChild = ContructTree(preOrder, inOrder, preStart + pivot - inStart + 1, preEnd, pivot + 1, inEnd); return node; } #endregion } }
using Enrollment.Bsl.Business.Requests; using Enrollment.Bsl.Business.Responses; using Enrollment.Web.Utils; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; namespace Enrollment.Api.Controllers { [Produces("application/json")] [Route("api/User")] public class UserController : Controller { private readonly IHttpClientFactory clientFactory; private readonly ConfigurationOptions configurationOptions; public UserController(IHttpClientFactory clientFactory, IOptions<ConfigurationOptions> optionsAccessor) { this.clientFactory = clientFactory; this.configurationOptions = optionsAccessor.Value; } [HttpPost("Delete")] public async Task<BaseResponse> Delete([FromBody] DeleteEntityRequest deleteUserRequest) => await this.clientFactory.PostAsync<BaseResponse> ( "api/User/Delete", JsonSerializer.Serialize(deleteUserRequest), this.configurationOptions.BaseBslUrl ); [HttpPost("Save")] public async Task<BaseResponse> Save([FromBody] SaveEntityRequest saveUserRequest) => await this.clientFactory.PostAsync<BaseResponse> ( "api/User/Save", JsonSerializer.Serialize(saveUserRequest), this.configurationOptions.BaseBslUrl ); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PayRoll.BLL { public class WeeklySchedule : PaymentSchedule { private bool IsFriday(DateTime date) { return date.DayOfWeek == DayOfWeek.Friday; } public bool IsPayDate(DateTime payDay) { return IsFriday(payDay); } public DateTime GetStartDay(DateTime endDay) { return endDay.AddDays(-6); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using ArteVida.Dominio.Contexto; using ArteVida.Dominio.Repositorio; using ArteVida.GestorWeb.ViewModels; using AutoMapper.QueryableExtensions; using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; namespace ArteVida.GestorWeb.Controllers.Cadastros { public class DiretoriaController : Controller { private DbContexto _contexto; private RepositorioDiretoria _repositorio; private int _Id; public DiretoriaController() { _contexto = new DbContexto(); _repositorio = new RepositorioDiretoria(_contexto); } // GET: Diretoria public ActionResult Index() { var model = new JanelaViewModel("Diretoria"); return View("_ConsultaBase", model); } public ActionResult Ler([DataSourceRequest] DataSourceRequest request) { return Json(PegarDiretores().ToDataSourceResult(request)); } private IQueryable<DiretoriaViewModel> PegarDiretores(string tipo = "Todos") { if (tipo != "Todos") { var dados = _repositorio.ObterTodos().ProjectTo<DiretoriaViewModel>(); return dados; } else { var dados = _repositorio.ObterTodos().ProjectTo<DiretoriaViewModel>(); return dados; } } } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Services.PowerShellContext { /// <summary> /// Provides platform specific console utilities. /// </summary> public interface IConsoleOperations { /// <summary> /// Obtains the next character or function key pressed by the user asynchronously. /// Does not block when other console API's are called. /// </summary> /// <param name="intercept"> /// Determines whether to display the pressed key in the console window. <see langword="true" /> /// to not display the pressed key; otherwise, <see langword="false" />. /// </param> /// <param name="cancellationToken">The CancellationToken to observe.</param> /// <returns> /// An object that describes the <see cref="ConsoleKey" /> constant and Unicode character, if any, /// that correspond to the pressed console key. The <see cref="ConsoleKeyInfo" /> object also /// describes, in a bitwise combination of <see cref="ConsoleModifiers" /> values, whether /// one or more Shift, Alt, or Ctrl modifier keys was pressed simultaneously with the console key. /// </returns> ConsoleKeyInfo ReadKey(bool intercept, CancellationToken cancellationToken); /// <summary> /// Obtains the next character or function key pressed by the user asynchronously. /// Does not block when other console API's are called. /// </summary> /// <param name="intercept"> /// Determines whether to display the pressed key in the console window. <see langword="true" /> /// to not display the pressed key; otherwise, <see langword="false" />. /// </param> /// <param name="cancellationToken">The CancellationToken to observe.</param> /// <returns> /// A task that will complete with a result of the key pressed by the user. /// </returns> Task<ConsoleKeyInfo> ReadKeyAsync(bool intercept, CancellationToken cancellationToken); /// <summary> /// Obtains the horizontal position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorLeft" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <returns>The horizontal position of the console cursor.</returns> int GetCursorLeft(); /// <summary> /// Obtains the horizontal position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorLeft" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken" /> to observe.</param> /// <returns>The horizontal position of the console cursor.</returns> int GetCursorLeft(CancellationToken cancellationToken); /// <summary> /// Obtains the horizontal position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorLeft" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <returns> /// A <see cref="Task{T}" /> representing the asynchronous operation. The /// <see cref="Task{T}.Result" /> property will return the horizontal position /// of the console cursor. /// </returns> Task<int> GetCursorLeftAsync(); /// <summary> /// Obtains the horizontal position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorLeft" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken" /> to observe.</param> /// <returns> /// A <see cref="Task{T}" /> representing the asynchronous operation. The /// <see cref="Task{T}.Result" /> property will return the horizontal position /// of the console cursor. /// </returns> Task<int> GetCursorLeftAsync(CancellationToken cancellationToken); /// <summary> /// Obtains the vertical position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorTop" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <returns>The vertical position of the console cursor.</returns> int GetCursorTop(); /// <summary> /// Obtains the vertical position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorTop" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken" /> to observe.</param> /// <returns>The vertical position of the console cursor.</returns> int GetCursorTop(CancellationToken cancellationToken); /// <summary> /// Obtains the vertical position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorTop" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <returns> /// A <see cref="Task{T}" /> representing the asynchronous operation. The /// <see cref="Task{T}.Result" /> property will return the vertical position /// of the console cursor. /// </returns> Task<int> GetCursorTopAsync(); /// <summary> /// Obtains the vertical position of the console cursor. Use this method /// instead of <see cref="System.Console.CursorTop" /> to avoid triggering /// pending calls to <see cref="IConsoleOperations.ReadKeyAsync(bool, CancellationToken)" /> /// on Unix platforms. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken" /> to observe.</param> /// <returns> /// A <see cref="Task{T}" /> representing the asynchronous operation. The /// <see cref="Task{T}.Result" /> property will return the vertical position /// of the console cursor. /// </returns> Task<int> GetCursorTopAsync(CancellationToken cancellationToken); } }
using System; using System.Collections.Generic; using System.Text; using DataAccess.POCO; namespace DataAccess.Interfaces { public interface ICustomerRepository : IRepository<Customers> { IEnumerable<Customers> GetAll(); } }
using System; using System.Collections.Generic; 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; using FieldLibrary; namespace Lab4 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void New(object sender, RoutedEventArgs e) { // V1Main MessageBox.Show("New"); } private void Open(object sender, RoutedEventArgs e) { MessageBox.Show("Open"); } private void Save(object sender, RoutedEventArgs e) { MessageBox.Show("Save"); } private void AddDefaults(object sender, RoutedEventArgs e) { MessageBox.Show("AddDefaults"); } private void AddDefaultV1DataCollection(object sender, RoutedEventArgs e) { MessageBox.Show("AddDefaultV1DataCollection"); } private void AddDefaultV1DataOnGrid(object sender, RoutedEventArgs e) { MessageBox.Show("AddDefaultV1DataOnGrid"); } private void AddElementFromFile(object sender, RoutedEventArgs e) { MessageBox.Show("AddElementFromFile"); } private void Remove(object sender, RoutedEventArgs e) { MessageBox.Show("Remove"); } } }
using System.Collections.Generic; using Assets.Scripts.Units; using UnityEngine; namespace Assets.Scripts { public class CastContext { public List<Unit> Targets; public Unit MainTarget; public Vector3 TargetPoint; public Transform TargetTransform; public Vector3 CasterPoint; } }
using Labs.WPF.TorrentDownload.ViewModels; using System.Windows; using Unity.Attributes; namespace Labs.WPF.TorrentDownload.Views { /// <summary> /// Interaction logic for SearchFilesView.xaml /// </summary> public partial class SearchFilesView : Window { public SearchFilesView() { InitializeComponent(); } [Dependency] public SearchFilesViewModel ViewModel { set { this.DataContext = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MagicOnion; using MagicOnion.Server; using MessagePack; using Microsoft.Extensions.Options; using SQLite; using WagahighChoices.Ashe; using WagahighChoices.GrpcUtils; using WagahighChoices.Kaoruko.Models; using WagahighChoices.Toa.Imaging; namespace WagahighChoices.Kaoruko.GrpcServer { public class AsheMagicOnionService : ServiceBase<IAsheMagicOnionService>, IAsheMagicOnionService { private SQLiteConnection _connection; private SQLiteConnection Connection => this._connection ?? (this._connection = this.Context.GetRequiredService<SQLiteConnection>()); private bool IsScreenshotEnabled => this.Context.GetService<IOptions<AsheServerOptions>>()?.Value.Screenshot == true; public async UnaryResult<SeekDirectionResult> SeekDirection() { var workerId = await this.WorkerInitializeAsync().ConfigureAwait(false); return await this.RetryWhenLocked(() => { return this.RunInImmediateTransaction(conn => { // 未着手のジョブを取得する // Choices が短いものから順に着手することで、新たなジョブを開拓していく var job = conn.FindWithQuery<WorkerJob>( "SELECT Id, Choices FROM WorkerJob WHERE WorkerId IS NULL ORDER BY length(Choices) LIMIT 1"); ChoiceAction[] actions; if (job == null) { var incompletedJobCount = conn.ExecuteScalar<int>( "SELECT count(*) FROM WorkerJob WHERE SearchResultId IS NULL"); if (incompletedJobCount > 0) { // 未完了のジョブがあるが、現在着手可能なジョブはない return new SeekDirectionResult(SeekDirectionResultKind.NotAvailable); } if (conn.Table<SearchResult>().Count() > 0) { // 探索結果が揃っているので、探索完了とみなす return new SeekDirectionResult(SeekDirectionResultKind.Finished); } // 初回ジョブを作成 job = new WorkerJob() { Id = Guid.NewGuid(), Choices = "", WorkerId = workerId, EnqueuedAt = DateTimeOffset.Now, }; conn.Insert(job); actions = Array.Empty<ChoiceAction>(); } else { actions = ModelUtils.ParseChoices(job.Choices); conn.Execute( "UPDATE WorkerJob SET WorkerId = ? WHERE Id = ?", workerId, job.Id); } Utils.Log.WriteMessage($"ワーカー #{workerId} にジョブ {job.Id} を指示"); return new SeekDirectionResult(SeekDirectionResultKind.Ok, job.Id, actions); }); }).ConfigureAwait(false); } public async UnaryResult<Nil> ReportResult(Guid jobId, Heroine heroine, IReadOnlyList<int> selectionIds) { var workerId = await this.WorkerInitializeAsync().ConfigureAwait(false); await this.RetryWhenLocked(() => { this.RunInImmediateTransaction(conn => { var job = conn.FindWithQuery<WorkerJob>( "SELECT Choices, SearchResultId FROM WorkerJob WHERE Id = ?", jobId); if (job.SearchResultId.HasValue) { // すでに結果報告済み Utils.Log.WriteMessage($"報告が重複しています (Worker: {workerId})"); return; } var jobChoices = ModelUtils.ParseChoices(job.Choices); // 実際に選択したものは、 job.Choices + ずっと上 var choices = jobChoices.Concat( Enumerable.Repeat(ChoiceAction.SelectUpper, selectionIds.Count - jobChoices.Length)); var searchResult = new SearchResult() { Selections = ModelUtils.ToSelectionsString(selectionIds), Choices = ModelUtils.ToChoicesString(choices), Heroine = heroine, Timestamp = DateTimeOffset.Now, }; conn.Insert(searchResult); conn.Execute( "UPDATE WorkerJob SET WorkerId = ?, SearchResultId = ? WHERE Id = ?", workerId, searchResult.Id, jobId); // このレポートで発見された未探索のジョブを作成 for (var i = jobChoices.Length; i < selectionIds.Count; i++) { // 未探索の下を選ぶ var newChoices = choices.Take(i).Append(ChoiceAction.SelectLower); var newJob = new WorkerJob() { Id = Guid.NewGuid(), Choices = ModelUtils.ToChoicesString(newChoices), EnqueuedAt = DateTimeOffset.Now, }; conn.Insert(newJob); } }); }).ConfigureAwait(false); return Nil.Default; } public async UnaryResult<Nil> Log(string message, bool isError, DateTimeOffset timestamp) { var workerId = await this.WorkerInitializeAsync().ConfigureAwait(false); await this.RetryWhenLocked(() => { this.Connection.Insert(new WorkerLog() { WorkerId = workerId, Message = message, IsError = isError, TimestampOnWorker = timestamp, TimestampOnServer = DateTimeOffset.Now, }); }).ConfigureAwait(false); return Nil.Default; } public async UnaryResult<Nil> ReportScreenshot(Bgra32Image screenshot, DateTimeOffset timestamp) { using (screenshot) { if (this.IsScreenshotEnabled) { var workerId = await this.WorkerInitializeAsync().ConfigureAwait(false); await this.RetryWhenLocked(() => { this.Connection.InsertOrReplace(new WorkerScreenshot() { WorkerId = workerId, Width = screenshot.Width, Height = screenshot.Height, Data = screenshot.Data.ToArray(), TimestampOnWorker = timestamp, TimestampOnServer = DateTimeOffset.Now, }); }).ConfigureAwait(false); } } return Nil.Default; } private void RunInImmediateTransaction(Action<SQLiteConnection> action) { var connection = this.Connection; connection.Execute("BEGIN IMMEDIATE"); try { action(connection); connection.Execute("COMMIT"); } catch (Exception ex) { try { connection.Execute("ROLLBACK"); } catch (Exception rollbackException) { throw new AggregateException(ex, rollbackException); } throw; } } private T RunInImmediateTransaction<T>(Func<SQLiteConnection, T> action) { var connection = this.Connection; connection.Execute("BEGIN IMMEDIATE"); try { var result = action(connection); connection.Execute("COMMIT"); return result; } catch (Exception ex) { try { connection.Execute("ROLLBACK"); } catch (Exception rollbackException) { throw new AggregateException(ex, rollbackException); } throw; } } /// <summary> /// 接続してきたワーカーの情報を保存 /// </summary> /// <returns><see cref="Worker.Id"/></returns> private async ValueTask<int> WorkerInitializeAsync() { var connectionId = this.GetConnectionContext().ConnectionId; if (string.IsNullOrEmpty(connectionId)) throw new InvalidOperationException("ConnectionId が指定されていません。"); if (this.GetConnectionContext().ConnectionStatus.IsCancellationRequested) throw new InvalidOperationException($"コネクション {connectionId} はすでに切断処理を行いました。"); var hostName = this.Context.CallContext.RequestHeaders.GetValue(GrpcAsheServerContract.HostNameHeader, false); var setDisconnectAction = false; var workerId = await this.RetryWhenLocked(() => { return this.RunInImmediateTransaction(conn => { var worker = conn.FindWithQuery<Worker>( "SELECT Id, DisconnectedAt FROM Worker WHERE ConnectionId = ?", connectionId); if (worker == null) { Utils.Log.WriteMessage("新規接続 " + connectionId); worker = new Worker() { ConnectionId = connectionId, HostName = hostName, ConnectedAt = DateTimeOffset.Now, }; conn.Insert(worker); setDisconnectAction = true; } else if (!worker.IsAlive) { throw new InvalidOperationException($"コネクション {connectionId} はすでに切断処理を行いました。"); } return worker.Id; }); }).ConfigureAwait(false); if (setDisconnectAction) { var databaseActivator = this.Context.GetRequiredService<DatabaseActivator>(); this.GetConnectionContext().ConnectionStatus.Register(async () => { Utils.Log.WriteMessage("切断 " + connectionId); // どこから呼び出されるかわからないものなので、別の SQLiteConnection を作成 using (var conn = databaseActivator.CreateConnection()) { await this.RetryWhenLocked(() => { conn.Execute("BEGIN IMMEDIATE"); // DisconnectedAt をセット conn.Execute( "UPDATE Worker SET DisconnectedAt = ? WHERE Id = ? AND DisconnectedAt IS NULL", DateTimeOffset.Now, workerId); // 担当ジョブを放棄 conn.Execute( "UPDATE WorkerJob SET WorkerId = NULL WHERE WorkerId = ? AND SearchResultId IS NULL", workerId); conn.Execute("COMMIT"); }).ConfigureAwait(false); } }); } return workerId; } private async Task RetryWhenLocked(Action action) { while (true) { try { action(); return; } catch (SQLiteException ex) { switch (ex.Result) { case SQLite3.Result.Busy: case SQLite3.Result.Locked: break; default: throw; } } await Task.Delay(100).ConfigureAwait(false); } } private async ValueTask<T> RetryWhenLocked<T>(Func<T> action) { while (true) { try { return action(); } catch (SQLiteException ex) { switch (ex.Result) { case SQLite3.Result.Busy: case SQLite3.Result.Locked: break; default: throw; } } await Task.Delay(100).ConfigureAwait(false); } } } }
using FastSQL.Sync.Core.Attributes; using FastSQL.Sync.Core.Enums; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace FastSQL.Sync.Core.Models { [Table("core_schedule_options")] [EntityType(EntityType.ScheduleOption)] public class ScheduleOptionModel : INotifyPropertyChanged { [Key] public Guid Id { get; set; } public Guid TargetEntityId { get; set; } [NotMapped] public string TargetEntityName { get; set; } public EntityType TargetEntityType { get; set; } public string WorkflowId { get; set; } private int _inteval; public int Interval { get => _inteval; set { _inteval = value; OnPropertyChanged(nameof(Interval)); } } private int _priority; public int Priority { get => _priority; set { _priority = value; OnPropertyChanged(nameof(Priority)); } } private ScheduleStatus _status; public ScheduleStatus Status { get => _status; set { _status = value; OnPropertyChanged(nameof(Status)); OnPropertyChanged(nameof(Enabled)); OnPropertyChanged(nameof(IsParallel)); } } [NotMapped] public bool Enabled { get => HasStatus(ScheduleStatus.Enabled); set { if (value) { AddStatus(ScheduleStatus.Enabled); } else { RemoveStatus(ScheduleStatus.Enabled); } OnPropertyChanged(nameof(Status)); } } [NotMapped] public bool IsParallel { get => HasStatus(ScheduleStatus.RunsInParallel); set { if (value) { AddStatus(ScheduleStatus.RunsInParallel); } else { RemoveStatus(ScheduleStatus.RunsInParallel); } OnPropertyChanged(nameof(Status)); } } [NotMapped] public EntityType EntityType => EntityType.ScheduleOption; public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } public void AddStatus(ScheduleStatus state) { Status = Status != 0 ? (Status | state) : state; } public void RemoveStatus(ScheduleStatus state) { if (Status == 0) { return; } Status = (Status | state) ^ state; } public bool HasStatus(ScheduleStatus state) { return (Status & state) > 0; } } }
using bot_backEnd.BL; using bot_backEnd.BL.Interfaces; using bot_backEnd.Models.DbModels; using bot_backEnd.Models.ViewModels; using bot_backEnd.UI.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace bot_backEnd.UI { public class AdministratorUI : IAdministratorUI { private readonly IAdministratorBL _iAdministratorBL; public AdministratorUI(IAdministratorBL iAdministratorBL) { _iAdministratorBL = iAdministratorBL; } public Administrator AddAdministrator(string email, string username, string password) { return _iAdministratorBL.AddAdministrator(email, username, password); } public Administrator AdministratorValidation(string username, string password) { return _iAdministratorBL.AdministratorValidation(username, password); } public bool ChangePassword(int adminID, string oldPassword, string newPassword) { return _iAdministratorBL.ChangePassword(adminID, oldPassword, newPassword); } public bool DeleteAdministrator(int userEntityID) { return _iAdministratorBL.DeleteAdministrator(userEntityID); } public Administrator GetAdministratorByID(int adminID) { return _iAdministratorBL.GetAdministratorByID(adminID); } public List<Administrator> GetAllAdministrators() { return _iAdministratorBL.GetAllAdministrators(); } public List<Administrator> GetFilteredAdministrators(string filterText) { return _iAdministratorBL.GetFilteredAdministrators(filterText); } public AdministratorStats GetStatisticForDashboard() { return _iAdministratorBL.GetStatisticForDashboard(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] public class Waypoint : MonoBehaviour { public float velocidadeRecomendada; private void OnDrawGizmos() { Gizmos.color = Color.yellow; Gizmos.DrawSphere(transform.position, 1f); } }
using FacultyV3.Core.Constants; using FacultyV3.Core.Interfaces; using FacultyV3.Core.Interfaces.IServices; using System; using System.Web.Mvc; using System.Linq; namespace FacultyV3.Web.Controllers { public class Detail_NewsController : Controller { private readonly IDetailNewsService detailNewsService; private readonly ICategoryNewsService categoryNewsService; private readonly ICategoryMenuService categoryMenuService; private IDataContext context; public Detail_NewsController(IDetailNewsService detailNewsService, ICategoryNewsService categoryNewsService, ICategoryMenuService categoryMenuService, IDataContext context) { this.detailNewsService = detailNewsService; this.categoryMenuService = categoryMenuService; this.categoryNewsService = categoryNewsService; this.context = context; } public ActionResult DetailNews(string id) { try { var model = detailNewsService.GetPostByID(id); if(model != null) return View(model); } catch (Exception) { } return View("~/Views/Shared/Error.cshtml"); } public ActionResult ListNewss(int page = 1, int pageSize = Constant.PAGESIZE) { try { var model = detailNewsService.PageListFE(Constant.NEWSS, page, pageSize); if (Enumerable.Count(model) > 0) return View("ListDetailNews", model); } catch (System.Exception) { } return View("~/Views/Shared/Error.cshtml"); } public ActionResult ListWorks(int page = 1, int pageSize = Constant.PAGESIZE) { try { var model = detailNewsService.PageListFE(Constant.WORK, page, pageSize); if (Enumerable.Count(model) > 0) return View("ListDetailNews", model); } catch (System.Exception) { } return View("~/Views/Shared/Error.cshtml"); } public ActionResult ListYouth_Group(int page = 1, int pageSize = Constant.PAGESIZE) { try { var model = detailNewsService.PageListFE(Constant.YOUTH_GROUP, page, pageSize); if (Enumerable.Count(model) > 0) return View("ListDetailNews", model); } catch (System.Exception) { } return View("~/Views/Shared/Error.cshtml"); } public ActionResult ListMinistry(int page = 1, int pageSize = Constant.PAGESIZE) { try { var model = detailNewsService.PageListFE(Constant.NEWS_FROM_THE_MINISTRY, page, pageSize); if (Enumerable.Count(model) > 0) return View("ListDetailNews", model); } catch (System.Exception) { } return View("~/Views/Shared/Error.cshtml"); } public ActionResult ListFaculty(int page = 1, int pageSize = Constant.PAGESIZE) { try { var model = detailNewsService.PageListFE(Constant.NEWS_FROM_FACULTY, page, pageSize); if (Enumerable.Count(model) > 0) return View("ListDetailNews", model); } catch (System.Exception) { } return View("~/Views/Shared/Error.cshtml"); } public ActionResult ListUniversity(int page = 1, int pageSize = Constant.PAGESIZE) { try { var model = detailNewsService.PageListFE(Constant.NEWS_FROM_UNIVERSITY, page, pageSize); if (Enumerable.Count(model) > 0) return View("ListDetailNews", model); } catch (System.Exception) { } return View("~/Views/Shared/Error.cshtml"); } public ActionResult ListPartyCell(int page = 1, int pageSize = Constant.PAGESIZE) { try { var model = detailNewsService.PageListFE(Constant.NEWS_FROM_PARTY_CELL, page, pageSize); if (Enumerable.Count(model) > 0) return View("ListDetailNews", model); } catch (System.Exception) { } return View("~/Views/Shared/Error.cshtml"); } public ActionResult ListUnion(int page = 1, int pageSize = Constant.PAGESIZE) { try { var model = detailNewsService.PageListFE(Constant.NEWS_FROM_UNION, page, pageSize); if (Enumerable.Count(model) > 0) return View("ListDetailNews", model); } catch (System.Exception) { } return View("~/Views/Shared/Error.cshtml"); } } }
namespace Exam_Cube3D { using System; using MultidimensionalArrayExtensions; public static class Cube3D { public const string BordersSymbol = "*"; public const string FrontSideSymbol = " "; public const string RightSideSymbol = "|"; public const string BottomSideSymbol = "-"; public static void Main() { var sideSize = int.Parse(Console.ReadLine()); var symbols = new string[] { FrontSideSymbol, BordersSymbol, RightSideSymbol, BottomSideSymbol }; var drawer = new CubeDrawer(sideSize, symbols); drawer.Draw(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Tutorial : MonoBehaviour { enum StateMachine { waiting_for_a = 0, waiting_for_d, waiting_for_jump, waiting_for_warlord_slash, waiting_for_warlord_block, waiting_for_switch_to_elemental, waiting_for_elementalist_fire, waiting_for_elementalist_ice, waiting_for_switch_to_ranger, waiting_for_ranger_shot, waiting_for_ranger_haste, waiting_for_first_c, waiting_for_second_c, waiting_for_escape, exit, count } [System.Serializable] public struct MultidimensionalString { public string[] strings; } // Public Objects public GameObject warlord, elementalist, ranger; public Dialog dialog; // Public Instructions public MultidimensionalString[] keyInstructions = new MultidimensionalString[(int)StateMachine.count]; // Private State Machine private StateMachine state; private bool shouldWrite = true; private KeyCode[] codes = { KeyCode.A, KeyCode.D, KeyCode.Space, KeyCode.Mouse0, KeyCode.Mouse1, KeyCode.LeftShift, KeyCode.Mouse0, KeyCode.Mouse1, KeyCode.LeftShift, KeyCode.Mouse0, KeyCode.Mouse1, KeyCode.C, KeyCode.C, KeyCode.Break, KeyCode.Break }; // Start is called before the first frame update void Start() { state = StateMachine.waiting_for_a; dialog.timeout = 0; warlord.SetActive(true); elementalist.SetActive(false); ranger.SetActive(false); dialog.player = warlord.GetComponent<PlayerController>(); } // Update is called once per frame void Update() { WaitForKey(codes[(int)state], keyInstructions[(int)state].strings); switch (state) { case StateMachine.waiting_for_a: case StateMachine.waiting_for_d: case StateMachine.waiting_for_jump: break; case StateMachine.waiting_for_warlord_slash: case StateMachine.waiting_for_warlord_block: case StateMachine.waiting_for_switch_to_elemental: warlord.SetActive(true); elementalist.SetActive(false); ranger.SetActive(false); dialog.player = warlord.GetComponent<PlayerController>(); break; case StateMachine.waiting_for_elementalist_fire: case StateMachine.waiting_for_elementalist_ice: case StateMachine.waiting_for_switch_to_ranger: warlord.SetActive(false); elementalist.SetActive(true); ranger.SetActive(false); dialog.player = elementalist.GetComponent<PlayerController>(); break; case StateMachine.waiting_for_ranger_shot: case StateMachine.waiting_for_ranger_haste: warlord.SetActive(false); elementalist.SetActive(false); ranger.SetActive(true); dialog.player = ranger.GetComponent<PlayerController>(); break; case StateMachine.waiting_for_first_c: case StateMachine.waiting_for_second_c: break; case StateMachine.waiting_for_escape: if (dialog.textDisplay.text == "" && Input.GetKeyDown(KeyCode.LeftShift)) { if (warlord.activeSelf) { warlord.SetActive(false); elementalist.SetActive(true); ranger.SetActive(false); } else if (elementalist.activeSelf) { warlord.SetActive(false); elementalist.SetActive(false); ranger.SetActive(true); } else if (ranger.activeSelf) { warlord.SetActive(true); elementalist.SetActive(false); ranger.SetActive(false); } } break; case StateMachine.exit: default: break; } if (dialog.textDisplay.text == "" && Input.GetKeyDown(KeyCode.H)) { shouldWrite = true; } } void WaitForKey(KeyCode key, string[] instructions) { if (shouldWrite) { dialog.Display(instructions); } shouldWrite = false; if (dialog.textDisplay.text == "" && Input.GetKeyDown(key) && state != StateMachine.exit) { shouldWrite = true; state++; } } }
using PlatformRacing3.Server.Game.Communication.Messages.Outgoing.Json; namespace PlatformRacing3.Server.Game.Communication.Messages.Outgoing; internal class BeginMatchOutgoingMessage : JsonOutgoingMessage<JsonBeginMatchOutgoingMessage> { internal BeginMatchOutgoingMessage() : base(new JsonBeginMatchOutgoingMessage()) { } }
using System; using System.IO; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using MonoGame.Extended.Gui.Controls; using MonoGame.Extended.Gui.Serialization; using Newtonsoft.Json; namespace MonoGame.Extended.Gui { public class Screen //: Element<GuiSystem>, IDisposable { public Screen() { //Windows = new WindowCollection(this) { ItemAdded = w => _isLayoutRequired = true }; } public virtual void Dispose() { } private Control _content; [JsonProperty(Order = 1)] public Control Content { get { return _content; } set { if (_content != value) { _content = value; _isLayoutRequired = true; } } } //[JsonIgnore] //public WindowCollection Windows { get; } public float Width { get; private set; } public float Height { get; private set; } public Size2 Size => new Size2(Width, Height); public bool IsVisible { get; set; } = true; private bool _isLayoutRequired; [JsonIgnore] public bool IsLayoutRequired => _isLayoutRequired || Content.IsLayoutRequired; public virtual void Update(GameTime gameTime) { } public void Show() { IsVisible = true; } public void Hide() { IsVisible = false; } public T FindControl<T>(string name) where T : Control { return FindControl<T>(Content, name); } private static T FindControl<T>(Control rootControl, string name) where T : Control { if (rootControl.Name == name) return rootControl as T; foreach (var childControl in rootControl.Children) { var control = FindControl<T>(childControl, name); if (control != null) return control; } return null; } public void Layout(IGuiContext context, Rectangle rectangle) { Width = rectangle.Width; Height = rectangle.Height; LayoutHelper.PlaceControl(context, Content, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height); //foreach (var window in Windows) // LayoutHelper.PlaceWindow(context, window, rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height); _isLayoutRequired = false; Content.IsLayoutRequired = false; } //public override void Draw(IGuiContext context, IGuiRenderer renderer, float deltaSeconds) //{ // renderer.DrawRectangle(BoundingRectangle, Color.Green); //} public static Screen FromStream(ContentManager contentManager, Stream stream, params Type[] customControlTypes) { return FromStream<Screen>(contentManager, stream, customControlTypes); } public static TScreen FromStream<TScreen>(ContentManager contentManager, Stream stream, params Type[] customControlTypes) where TScreen : Screen { var skinService = new SkinService(); var serializer = new GuiJsonSerializer(contentManager, customControlTypes) { Converters = { new SkinJsonConverter(contentManager, skinService, customControlTypes), new ControlJsonConverter(skinService, customControlTypes) } }; using (var streamReader = new StreamReader(stream)) using (var jsonReader = new JsonTextReader(streamReader)) { var screen = serializer.Deserialize<TScreen>(jsonReader); return screen; } } public static Screen FromFile(ContentManager contentManager, string path, params Type[] customControlTypes) { using (var stream = TitleContainer.OpenStream(path)) { return FromStream<Screen>(contentManager, stream, customControlTypes); } } public static TScreen FromFile<TScreen>(ContentManager contentManager, string path, params Type[] customControlTypes) where TScreen : Screen { using (var stream = TitleContainer.OpenStream(path)) { return FromStream<TScreen>(contentManager, stream, customControlTypes); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Web; using System.Text; using System.Web.Hosting; using WebMarkupMin.Core; namespace AngularTemplates.Compile { public class TemplateCompiler { private readonly TemplateCompilerOptions _options; private readonly string _baseUrl; private readonly string _moduleName; private readonly string _workingDir; private const string DefaultModuleName = "app"; public TemplateCompiler(TemplateCompilerOptions options) { _options = options; _baseUrl = string.Empty; if (!string.IsNullOrWhiteSpace(options.Prefix)) { _baseUrl = options.Prefix; if (!_baseUrl.EndsWith("/")) { _baseUrl += "/"; } } _moduleName = string.IsNullOrWhiteSpace(options.ModuleName) ? DefaultModuleName : options.ModuleName; _workingDir = string.IsNullOrWhiteSpace(options.WorkingDir) ? Environment.CurrentDirectory : Path.GetFullPath(options.WorkingDir); } /// <summary> /// Compile template files into a string /// </summary> /// <param name="templateFiles"></param> /// <returns></returns> public string Compile<T>(T[] templateFiles) where T : VirtualFile { var sb = new StringBuilder(); using (var stream = new StringWriter(sb)) { Compile(stream, templateFiles); } return sb.ToString(); } /// <summary> /// Compile template files and save them to external file specified in options.OutputPath /// </summary> /// <param name="templateFiles"></param> public void CompileToFile<T>(T[] templateFiles) where T : VirtualFile { CheckOutputDir(); using (var stream = new StreamWriter(_options.OutputPath)) { Compile(stream, templateFiles); } } private void Compile<T>(TextWriter writer, T[] templateFiles) where T : VirtualFile { if (templateFiles == null) { templateFiles = new T[0]; } writer.Write("angular.module('"); writer.Write(_moduleName); writer.Write("'"); if (_options.Standalone) { writer.Write(", []"); } writer.WriteLine(").run(['$templateCache', function ($templateCache) {"); foreach (var file in templateFiles) { var templateName = GetTemplateName(file.VirtualPath); string template; using (var streamReader = new StreamReader(file.Open())) { template = streamReader.ReadToEnd(); } WriteToStream(writer, templateName, template); } writer.Write("}]);"); } private void WriteToStream(TextWriter writer, string templateName, string template) { writer.Write("$templateCache.put('"); writer.Write(templateName); writer.Write("', "); writer.Write(CompileTemplate(template)); writer.WriteLine(");"); } private string CompileTemplate(string template) { var minifiedHtml = MinifyHtml(template); return HttpUtility.JavaScriptStringEncode(minifiedHtml, true); } private string GetTemplateName(string file) { var name = _baseUrl + GetRelativePath(Path.GetFullPath(file), _workingDir); return _options.LowercaseTemplateName ? name.ToLower() : name; } private string GetRelativePath(string filespec, string folder) { var pathUri = new Uri(filespec); // Folders must end in a slash if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString())) { folder += Path.DirectorySeparatorChar; } var folderUri = new Uri(folder); return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString()); } private void CheckOutputDir() { var outputDir = Path.GetDirectoryName(_options.OutputPath); if (outputDir != null && !Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } } private string MinifyHtml(string html) { var htmlMinifier = new HtmlMinifier(); var result = htmlMinifier.Minify(html); if (result.Errors.Count == 0) { return result.MinifiedContent; } return GetMinificationError(html, result.Errors); } private string GetMinificationError(string originalHtml, IList<MinificationErrorInfo> errors) { var sb = new StringBuilder("<!-- Html minification failed. Returning unminified contents."); sb.Append(Environment.NewLine); foreach (var errorInfo in errors) { sb.AppendLine(errorInfo.Message).AppendLine(errorInfo.SourceFragment); } sb.AppendLine("-->").AppendLine(originalHtml); return sb.ToString(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Pitstop { public class CameraTransition : MonoBehaviour { [SerializeField] GameObject virtualCameraPlayer = default; [SerializeField] GameObject virtualCameraGlade = default; [SerializeField] Camera uiCamera = default; private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "Player") { virtualCameraGlade.SetActive(true); virtualCameraPlayer.SetActive(false); uiCamera.orthographicSize = 11; } } void OnTriggerEnter2D(Collider2D collider) { if (collider.gameObject.tag == "Player") { virtualCameraGlade.SetActive(true); virtualCameraPlayer.SetActive(false); uiCamera.orthographicSize = 11; } } private void OnCollisionExit2D(Collision2D collision) { if (collision.gameObject.tag == "Player") { virtualCameraPlayer.SetActive(true); virtualCameraGlade.SetActive(false); uiCamera.orthographicSize = 5; } } void OnTriggerExit2D(Collider2D collider) { if (collider.gameObject.tag == "Player") { virtualCameraPlayer.SetActive(true); virtualCameraGlade.SetActive(false); uiCamera.orthographicSize = 5; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Model.Security.MembershipManagement; using Model.DataEntity; using Business.Helper; using Model.Locale; using Uxnet.Web.WebUI; using System.Text.RegularExpressions; using Utility; namespace eIVOGo.Module.SAM { public partial class EditMyself : EditMember { protected override void initializeData() { UserProfileMember user = WebPageUtility.UserProfile; var item = dsUserProfile.CreateDataManager().EntityList.Where(u => u.UID == user.UID).FirstOrDefault(); if (item == null) { WebMessageBox.AjaxAlert(this, "使用者不存在!!"); } if (item.UserProfileStatus.CurrentLevel == (int)Naming.MemberStatusDefinition.Wait_For_Check) { user.CurrentSiteMenu = "WaitForCheckMenu.xml"; } EditItem.DataItem = item; } } }
using System; using System.Globalization; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using MMSCAN; using Sybase.Collections; using System.Diagnostics; namespace ScannerWinMobile { public partial class INVDocByDateSelectForm : Form { private Dictionary<DateTime, GenericList<ZFM_MOB_MMS_INV_SET_RFC_IT_INV_SET>> _possibleDocs = null; public GenericList<ZFM_MOB_MMS_INV_SET_RFC_IT_INV_SET> SelectedDoc { get; private set; } public INVDocByDateSelectForm() { InitializeComponent(); } private void fillListView() { _possibleDocs = DataStorage.GetInstance().INVSetS; if (_possibleDocs.Count == 0) { delButton.Enabled = false; selButton.Enabled = false; applyButton.Enabled = false; } docListView.Items.Clear(); foreach (var doc in _possibleDocs) { var maxDate = doc.Value.Max(set => (set.TIMEADD != null && set.DATEADD != null) ? new DateTime( set.DATEADD.Value.Year, set.DATEADD.Value.Month, set.DATEADD.Value.Day, set.TIMEADD.Value.Hour, set.TIMEADD.Value.Minute, set.TIMEADD.Value.Second) : DateTime.Now); var lastTMC = doc.Value.FirstOrDefault( set => set.TIMEADD != null && set.DATEADD != null && (set.DATEADD.Value.Year == maxDate.Year && set.DATEADD.Value.Month == maxDate.Month && set.DATEADD.Value.Day == maxDate.Day && set.TIMEADD.Value.Hour == maxDate.Hour && set.TIMEADD.Value.Minute == maxDate.Minute && set.TIMEADD.Value.Second == maxDate.Second)); string lastTMC_ZPOSITION = string.Empty; if (lastTMC != null) { lastTMC_ZPOSITION = lastTMC.ZPOSITION; } var item = new ListViewItem(new string[] { doc.Key.ToString(CultureInfo.InvariantCulture), lastTMC_ZPOSITION }); item.Tag = doc.Key; docListView.Items.Add(item); } } private void INVDocByDateSelectForm_KeyDown(object sender, KeyEventArgs e) { if ((e.KeyCode == System.Windows.Forms.Keys.F1)) { selButton_Click(null, null); } if ((e.KeyCode == System.Windows.Forms.Keys.F2)) // на удалении горячая клавиша опасна ) { } if ((e.KeyCode == System.Windows.Forms.Keys.F5)) { logButton_Click(null,null); } if ((e.KeyCode == System.Windows.Forms.Keys.F3)) { newButton_Click(null, null); } if ((e.KeyCode == System.Windows.Forms.Keys.F5)) { DataStorage.SafetyBeginSync(MBO_INV_HIST.GetSynchronizationGroup().Name); new INVHistForm().ShowDialog(); } if ((e.KeyCode == System.Windows.Forms.Keys.Escape)) { backButton_Click(null, null); } } private void docListView_SelectedIndexChanged(object sender, EventArgs e) { if (docListView.SelectedIndices.Count >= 1 && docListView.SelectedIndices[0] >= 0) { delButton.Enabled = true; selButton.Enabled = true; applyButton.Enabled = true; } else { delButton.Enabled = false; selButton.Enabled = false; applyButton.Enabled = false; } } private void selButton_Click(object sender, EventArgs e) { if (docListView.SelectedIndices.Count == 1 && docListView.SelectedIndices[0] >= 0) { var docDateTime = (DateTime) docListView.Items[docListView.SelectedIndices[0]].Tag; SelectedDoc = _possibleDocs[docDateTime]; DataStorage.GetInstance().DelINVSet(docDateTime); showNextForm(); } else { MessageBox.Show("Выберите один элемент из списка"); } } private void delButton_Click(object sender, EventArgs e) { var indexs = new int[docListView.SelectedIndices.Count]; docListView.SelectedIndices.CopyTo(indexs, 0); if (MessageBox.Show("Вы уверены?", "Удаление записей", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { foreach (var selIndex in indexs) { var docDateTime = (DateTime) docListView.Items[selIndex].Tag; DataStorage.GetInstance().DelINVSet(docDateTime); } fillListView(); } } private void backButton_Click(object sender, EventArgs e) { SelectedDoc = null; DlgStateMashine.showNextForm(StateChangeEvent.jumpType.KeyPressed_Esc); } private void newButton_Click(object sender, EventArgs e) { SelectedDoc = new GenericList<ZFM_MOB_MMS_INV_SET_RFC_IT_INV_SET>(); showNextForm(); } private void showNextForm() { DataStorage.SafetyBeginSync(MBO_INV.GetSynchronizationGroup().Name); var dlg = new INVScanBCofMaterialAssetsForm(); dlg.INVTable = SelectedDoc; dlg.ShowDialog(); fillListView(); // redundant: form_activated calling after modal dialog shown } private void INVDocByDateSelectForm_Activated(object sender, EventArgs e) { SUPсonnector.ConnectionChanged = new Action<Color>(delegate(Color color) { if (InvokeRequired) connectionStatusLabel.Invoke( new Action( () => connectionStatusLabel.BackColor = color)); else connectionStatusLabel.BackColor = color; }); fillListView(); } private void logButton_Click(object sender, EventArgs e) { DataStorage.SafetyBeginSync(MBO_INV_HIST.GetSynchronizationGroup().Name); var dlg = new INVHistForm(); dlg.ShowDialog(); } private void applyButton_Click(object sender, EventArgs e) { if (!((Control) sender).Enabled || !((Control) sender).Visible) return; if (docListView.SelectedIndices.Count != 1 || docListView.SelectedIndices[0] < 0) { MessageBox.Show("Выберите один элемент из списка"); return; } var pp = MMSCANDB.GetPersonalizationParameters(); Debug.WriteLine(pp.PKUsername); Debug.WriteLine(pp.PKUserpass); var docDateTime = (DateTime) docListView.Items[docListView.SelectedIndices[0]].Tag; var INVTable = _possibleDocs[docDateTime]; Cursor.Current = Cursors.WaitCursor; var rec = new MBO_INV_SET(); rec.Create(INVTable); rec.SubmitPending(); rec.Save(); MMSCANDB.Synchronize(MBO_INV_SET.GetSynchronizationGroup().Name); var errorMsg = MBO_INV_SET.FindAll().FirstOrDefault(set => set.Attr_E_RETURN_TEXT != string.Empty); Cursor.Current = Cursors.Default; if (errorMsg != null) { MessageBox.Show("Ошибка синхронизации:\r\n" + errorMsg.Attr_E_RETURN_TEXT, "Операция не выполнена", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1); } else { /* var successMsg = MBO_INV_SET.FindAll().FirstOrDefault(set => set.Attr_E_SUCCESS_TEXT != string.Empty); if (successMsg != null) { MessageBox.Show(successMsg.Attr_E_SUCCESS_TEXT, "Операция выполнена", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1); } */ DataStorage.GetInstance().DelINVSet(docDateTime); fillListView(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using RocksmithToolkitLib.DLCPackage; using RocksmithToolkitLib.DLCPackage.AggregateGraph; using RocksmithToolkitLib.DLCPackage.Manifest; using RocksmithToolkitLib.Sng; using RocksmithToolkitLib.Sng2014HSL; using RocksmithToolkitLib.Xml; using RocksmithToolkitLib.Extensions; using RocksmithToolkitLib.DLCPackage.Manifest.Tone; namespace RocksmithToolkitLib.DLCPackage { public enum RouteMask : int { // Used for lessons or for display only in song list None = 0, Lead = 1, Rhythm = 2, Any = 3, Bass = 4 } public enum DNAId : int { None = 0, Solo = 1, Riff = 2, Chord = 3 } public class Arrangement { private string _songFilename = null; public SongFile SongFile { get { var platform = new Platform(GamePlatform.Pc, GameVersion.RS2014); //FIXME var stream = new MemoryStream(); Sng2014.WriteSng(stream, platform); return new SongFile() { File = Path.ChangeExtension(_songFilename, ".sng"), Data = stream }; } } public SongXML SongXml { get { var platform = new Platform(GamePlatform.Pc, GameVersion.RS2014); //FIXME var stream = new MemoryStream(); dynamic xmlContent = null; if (this.ArrangementType == ArrangementType.Vocal) xmlContent = new Vocals(this.Sng2014); else xmlContent = new Song2014(this.Sng2014, null); xmlContent.Serialize(stream); stream.Seek(0, SeekOrigin.Begin); return new SongXML() { File = Path.ChangeExtension(_songFilename, ".xml"), Data = stream }; } } // Song Information public int ArrangementSort { get; set; } public ArrangementName Name { get; private set; } public string Tuning { get; set; } public TuningStrings TuningStrings { get; set; } public double TuningPitch { get; set; } public int ScrollSpeed { get; set; } public PluckedType PluckedType { get; set; } // cache parsing results (speeds up generating for multiple platforms) public Sng2014File Sng2014 { get; private set; } // Gameplay Path public RouteMask RouteMask { get; set; } public bool BonusArr = false; // Tone Selector public string ToneBase { get; set; } public string ToneMultiplayer { get; set; } public string ToneA { get; set; } public string ToneB { get; set; } public string ToneC { get; set; } public string ToneD { get; set; } public List<Tone2014> Tones { get; set; } // DLC ID public Guid Id { get; set; } public int MasterId { get; set; } public static Arrangement Read(Attributes2014 attr, Platform platform, Guid id, string filename, Stream data = null) { Arrangement result = null; using (var str = data ?? File.OpenRead(filename)) { switch (Path.GetExtension(filename)) { case ".xml": Sng2014File xml = null; if (((ArrangementName)attr.ArrangementType) == ArrangementName.Vocals) xml = Sng2014FileWriter.ReadVocals(data); else xml = Sng2014File.ConvertXML(str); result = new Arrangement(attr, xml, id); break; case ".sng": result = new Arrangement(attr, Sng2014File.ReadSng(str, platform), id); break; default: throw new Exception("Unknown file type: " + filename); } result._songFilename = filename; } return result; } public ArrangementType ArrangementType { get { switch (Name) { case ArrangementName.Bass: return Sng.ArrangementType.Bass; case ArrangementName.Vocals: return Sng.ArrangementType.Vocal; default: return Sng.ArrangementType.Guitar; } } } private Arrangement(Attributes2014 attr, Sng2014File song, Guid id) { this.ArrangementSort = attr.ArrangementSort; this.Sng2014 = song; this.Name = (ArrangementName)Enum.Parse(typeof(ArrangementName), attr.ArrangementName); this.ScrollSpeed = 20; this.Id = id; this.MasterId = ArrangementType == Sng.ArrangementType.Vocal ? 1 : RandomGenerator.NextInt(); if (this.ArrangementType == ArrangementType.Vocal) { this.Tones = new List<Tone2014>(); } else { ParseTuning(this, attr); ParseTones(this, attr); } } private static void ParseTones(Arrangement dest, Attributes2014 attr) { dest.ScrollSpeed = Convert.ToInt32(attr.DynamicVisualDensity.Last() * 10); dest.PluckedType = (PluckedType)attr.ArrangementProperties.BassPick; dest.RouteMask = (RouteMask)attr.ArrangementProperties.RouteMask; dest.BonusArr = attr.ArrangementProperties.BonusArr == 1; dest.ToneBase = attr.Tone_Base; dest.ToneMultiplayer = attr.Tone_Multiplayer; dest.ToneA = attr.Tone_A; dest.ToneB = attr.Tone_B; dest.ToneC = attr.Tone_C; dest.ToneD = attr.Tone_D; dest.Tones = attr.Tones.ToList(); } private static void ParseTuning(Arrangement dest, Attributes2014 attr) { bool isBass = false; TuningDefinition tuning = null; switch (dest.Name) { case ArrangementName.Bass: tuning = TuningDefinitionRepository.Instance().SelectForBass(attr.Tuning, GameVersion.RS2014); isBass = true; break; case ArrangementName.Vocals: break; default: tuning = TuningDefinitionRepository.Instance().Select(attr.Tuning, GameVersion.RS2014); break; } if (tuning == null) { tuning = new TuningDefinition(); tuning.UIName = tuning.Name = TuningDefinition.NameFromStrings(attr.Tuning, isBass); tuning.Custom = true; tuning.GameVersion = GameVersion.RS2014; tuning.Tuning = attr.Tuning; TuningDefinitionRepository.Instance().Add(tuning, true); } dest.Tuning = tuning.UIName; dest.TuningStrings = tuning.Tuning; if (attr.CentOffset != null) dest.TuningPitch = attr.CentOffset.Cents2Frequency(); } public override string ToString() { var toneDesc = String.Empty; if (!String.IsNullOrEmpty(ToneBase)) toneDesc = ToneBase; if (!String.IsNullOrEmpty(ToneB)) toneDesc += String.Format(", {0}", ToneB); if (!String.IsNullOrEmpty(ToneC)) toneDesc += String.Format(", {0}", ToneC); if (!String.IsNullOrEmpty(ToneD)) toneDesc += String.Format(", {0}", ToneD); switch (ArrangementType) { case ArrangementType.Bass: return String.Format("{0} [{1}] ({2})", ArrangementType, Tuning, toneDesc); case ArrangementType.Vocal: return String.Format("{0}", ArrangementType); default: return String.Format("{0} - {1} [{2}] ({3})", ArrangementType, Name, Tuning, toneDesc); } } public void CleanCache() { Sng2014 = null; } public string SongFilePath { get { return Path.ChangeExtension(this._songFilename, ".sng"); } } } }
using PDV.CONTROLER.Funcoes; using PDV.DAO.DB.Utils; using PDV.DAO.Entidades; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PDV.VIEW.Forms.Gerenciamento.DAV { public partial class LoginAdminDAV : DevExpress.XtraEditors.XtraForm { public Usuario Logado = null; public bool isLogado { get; set; } = false; public LoginAdminDAV() { InitializeComponent(); } private void Logar() { if (string.IsNullOrEmpty(ovTXT_Login.Text.Trim())) { ovTXT_StatusLogin.Text = "Informe o Login."; ovTXT_Login.Select(); Alert("Informe o Login."); return; } if (string.IsNullOrEmpty(ovTXT_Senha.Text.Trim())) { ovTXT_StatusLogin.Text = "Informe a Senha."; ovTXT_Senha.Select(); Alert("Informe a Senha."); return; } ovTXT_StatusLogin.Text = ""; Logado = FuncoesUsuario.GetUsuarioRoot(ovTXT_Login.Text, Criptografia.CodificaSenha(ovTXT_Senha.Text)); if (Logado != null) { if (!IsAdmin()) { ovTXT_StatusLogin.Text = "Este Usuário não é Administrador."; Alert("Usuário não é Administrador."); } else { isLogado = true; Close(); ovTXT_Senha.Text = ""; } } else { Logado = FuncoesUsuario.GetUsuarioPorLoginESenha(ovTXT_Login.Text, Criptografia.CodificaSenha(ovTXT_Senha.Text)); if (Logado == null) { ovTXT_StatusLogin.Text = "Email ou Senha Incorreto."; Alert("Email ou Senha Incorreto."); Logado = null; return; } else { if (!IsAdmin()) { ovTXT_StatusLogin.Text = "Este Usuário não é Administrador."; Alert("Usuário não é Administrador."); } else { isLogado = true; Close(); ovTXT_Senha.Text = ""; } } } } public void Alert(string texto) { MessageBox.Show(texto, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } private bool IsAdmin() { PerfilAcesso perfil = FuncoesPerfilAcesso.GetPerfil(Logado.IDPerfilAcesso); return perfil.IsAdmin == 1; } private void logarTextBox_Click(object sender, EventArgs e) { Logar(); } private void button1_Click(object sender, EventArgs e) { Close(); } private void LoginAdminDAV_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) Logar(); if (e.KeyCode == Keys.Escape) Close(); } } }
 namespace hilcoe.securityCourse { /// <summary> /// AES class. /// </summary> public static partial class AES { /// <summary> /// Cipher method. /// </summary> /// <param name="input"></param> /// <param name="key"></param> /// <returns></returns> public static byte[] Cipher(byte[] input, byte[] key) { throw new System.NotImplementedException(); } /// <summary> /// Decipher method. /// </summary> /// <param name="input"></param> /// <param name="key"></param> /// <returns></returns> public static byte[] Decipher(byte[] input, byte[] key) { throw new System.NotImplementedException(); } } }
using System.Data; using Moq; using NUnit.Framework; namespace Tolley.Data.Tests { [TestFixture] public class DataContextTests { private static IDbTransaction GetMockTransaction() { IDbTransaction transaction = new Mock<IDbTransaction>().Object; return transaction; } private static IDbConnection GetMockConnection() { var connection = new Mock<IDbConnection>(); connection.Setup(x => x.BeginTransaction()).Returns(GetMockTransaction); return connection.Object; } private static IConnectionFactory GetMockConnectionFactory() { var factory = new Mock<IConnectionFactory>(); factory.Setup(f => f.GetConnection()).Returns(GetMockConnection); return factory.Object; } [Test] public void Dispose_CleansUpTransaction() { var transaction = new Mock<IDbTransaction>(); var connection = new Mock<IDbConnection>(); connection.Setup(x => x.BeginTransaction()).Returns(transaction.Object); var factory = new Mock<IConnectionFactory>(); factory.Setup(f => f.GetConnection()).Returns(connection.Object); IUnitOfWork uow; using (var context = new DataContext(factory.Object)) { uow = context.BeginScope(); } Assert.IsNotNull(uow); transaction.Verify(x => x.Rollback(), Times.Once); transaction.Verify(x => x.Dispose(), Times.Once); } [Test] public void Dispose_ClosesConnection() { var transaction = new Mock<IDbTransaction>(); var connection = new Mock<IDbConnection>(); connection.Setup(x => x.BeginTransaction()).Returns(transaction.Object); var factory = new Mock<IConnectionFactory>(); factory.Setup(f => f.GetConnection()).Returns(connection.Object); using (new DataContext(factory.Object)) { } connection.Verify(x => x.Close(), Times.Once); } [Test] public void BeginScope_ReturnsAUnitOfWork() { var context = new DataContext(GetMockConnectionFactory()); using (IUnitOfWork uow = context.BeginScope()) { Assert.IsNotNull(uow); } } [Test] public void FinalSaveChanges_CommitsTransaction() { var transaction = new Mock<IDbTransaction>(); var connection = new Mock<IDbConnection>(); connection.Setup(x => x.BeginTransaction()).Returns(transaction.Object); var factory = new Mock<IConnectionFactory>(); factory.Setup(f => f.GetConnection()).Returns(connection.Object); var context = new DataContext(factory.Object); using (IUnitOfWork uow = context.BeginScope()) { using (IUnitOfWork uow2 = context.BeginScope()) { uow2.SaveChanges(); } uow.SaveChanges(); } transaction.Verify(x => x.Commit(), Times.Once); } [Test] public void InnerSaveChanges_DoesNotCommitTransaction() { var transaction = new Mock<IDbTransaction>(); var connection = new Mock<IDbConnection>(); connection.Setup(x => x.BeginTransaction()).Returns(transaction.Object); var factory = new Mock<IConnectionFactory>(); factory.Setup(f => f.GetConnection()).Returns(connection.Object); var context = new DataContext(factory.Object); using (context.BeginScope()) { using (IUnitOfWork uow2 = context.BeginScope()) { uow2.SaveChanges(); transaction.Verify(x => x.Commit(), Times.Never); } } } [Test] public void NestedUnitOfWork_UsesSameTransaction() { var context = new DataContext(GetMockConnectionFactory()); using (context.BeginScope()) { IDbTransaction trn = context.Transaction; using (context.BeginScope()) { Assert.AreSame(trn, context.Transaction); } } } [Test] public void UnitOfWork_IfCommitted_DoesNotRollBackOnDispose() { var transaction = new Mock<IDbTransaction>(); var connection = new Mock<IDbConnection>(); connection.Setup(x => x.BeginTransaction()).Returns(transaction.Object); var factory = new Mock<IConnectionFactory>(); factory.Setup(f => f.GetConnection()).Returns(connection.Object); var context = new DataContext(factory.Object); using (context.BeginScope()) { using (IUnitOfWork uow2 = context.BeginScope()) { uow2.SaveChanges(); } transaction.Verify(x => x.Rollback(), Times.Never); } } [Test] public void UnitOfWork_IfInnerRolledBack_RollsBackAll() { var transaction = new Mock<IDbTransaction>(); var connection = new Mock<IDbConnection>(); connection.Setup(x => x.BeginTransaction()).Returns(transaction.Object); var factory = new Mock<IConnectionFactory>(); factory.Setup(f => f.GetConnection()).Returns(connection.Object); var context = new DataContext(factory.Object); using (IUnitOfWork uow = context.BeginScope()) { using (context.BeginScope()) { } uow.SaveChanges(); } transaction.Verify(x => x.Commit(), Times.Never); } [Test] public void UnitOfWork_IfNotSaved_RollsBack() { var transaction = new Mock<IDbTransaction>(); var connection = new Mock<IDbConnection>(); connection.Setup(x => x.BeginTransaction()).Returns(transaction.Object); var factory = new Mock<IConnectionFactory>(); factory.Setup(f => f.GetConnection()).Returns(connection.Object); var context = new DataContext(factory.Object); using (context.BeginScope()) { } transaction.Verify(x => x.Rollback(), Times.Once); } [Test] public void UnitOfWork_IfSaved_CommitsTransaction() { var transaction = new Mock<IDbTransaction>(); var connection = new Mock<IDbConnection>(); connection.Setup(x => x.BeginTransaction()).Returns(transaction.Object); var factory = new Mock<IConnectionFactory>(); factory.Setup(f => f.GetConnection()).Returns(connection.Object); var context = new DataContext(factory.Object); using (IUnitOfWork uow = context.BeginScope()) { uow.SaveChanges(); } transaction.Verify(x => x.Commit(), Times.Once); } } }
using System; using Android.Media; using System.IO; using Xamarin.Forms; using App1.Droid.Services; using App1.Services; using Uri = Android.Net.Uri; [assembly: Dependency(typeof(CVoiceRecorder))] namespace App1.Droid.Services { class CVoiceRecorder : IVoiceRecorder { private MediaPlayer player; private MediaRecorder recorder; private string audioFilePath; public bool PrepareRecord() { try { string fileName = $"Myfile{DateTime.Now.ToString("yyyyMMddHHmmss")}.wav"; audioFilePath = Path.Combine(Path.GetTempPath(), fileName); if (recorder == null) { recorder = new MediaRecorder(); } else { recorder.Reset(); } Console.WriteLine("daeseong1"); recorder.SetAudioSource(AudioSource.Mic); recorder.SetOutputFormat(OutputFormat.ThreeGpp); recorder.SetAudioEncoder(AudioEncoder.Aac); recorder.SetOutputFile(audioFilePath); recorder.Prepare(); Console.WriteLine("daeseong2"); return true; } catch { return false; } } public string GetPlayPath() { return audioFilePath; } public bool Record() { try { recorder.Start(); return true; } catch (Exception e) { Console.WriteLine(e.InnerException); return false; } } public void Play(string path) { try { var ctx = Forms.Context; player = MediaPlayer.Create(ctx, Uri.Parse(path)); player.Start(); } catch { Console.WriteLine("daeseong3"); } } public void StopRecord() { try { recorder.Stop(); recorder.Reset(); recorder.Release(); MessagingCenter.Send(this, "voiceRecorded", audioFilePath); } catch { Console.WriteLine("daeseong4"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Zhouli.BLL; using Zhouli.BLL.Interface; using Zhouli.BlogWebApi.Filters.ArticleBrowsing; using Zhouli.Common.ResultModel; using Zhouli.DbEntity.Models; using Zhouli.DI; using Zhouli.Dto.ModelDto; using static Zhouli.DbEntity.Models.ZhouLiEnum; namespace Zhouli.BlogWebApi.Controllers { /// <summary> /// 轮播图api /// </summary> [Route("api/blog/navigationimg")] [ApiController] [Authorize] public class NavigationImgController : Controller { private readonly IBlogNavigationImgBLL _blogNavigationImgBLL; public NavigationImgController(IBlogNavigationImgBLL blogNavigationImgBLL) { _blogNavigationImgBLL = blogNavigationImgBLL; } /// <summary> /// 获取所有轮播图 /// </summary> /// <returns></returns> [HttpGet("")] public IActionResult GetNavigationImgList() { return Ok(new ResponseModel { Data = _blogNavigationImgBLL.GetModels(t => t.DeleteSign == (int)Enum_DeleteSign.Sing_Deleted).Select(t => new { t.NavigationImgDescribe, t.NavigationImgUrl }) }); } } }
using eForm.EFlight; using eForm.EFlight; using eForm.EFlight; using System; using System.Linq; using System.Linq.Dynamic.Core; using Abp.Linq.Extensions; using System.Collections.Generic; using System.Threading.Tasks; using Abp.Domain.Repositories; using eForm.EFlight.Exporting; using eForm.EFlight.Dtos; using eForm.Dto; using Abp.Application.Services.Dto; using eForm.Authorization; using Abp.Extensions; using Abp.Authorization; using Microsoft.EntityFrameworkCore; namespace eForm.EFlight { [AbpAuthorize(AppPermissions.Pages_Flights)] public class FlightsAppService : eFormAppServiceBase, IFlightsAppService { private readonly IRepository<Flight> _flightRepository; private readonly IFlightsExcelExporter _flightsExcelExporter; private readonly IRepository<TravelAgent,int> _lookup_travelAgentRepository; private readonly IRepository<Purpose,int> _lookup_purposeRepository; private readonly IRepository<JobTitle,int> _lookup_jobTitleRepository; public FlightsAppService(IRepository<Flight> flightRepository, IFlightsExcelExporter flightsExcelExporter , IRepository<TravelAgent, int> lookup_travelAgentRepository, IRepository<Purpose, int> lookup_purposeRepository, IRepository<JobTitle, int> lookup_jobTitleRepository) { _flightRepository = flightRepository; _flightsExcelExporter = flightsExcelExporter; _lookup_travelAgentRepository = lookup_travelAgentRepository; _lookup_purposeRepository = lookup_purposeRepository; _lookup_jobTitleRepository = lookup_jobTitleRepository; } public async Task<PagedResultDto<GetFlightForViewDto>> GetAll(GetAllFlightsInput input) { var filteredFlights = _flightRepository.GetAll() .Include( e => e.TravelAgentFk) .Include( e => e.PurposeFk) .Include( e => e.JobTitleFk) .WhereIf(!string.IsNullOrWhiteSpace(input.Filter), e => false || e.Detail.Contains(input.Filter) || e.Name.Contains(input.Filter) || e.NRIC.Contains(input.Filter) || e.StaffID.Contains(input.Filter) || e.Position.Contains(input.Filter) || e.Email.Contains(input.Filter) || e.PhoneNo.Contains(input.Filter) || e.MembershipNo.Contains(input.Filter) || e.ValidationName.Contains(input.Filter) || e.ValidationPhoneNo.Contains(input.Filter) || e.ValidationPosition.Contains(input.Filter) || e.ApprovalName.Contains(input.Filter) || e.ApprovalPosition.Contains(input.Filter)) .WhereIf(!string.IsNullOrWhiteSpace(input.DetailFilter), e => e.Detail == input.DetailFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.NameFilter), e => e.Name == input.NameFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.NRICFilter), e => e.NRIC == input.NRICFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.StaffIDFilter), e => e.StaffID == input.StaffIDFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.PositionFilter), e => e.Position == input.PositionFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.EmailFilter), e => e.Email == input.EmailFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.PhoneNoFilter), e => e.PhoneNo == input.PhoneNoFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.MembershipNoFilter), e => e.MembershipNo == input.MembershipNoFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.ValidationNameFilter), e => e.ValidationName == input.ValidationNameFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.ValidationPhoneNoFilter), e => e.ValidationPhoneNo == input.ValidationPhoneNoFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.ValidationPositionFilter), e => e.ValidationPosition == input.ValidationPositionFilter) .WhereIf(input.MinValidationDateFilter != null, e => e.ValidationDate >= input.MinValidationDateFilter) .WhereIf(input.MaxValidationDateFilter != null, e => e.ValidationDate <= input.MaxValidationDateFilter) .WhereIf(input.ValidationFilter > -1, e => (input.ValidationFilter == 1 && e.Validation) || (input.ValidationFilter == 0 && !e.Validation) ) .WhereIf(!string.IsNullOrWhiteSpace(input.ApprovalNameFilter), e => e.ApprovalName == input.ApprovalNameFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.ApprovalPositionFilter), e => e.ApprovalPosition == input.ApprovalPositionFilter) .WhereIf(input.MinApprovalDateFilter != null, e => e.ApprovalDate >= input.MinApprovalDateFilter) .WhereIf(input.MaxApprovalDateFilter != null, e => e.ApprovalDate <= input.MaxApprovalDateFilter) .WhereIf(input.ApprovalFilter > -1, e => (input.ApprovalFilter == 1 && e.Approval) || (input.ApprovalFilter == 0 && !e.Approval) ) .WhereIf(!string.IsNullOrWhiteSpace(input.TravelAgentNameFilter), e => e.TravelAgentFk != null && e.TravelAgentFk.Name == input.TravelAgentNameFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.PurposeNameFilter), e => e.PurposeFk != null && e.PurposeFk.Name == input.PurposeNameFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.JobTitleNameFilter), e => e.JobTitleFk != null && e.JobTitleFk.Name == input.JobTitleNameFilter); var pagedAndFilteredFlights = filteredFlights .OrderBy(input.Sorting ?? "id asc") .PageBy(input); var flights = from o in pagedAndFilteredFlights join o1 in _lookup_travelAgentRepository.GetAll() on o.TravelAgentId equals o1.Id into j1 from s1 in j1.DefaultIfEmpty() join o2 in _lookup_purposeRepository.GetAll() on o.PurposeId equals o2.Id into j2 from s2 in j2.DefaultIfEmpty() join o3 in _lookup_jobTitleRepository.GetAll() on o.JobTitleId equals o3.Id into j3 from s3 in j3.DefaultIfEmpty() select new GetFlightForViewDto() { Flight = new FlightDto { Detail = o.Detail, Name = o.Name, NRIC = o.NRIC, StaffID = o.StaffID, Position = o.Position, Email = o.Email, PhoneNo = o.PhoneNo, MembershipNo = o.MembershipNo, ValidationName = o.ValidationName, ValidationPhoneNo = o.ValidationPhoneNo, ValidationPosition = o.ValidationPosition, ValidationDate = o.ValidationDate, Validation = o.Validation, ApprovalName = o.ApprovalName, ApprovalPosition = o.ApprovalPosition, ApprovalDate = o.ApprovalDate, Approval = o.Approval, Id = o.Id }, TravelAgentName = s1 == null ? "" : s1.Name.ToString(), PurposeName = s2 == null ? "" : s2.Name.ToString(), JobTitleName = s3 == null ? "" : s3.Name.ToString() }; var totalCount = await filteredFlights.CountAsync(); return new PagedResultDto<GetFlightForViewDto>( totalCount, await flights.ToListAsync() ); } public async Task<GetFlightForViewDto> GetFlightForView(int id) { var flight = await _flightRepository.GetAsync(id); var output = new GetFlightForViewDto { Flight = ObjectMapper.Map<FlightDto>(flight) }; if (output.Flight.TravelAgentId != null) { var _lookupTravelAgent = await _lookup_travelAgentRepository.FirstOrDefaultAsync((int)output.Flight.TravelAgentId); output.TravelAgentName = _lookupTravelAgent.Name.ToString(); } if (output.Flight.PurposeId != null) { var _lookupPurpose = await _lookup_purposeRepository.FirstOrDefaultAsync((int)output.Flight.PurposeId); output.PurposeName = _lookupPurpose.Name.ToString(); } if (output.Flight.JobTitleId != null) { var _lookupJobTitle = await _lookup_jobTitleRepository.FirstOrDefaultAsync((int)output.Flight.JobTitleId); output.JobTitleName = _lookupJobTitle.Name.ToString(); } return output; } [AbpAuthorize(AppPermissions.Pages_Flights_Edit)] public async Task<GetFlightForEditOutput> GetFlightForEdit(EntityDto input) { var flight = await _flightRepository.FirstOrDefaultAsync(input.Id); var output = new GetFlightForEditOutput {Flight = ObjectMapper.Map<CreateOrEditFlightDto>(flight)}; if (output.Flight.TravelAgentId != null) { var _lookupTravelAgent = await _lookup_travelAgentRepository.FirstOrDefaultAsync((int)output.Flight.TravelAgentId); output.TravelAgentName = _lookupTravelAgent.Name.ToString(); } if (output.Flight.PurposeId != null) { var _lookupPurpose = await _lookup_purposeRepository.FirstOrDefaultAsync((int)output.Flight.PurposeId); output.PurposeName = _lookupPurpose.Name.ToString(); } if (output.Flight.JobTitleId != null) { var _lookupJobTitle = await _lookup_jobTitleRepository.FirstOrDefaultAsync((int)output.Flight.JobTitleId); output.JobTitleName = _lookupJobTitle.Name.ToString(); } return output; } public async Task CreateOrEdit(CreateOrEditFlightDto input) { if(input.Id == null){ await Create(input); } else{ await Update(input); } } [AbpAuthorize(AppPermissions.Pages_Flights_Create)] protected virtual async Task Create(CreateOrEditFlightDto input) { var flight = ObjectMapper.Map<Flight>(input); if (AbpSession.TenantId != null) { flight.TenantId = (int?) AbpSession.TenantId; } await _flightRepository.InsertAsync(flight); } [AbpAuthorize(AppPermissions.Pages_Flights_Edit)] protected virtual async Task Update(CreateOrEditFlightDto input) { var flight = await _flightRepository.FirstOrDefaultAsync((int)input.Id); ObjectMapper.Map(input, flight); } [AbpAuthorize(AppPermissions.Pages_Flights_Delete)] public async Task Delete(EntityDto input) { await _flightRepository.DeleteAsync(input.Id); } public async Task<FileDto> GetFlightsToExcel(GetAllFlightsForExcelInput input) { var filteredFlights = _flightRepository.GetAll() .Include( e => e.TravelAgentFk) .Include( e => e.PurposeFk) .Include( e => e.JobTitleFk) .WhereIf(!string.IsNullOrWhiteSpace(input.Filter), e => false || e.Detail.Contains(input.Filter) || e.Name.Contains(input.Filter) || e.NRIC.Contains(input.Filter) || e.StaffID.Contains(input.Filter) || e.Position.Contains(input.Filter) || e.Email.Contains(input.Filter) || e.PhoneNo.Contains(input.Filter) || e.MembershipNo.Contains(input.Filter) || e.ValidationName.Contains(input.Filter) || e.ValidationPhoneNo.Contains(input.Filter) || e.ValidationPosition.Contains(input.Filter) || e.ApprovalName.Contains(input.Filter) || e.ApprovalPosition.Contains(input.Filter)) .WhereIf(!string.IsNullOrWhiteSpace(input.DetailFilter), e => e.Detail == input.DetailFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.NameFilter), e => e.Name == input.NameFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.NRICFilter), e => e.NRIC == input.NRICFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.StaffIDFilter), e => e.StaffID == input.StaffIDFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.PositionFilter), e => e.Position == input.PositionFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.EmailFilter), e => e.Email == input.EmailFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.PhoneNoFilter), e => e.PhoneNo == input.PhoneNoFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.MembershipNoFilter), e => e.MembershipNo == input.MembershipNoFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.ValidationNameFilter), e => e.ValidationName == input.ValidationNameFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.ValidationPhoneNoFilter), e => e.ValidationPhoneNo == input.ValidationPhoneNoFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.ValidationPositionFilter), e => e.ValidationPosition == input.ValidationPositionFilter) .WhereIf(input.MinValidationDateFilter != null, e => e.ValidationDate >= input.MinValidationDateFilter) .WhereIf(input.MaxValidationDateFilter != null, e => e.ValidationDate <= input.MaxValidationDateFilter) .WhereIf(input.ValidationFilter > -1, e => (input.ValidationFilter == 1 && e.Validation) || (input.ValidationFilter == 0 && !e.Validation) ) .WhereIf(!string.IsNullOrWhiteSpace(input.ApprovalNameFilter), e => e.ApprovalName == input.ApprovalNameFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.ApprovalPositionFilter), e => e.ApprovalPosition == input.ApprovalPositionFilter) .WhereIf(input.MinApprovalDateFilter != null, e => e.ApprovalDate >= input.MinApprovalDateFilter) .WhereIf(input.MaxApprovalDateFilter != null, e => e.ApprovalDate <= input.MaxApprovalDateFilter) .WhereIf(input.ApprovalFilter > -1, e => (input.ApprovalFilter == 1 && e.Approval) || (input.ApprovalFilter == 0 && !e.Approval) ) .WhereIf(!string.IsNullOrWhiteSpace(input.TravelAgentNameFilter), e => e.TravelAgentFk != null && e.TravelAgentFk.Name == input.TravelAgentNameFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.PurposeNameFilter), e => e.PurposeFk != null && e.PurposeFk.Name == input.PurposeNameFilter) .WhereIf(!string.IsNullOrWhiteSpace(input.JobTitleNameFilter), e => e.JobTitleFk != null && e.JobTitleFk.Name == input.JobTitleNameFilter); var query = (from o in filteredFlights join o1 in _lookup_travelAgentRepository.GetAll() on o.TravelAgentId equals o1.Id into j1 from s1 in j1.DefaultIfEmpty() join o2 in _lookup_purposeRepository.GetAll() on o.PurposeId equals o2.Id into j2 from s2 in j2.DefaultIfEmpty() join o3 in _lookup_jobTitleRepository.GetAll() on o.JobTitleId equals o3.Id into j3 from s3 in j3.DefaultIfEmpty() select new GetFlightForViewDto() { Flight = new FlightDto { Detail = o.Detail, Name = o.Name, NRIC = o.NRIC, StaffID = o.StaffID, Position = o.Position, Email = o.Email, PhoneNo = o.PhoneNo, MembershipNo = o.MembershipNo, ValidationName = o.ValidationName, ValidationPhoneNo = o.ValidationPhoneNo, ValidationPosition = o.ValidationPosition, ValidationDate = o.ValidationDate, Validation = o.Validation, ApprovalName = o.ApprovalName, ApprovalPosition = o.ApprovalPosition, ApprovalDate = o.ApprovalDate, Approval = o.Approval, Id = o.Id }, TravelAgentName = s1 == null ? "" : s1.Name.ToString(), PurposeName = s2 == null ? "" : s2.Name.ToString(), JobTitleName = s3 == null ? "" : s3.Name.ToString() }); var flightListDtos = await query.ToListAsync(); return _flightsExcelExporter.ExportToFile(flightListDtos); } [AbpAuthorize(AppPermissions.Pages_Flights)] public async Task<PagedResultDto<FlightTravelAgentLookupTableDto>> GetAllTravelAgentForLookupTable(GetAllForLookupTableInput input) { var query = _lookup_travelAgentRepository.GetAll().WhereIf( !string.IsNullOrWhiteSpace(input.Filter), e=> (e.Name != null ? e.Name.ToString():"").Contains(input.Filter) ); var totalCount = await query.CountAsync(); var travelAgentList = await query .PageBy(input) .ToListAsync(); var lookupTableDtoList = new List<FlightTravelAgentLookupTableDto>(); foreach(var travelAgent in travelAgentList){ lookupTableDtoList.Add(new FlightTravelAgentLookupTableDto { Id = travelAgent.Id, DisplayName = travelAgent.Name?.ToString() }); } return new PagedResultDto<FlightTravelAgentLookupTableDto>( totalCount, lookupTableDtoList ); } [AbpAuthorize(AppPermissions.Pages_Flights)] public async Task<PagedResultDto<FlightPurposeLookupTableDto>> GetAllPurposeForLookupTable(GetAllForLookupTableInput input) { var query = _lookup_purposeRepository.GetAll().WhereIf( !string.IsNullOrWhiteSpace(input.Filter), e=> (e.Name != null ? e.Name.ToString():"").Contains(input.Filter) ); var totalCount = await query.CountAsync(); var purposeList = await query .PageBy(input) .ToListAsync(); var lookupTableDtoList = new List<FlightPurposeLookupTableDto>(); foreach(var purpose in purposeList){ lookupTableDtoList.Add(new FlightPurposeLookupTableDto { Id = purpose.Id, DisplayName = purpose.Name?.ToString() }); } return new PagedResultDto<FlightPurposeLookupTableDto>( totalCount, lookupTableDtoList ); } [AbpAuthorize(AppPermissions.Pages_Flights)] public async Task<PagedResultDto<FlightJobTitleLookupTableDto>> GetAllJobTitleForLookupTable(GetAllForLookupTableInput input) { var query = _lookup_jobTitleRepository.GetAll().WhereIf( !string.IsNullOrWhiteSpace(input.Filter), e=> (e.Name != null ? e.Name.ToString():"").Contains(input.Filter) ); var totalCount = await query.CountAsync(); var jobTitleList = await query .PageBy(input) .ToListAsync(); var lookupTableDtoList = new List<FlightJobTitleLookupTableDto>(); foreach(var jobTitle in jobTitleList){ lookupTableDtoList.Add(new FlightJobTitleLookupTableDto { Id = jobTitle.Id, DisplayName = jobTitle.Name?.ToString() }); } return new PagedResultDto<FlightJobTitleLookupTableDto>( totalCount, lookupTableDtoList ); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Slime : MonoBehaviour { public float health; public float moveSpeed; public float posX; public float posY; public float cumPosX = 0, cumPosY = 0; public float damage; Transform player; private Vector3 moveDir; void Awake() {// IDK what awake does but it was in the tutoral lol player = GameObject.FindGameObjectWithTag ("Player").transform; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { moveToPlayer (); } void OnTriggerStay2D(Collider2D other) { //This will do ticks of damage every frame, however it stops until the player moves again at about 20 frames //Debug.Log (other); if(other.gameObject.tag.Equals("Player")) { other.gameObject.GetComponent<Player> ().takeDamage(damage); } //Destroy (this.gameObject); } public void takeDamage(float damage) {//death, damage, pain health -= damage; this.gameObject.GetComponentInChildren<Fade>().fade(); this.gameObject.GetComponent<GUIscript> ().takeDamage (); if(health <= 0) { die(); } } void die() {// :( Destroy (this.gameObject); } public void moveToPlayer() { //Spent forever on this only to find a function that was easy if(Global.playerAlive == true) { this.transform.position = Vector3.MoveTowards (transform.position,player.transform.position,moveSpeed * Time.deltaTime); } } public float getHealth(){ return health; } }
namespace CMS_Database.Entities { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("PhieuNhap")] public partial class PhieuNhap { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public PhieuNhap() { CTPhieuNhap = new HashSet<CTPhieuNhap>(); } public int Id { get; set; } public int? IdNhaCungCap { get; set; } public DateTime NgayTao { get; set; } public int? IdNhanVien { get; set; } public double? TongTien { get; set; } [StringLength(50)] public string GhiChu { get; set; } public bool? IsDetele { get; set; } public bool? IsPrint { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<CTPhieuNhap> CTPhieuNhap { get; set; } public virtual NhaCungCap NhaCungCap { get; set; } public virtual NhanVien NhanVien { get; set; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Resources; using Utility.Logger; namespace JKMServices.DAL.SQL { public static class ConnectionManager { public enum SqlCommandType : byte { Query = 1, StoreProcedure }; private static SqlConnection sqlConnection; private static SqlCommand sqlCommand; private static readonly ResourceManager resourceManager; private static readonly Logger loggerObject; private static readonly LoggerStackTrace loggerStackTrace; static ConnectionManager() { resourceManager = new System.Resources.ResourceManager("JKMServices.DAL.Resource", System.Reflection.Assembly.GetExecutingAssembly()); //Create the objects for logger as new. This object can't be injected in static class. loggerStackTrace = new LoggerStackTrace(); loggerObject = new Logger(loggerStackTrace); } /// <summary> /// Property Name : GetSQLConnection /// Author : Vivek Bhavsar /// Creation Date : 29 Nov 2017 /// Purpose : Get SQL Connection /// Revision : /// </summary> private static void GetSQLConnection() { sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["JKMDBContext"].ConnectionString); sqlConnection.Open(); loggerObject.Info(resourceManager.GetString("sqlConnectionOpened")); sqlCommand = new SqlCommand { Connection = sqlConnection }; } /// <summary> /// Property Name : CloseSQLConnection /// Author : Vivek Bhavsar /// Creation Date : 29 Nov 2017 /// Purpose : Close SQL Connection /// Revision : /// </summary> private static void CloseSQLConnection() { if (sqlConnection != null && sqlConnection.State == ConnectionState.Open) { loggerObject.Info(resourceManager.GetString("sqlConnectionClosed")); sqlConnection.Close(); } } /// <summary> /// Property Name : GetQuery /// Author : Vivek Bhavsar /// Creation Date : 29 Nov 2017 /// Purpose : Close SQL Connection /// Revision : /// </summary> private static string GetQuery(string queryName) { string sqlQuery = resourceManager.GetString(queryName); return sqlQuery; } /// <summary> /// Property Name : ModifyData /// Author : Vivek Bhavsar /// Creation Date : 29 Nov 2017 /// Purpose : Save data by using dynamic command /// Revision : By Ranjana Singh on 02nd Dec 2017 : Changed method name from SaveData to ModifyData. /// /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")] public static int ModifyData(string queryName, Dictionary<string, dynamic> ParametersList, bool executeMultipleUpdate = false, int queryType = (int)SqlCommandType.Query) { int returnValue; SqlTransaction sqlTransaction = null; try { GetSQLConnection(); sqlTransaction = sqlConnection.BeginTransaction(IsolationLevel.ReadCommitted); sqlCommand.Transaction = sqlTransaction; sqlCommand.CommandText = GetQuery(queryName); if (ParametersList != null) { if (executeMultipleUpdate) { // Query must accept parameter values in {0} and {1} format. sqlCommand.CommandText = string.Format(sqlCommand.CommandText, ParametersList["UpdateValues"], ParametersList["WhereConditionValue"]); } else { foreach (var Parameter in ParametersList.Keys) { sqlCommand.Parameters.AddWithValue(Parameter.ToString(), ParametersList[Parameter]); } } } returnValue = 0; if (queryType == (int)SqlCommandType.StoreProcedure) { sqlCommand.CommandType = CommandType.StoredProcedure; } returnValue = sqlCommand.ExecuteNonQuery(); sqlTransaction.Commit(); loggerObject.Info(resourceManager.GetString("sqlQuerySuccessful") + sqlCommand.CommandText); return returnValue; } catch (Exception exceptionObject) { loggerObject.Info(resourceManager.GetString("sqlQueryFailed"), exceptionObject); sqlTransaction.Rollback(); return -1; } finally { CloseSQLConnection(); } } /// <summary> /// Property Name : GetData /// Author : Vivek Bhavsar /// Creation Date : 29 Nov 2017 /// Purpose : Get data by using dynamic command /// Revision : By Ranjana Singh on 04th Dec 2017 : Changed return type from default ex to null. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")] public static DataTable GetData(string queryName, Dictionary<string, dynamic> parametersList) { SqlDataAdapter sqlDataAdapter; DataSet dsReturn; try { GetSQLConnection(); sqlCommand.CommandText = GetQuery(queryName); if (parametersList != null) { foreach (var Parameter in parametersList.Keys) { sqlCommand.Parameters.AddWithValue(Parameter.ToString(), parametersList[Parameter]); } } sqlDataAdapter = new SqlDataAdapter(); sqlDataAdapter.SelectCommand = sqlCommand; dsReturn = new DataSet(); sqlDataAdapter.Fill(dsReturn); loggerObject.Info(resourceManager.GetString("sqlQuerySuccessful") + sqlCommand.CommandText); return dsReturn.Tables[0]; } catch (Exception exceptionObject) { loggerObject.Info(resourceManager.GetString("sqlQueryFailed"), exceptionObject); return null; } finally { CloseSQLConnection(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AntlionBehavior : MonoBehaviour { private GameObject antlionCharacter; private GameObject player; private GameObject ground; // for referencing collissions with the ground private bool stalled = false; private bool eating = false; private Animator animator; private float countDownTimer = 0f; private bool gameOver = false; private bool start = false; private float digDepth; private bool digging = false; public float speedX = 5.0f; public float digSpeedX = 10.0f; public float digSpeedY = 10.0f; public float eatingTime = 2f; void Start () { antlionCharacter = transform.GetChild (0).gameObject; initializePositionAntlionCharacter (); player = GameObject.Find ("Player").GetComponent<Transform> ().gameObject; digDepth = player.GetComponent<PlayerController> ().getDigDepth (); ground = GameObject.Find ("Ground").GetComponent<Transform>().gameObject; initializeIgnoreColliders (); animator = antlionCharacter.GetComponent<Animator> (); animator.speed = 1; } void Update () { if (start) { if (player.GetComponent<PlayerController> ().allAntsEaten ()) { gameOver = true; } Vector3 playerLastAnt = Vector3.zero; if (!stalled && !eating && !gameOver) { playerLastAnt = player.GetComponent<PlayerController> ().getLastAntPosition (); if (player.GetComponent<PlayerController> ().lastAntDigging ()) { if (digging == false) { digging = true; antlionCharacterignoreGroundColliders (true); } dig (); } else { if(toSurface()){ digging = false; antlionCharacterignoreGroundColliders (false); } } if (playerLastAnt [0] > transform.position.x) { transform.Translate (new Vector3 (speedX * Time.deltaTime, 0f, 0f)); moveAntlionCharacter (); } } if (countDownTimer > 0 && !gameOver) { countDownTimer = countDownTimer - Time.deltaTime; } else { stalled = false; eating = false; animator.Play ("Antlion_Run"); } } } private void moveAntlionCharacter() { float bufferSpace = 0.2f; if (antlionCharacter.transform.position.x <= transform.position.x - bufferSpace) { antlionCharacter.transform.Translate (new Vector3 (speedX * Time.deltaTime, 0f, 0f)); } else if (antlionCharacter.transform.position.x >= transform.position.x + bufferSpace) { antlionCharacter.transform.Translate (new Vector3 (-speedX * Time.deltaTime, 0f, 0f)); } } private bool toSurface() { if (antlionCharacter.transform.position.y < transform.position.y) { antlionCharacter.transform.Translate (new Vector3 (0f, digSpeedY * Time.deltaTime, 0f)); return false; } return true; } private void dig() { float maxDepth = transform.position.y - digDepth; float moveY = 0f; if (antlionCharacter.transform.position.y > maxDepth) { moveY = -digSpeedY * Time.deltaTime; antlionCharacter.transform.Translate (0f, moveY, 0f); } else { antlionCharacter.transform.position = new Vector3 (antlionCharacter.transform.position.x, maxDepth, antlionCharacter.transform.position.z); } } private void antlionCharacterignoreGroundColliders (bool ignore) { Collider2D[] groundColliders = ground.GetComponentsInChildren<Collider2D> (); for (int i = 0; i < groundColliders.Length; i++) { Physics2D.IgnoreCollision (antlionCharacter.GetComponent<Collider2D> (), groundColliders [i], ignore); } Rigidbody2D rb = antlionCharacter.GetComponent<Rigidbody2D> (); if (ignore) { rb.gravityScale = 0f; rb.freezeRotation = true; } else { rb.gravityScale = 1f; rb.freezeRotation = false; } } private void initializeIgnoreColliders () { Collider2D coll = GetComponent<Collider2D> (); Collider2D collAntlion = antlionCharacter.GetComponent<Collider2D> (); Physics2D.IgnoreCollision (collAntlion, coll, true); GameObject[] allGameObjects = UnityEngine.Object.FindObjectsOfType<GameObject> (); for (int i = 0; i< allGameObjects.Length; i++) { // disable collisions for parent colllider if (allGameObjects[i].activeInHierarchy) { Physics2D.IgnoreCollision (coll, allGameObjects[i].GetComponent<Collider2D> (), true); } // disable collision for antlion character collider if (allGameObjects[i].activeInHierarchy && (allGameObjects[i].name.Contains("Ant Hill") || !allGameObjects[i].name.Contains("Ant"))) { Physics2D.IgnoreCollision (collAntlion, allGameObjects[i].GetComponent<Collider2D>(), true); } } Collider2D[] groundColliders = ground.GetComponentsInChildren<Collider2D> (); for (int i = 0; i < groundColliders.Length; i++) { Physics2D.IgnoreCollision (coll, groundColliders [i], false); Physics2D.IgnoreCollision (collAntlion, groundColliders [i], false); } } public bool isGameOver() { return gameOver; } public void setEating(bool isEating) { animator.Play ("Antlion_Eat"); eating = isEating; countDownTimer = eatingTime; } public void setStalled(bool isStalled) { animator.Play ("Antlion_Stunned"); stalled = isStalled; countDownTimer = eatingTime; } public bool isEating() { return eating; } public bool isStalled() { return stalled; } public void enableAntlionCharacterCollider(GameObject thrownObject) { Collider2D antlionColl = antlionCharacter.GetComponent<Collider2D> (); Physics2D.IgnoreCollision (antlionColl, thrownObject.GetComponent<Collider2D>(), false); } public void disableAntlionCharacterCollider(GameObject thrownObject) { Collider2D antlionColl = antlionCharacter.GetComponent<Collider2D> (); Physics2D.IgnoreCollision (antlionColl, thrownObject.GetComponent<Collider2D>(), true); } private void initializePositionAntlionCharacter() { antlionCharacter.transform.position = transform.position; } public void startMovement() { start = true; } public void stopMovement() { start = false; if (player.GetComponent<PlayerController> ().allAntsEaten ()) { stopAnimations (); } else { animator.Play ("Antlion_Dead"); } } private void stopAnimations () { antlionCharacter.GetComponent<Animator> ().Stop (); } private void startAnimations () { //antlionCharacter.GetComponent<Animator> ().Play ("RUN"); } }
using Crt.HttpClients.Models; using Crt.Model.Utils; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using GJFeature = GeoJSON.Net.Feature; // use an alias since Feature exists in HttpClients.Models using NTSGeometry = NetTopologySuite.Geometries; using NetTopologySuite.Geometries.Utilities; using NetTopologySuite.Operation.Polygonize; namespace Crt.HttpClients { public interface IGeoServerApi { //Task<double> GetTotalSegmentLength(string lineString); Task<double> GetTotalSegmentLength(NTSGeometry.Geometry geometry); Task<(double totalLength, double clippedLength)> GetSegmentLengthWithinPolygon(string lineString, string polygonLineString); Task<string> GetProjectExtent(decimal projectId); Task<List<PolygonLayer>> GetPolygonOfInterestForServiceArea(string boundingBox); Task<List<PolygonLayer>> GetPolygonOfInterestForDistrict(string boundingBox); Task<List<PolygonLayer>> GetHighwaysOfInterest(string boundingBox); HttpClient Client { get; } public string Path { get; } } public class GeoServerApi : IGeoServerApi { public HttpClient Client { get; private set; } public string Path { get; private set; } private Queries _queries; private IApi _api; private ILogger<IGeoServerApi> _logger; //the default polyXY is in the ocean and is only used when retrieving // the full length of a segment, that way it doesn't get clipped private const string DEFAULT_POLYXY = "-140.58\\,47.033"; private const string DEFAULT_SRID = "4326"; public GeoServerApi(HttpClient client, IApi api, IConfiguration config, ILogger<IGeoServerApi> logger) { Client = client; _queries = new Queries(); _api = api; var env = config.GetEnvironment(); Path = config.GetValue<string>($"GeoServer{env}:Path"); _logger = logger; } public async Task<double> GetTotalSegmentLength(NTSGeometry.Geometry geometry) //public async Task<double> GetTotalSegmentLength(string lineString) { double totalLength = 0; //var lineStringCoordinates = SpatialUtils.BuildGeometryString(geometry.Coordinates); var geometryGroup = SpatialUtils.BuildGeometryStringList(geometry.Coordinates); foreach (var lineStringCoordinates in geometryGroup) { var body = string.Format(_queries.LineWithinPolygonQuery, DEFAULT_SRID, lineStringCoordinates, DEFAULT_SRID, DEFAULT_POLYXY); var content = await (await _api.PostWithRetry(Client, Path, body)).Content.ReadAsStringAsync(); var featureCollection = SpatialUtils.ParseJSONToFeatureCollection(content); if (featureCollection != null) { foreach (GJFeature.Feature feature in featureCollection.Features) { totalLength += Convert.ToDouble(feature.Properties["COMPLETE_LENGTH_KM"]); } } } return totalLength; } public async Task<(double totalLength, double clippedLength)> GetSegmentLengthWithinPolygon(string lineString, string polygonLineString) { double length = 0, clippedLength = 0; var body = string.Format(_queries.LineWithinPolygonQuery, DEFAULT_SRID, lineString, DEFAULT_SRID, polygonLineString); var content = await (await _api.PostWithRetry(Client, Path, body)).Content.ReadAsStringAsync(); var featureCollection = SpatialUtils.ParseJSONToFeatureCollection(content); if (featureCollection != null) { foreach (GJFeature.Feature feature in featureCollection.Features) { length += Convert.ToDouble(feature.Properties["COMPLETE_LENGTH_KM"]); clippedLength += Convert.ToDouble(feature.Properties["CLIPPED_LENGTH_KM"]); } } return (length, clippedLength); } public async Task<string> GetProjectExtent(decimal projectId) { var query = ""; var content = ""; try { query = Path + string.Format(_queries.BoundingBoxForProject, projectId); content = await (await _api.GetWithRetry(Client, query)).Content.ReadAsStringAsync(); var featureCollection = SpatialUtils.ParseJSONToFeatureCollection(content); return (featureCollection != null) ? string.Join(",", featureCollection.BoundingBoxes) : null; } catch (System.Exception ex) { _logger.LogError($"Exception: {ex.Message} - GetProjectExtent({projectId}): {query} - {content}"); throw; } } public async Task<List<PolygonLayer>> GetHighwaysOfInterest(string boundingBox) { List<PolygonLayer> layerLines = new List<PolygonLayer>(); var query = ""; var content = ""; try { //build the query and get the geoJSON return query = Path + string.Format(_queries.HighwayFeatures, "cwr:V_NM_NLT_DSA_GDSA_SDO_DT", boundingBox); content = await (await _api.GetWithRetry(Client, query)).Content.ReadAsStringAsync(); var featureCollection = SpatialUtils.ParseJSONToFeatureCollection(content); //continue if we have a feature collection if (featureCollection != null) { foreach (GJFeature.Feature feature in featureCollection.Features) { NTSGeometry.Geometry geometry = null; if (feature.Geometry.Type == GeoJSON.Net.GeoJSONObjectType.MultiLineString) { geometry = SpatialUtils.GenerateMultiLineString(feature, boundingBox); } else if (feature.Geometry.Type == GeoJSON.Net.GeoJSONObjectType.LineString) { geometry = SpatialUtils.GenerateLineString(feature, boundingBox); } if (!geometry.IsEmpty) { layerLines.Add(new PolygonLayer { NTSGeometry = geometry, Name = (string)feature.Properties["NE_UNIQUE"], Number = feature.Properties["HIGHWAY_NUMBER"].ToString() }); } } } return layerLines; } catch (System.Exception ex) { _logger.LogError($"Exception {ex.Message} - GetHighwaysOfInterest({boundingBox}): {query} - {content}"); throw; } } public async Task<List<PolygonLayer>> GetPolygonOfInterestForServiceArea(string boundingBox) { List<PolygonLayer> layerPolygons = new List<PolygonLayer>(); var query = ""; var content = ""; try { //build the query and get the geoJSON return query = Path + string.Format(_queries.PolygonOfInterest, "hwy:DSA_CONTRACT_AREA", boundingBox); content = await (await _api.GetWithRetry(Client, query)).Content.ReadAsStringAsync(); var featureCollection = SpatialUtils.ParseJSONToFeatureCollection(content); //continue if we have a feature collection if (featureCollection != null) { //iterate the features in the parsed geoJSON collection foreach (GJFeature.Feature feature in featureCollection.Features) { var simplifiedGeom = SpatialUtils.GenerateNTSPolygonGeometery(feature); layerPolygons.Add(new PolygonLayer { NTSGeometry = simplifiedGeom, Name = (string)feature.Properties["CONTRACT_AREA_NAME"], Number = feature.Properties["CONTRACT_AREA_NUMBER"].ToString() }); } } return layerPolygons; } catch (System.Exception ex) { _logger.LogError($"Exception {ex.Message} - GetPolygonOfInterestForServiceArea({boundingBox}): {query} - {content}"); throw; } } public async Task<List<PolygonLayer>> GetPolygonOfInterestForDistrict(string boundingBox) { List<PolygonLayer> layerPolygons = new List<PolygonLayer>(); var query = ""; var content = ""; try { //build the query and get the geoJSON return query = Path + string.Format(_queries.PolygonOfInterest, "hwy:DSA_DISTRICT_BOUNDARY", boundingBox); content = await (await _api.GetWithRetry(Client, query)).Content.ReadAsStringAsync(); var featureCollection = SpatialUtils.ParseJSONToFeatureCollection(content); //continue if we have a feature collection if (featureCollection != null) { foreach (GJFeature.Feature feature in featureCollection.Features) { var simplifiedGeom = SpatialUtils.GenerateNTSPolygonGeometery(feature); layerPolygons.Add(new PolygonLayer { NTSGeometry = simplifiedGeom, Name = (string)feature.Properties["DISTRICT_NAME"], Number = feature.Properties["DISTRICT_NUMBER"].ToString() }); } } return layerPolygons; } catch (System.Exception ex) { _logger.LogError($"Exception {ex.Message} - GetPolygonOfInterestForDistrict({boundingBox}): {query} - {content}"); throw; } } } }
namespace E23_SeriesOfLetters { using System; using System.Text.RegularExpressions; public class SeriesOfLetters { public static void Main(string[] args) { // Write a program that reads a string from the console and // replaces all series of consecutive identical letters // with a single one. // Example: // input: // aaaaabbbbbcdddeeeeffggh // output: // abcdefgh string text = "aaaaabbbbbcdddeeeeffggh"; Console.WriteLine(text); var pattern = @"(\w)\1+"; var replacement = "$1"; Console.WriteLine("Result:"); Console.WriteLine(Regex.Replace(text, pattern, replacement)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StaticSpikes : MonoBehaviour { [SerializeField] AudioManager SFX = null; [SerializeField] float thrust = 0; [SerializeField] bool onGround = false, onRoof = false; private void OnTriggerEnter2D(Collider2D collision) { collision.GetComponent<Rigidbody2D>().velocity = Vector2.zero; if (collision.gameObject.tag == "Player") { SFX.Play("SP_Damage"); collision.GetComponent<PlayerController2D>().TakeDamage(10); if(onGround) { collision.GetComponent<Rigidbody2D>().velocity = (new Vector2(0, thrust)); } else if(onRoof) { collision.GetComponent<Rigidbody2D>().velocity = (new Vector2(0, -thrust)); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileIndexer { class Program { static void Main(string[] args) { Indexer.GenerateFile(new Megabyte(1000)); Indexer.GenerateIndexFile(); var index = Indexer.CreateDictionaryFromIndex(); var lineCount = Indexer.CountLines(); Console.WriteLine($"Line count: {lineCount}"); CompareSearchTime(index, 5); CompareSearchTime(index, 500); CompareSearchTime(index, 50000); CompareSearchTime(index, 250000); CompareSearchTime(index, lineCount / 8); CompareSearchTime(index, lineCount / 4); CompareSearchTime(index, lineCount / 2); CompareSearchTime(index, lineCount); Console.Read(); } private static void CompareSearchTime(IDictionary<long, long> index, long lineNumber) { Console.WriteLine($"Line number: {lineNumber}"); var sw = new Stopwatch(); sw.Start(); var line = Indexer.GetLineByLinearSearch(lineNumber); sw.Stop(); Console.WriteLine(line); Console.WriteLine($"Linear time(ms): {sw.ElapsedMilliseconds}"); sw.Reset(); sw.Start(); line = Indexer.GetLineByDictionaryLookup(index, lineNumber); sw.Stop(); Console.WriteLine(line); Console.WriteLine($"Lookup time(ms): {sw.ElapsedMilliseconds}"); Console.WriteLine(); Console.WriteLine(); } } }
namespace AllSongsXmlReader { using System; using System.Xml; class ExtractAllSongs { static void Main() { Console.WriteLine("List of all songs from Catalogue: {0}{1}", Environment.NewLine, new string('-',42)); using (XmlReader reader = XmlReader.Create("../../../Lib/xml/catalogue.xml")) { while (reader.Read()) { if(reader.NodeType == XmlNodeType.Element && reader.Name == "title") { Console.WriteLine(reader.ReadElementString()); } } } } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; using Org.BouncyCastle.Math; using Org.BouncyCastle.Crypto.Parameters; using commercio.sdk; using commercio.sacco.lib; using sdk_test.TestResources; namespace commercio.sdk_test { [TestClass] public class RSAKeyParser_test { [TestMethod] public void TestParsingKeys() { String RSAPublicText = TestResources.RSAPublicText; // Test the parsing RsaKeyParameters pubKey = RSAKeyParser.parsePublicKeyFromPem(RSAPublicText); // Here to make debug simpler... BigInteger modulus = pubKey.Modulus; BigInteger exp = pubKey.Exponent; BigInteger testModulus = new BigInteger(HexEncDec.StringToByteArray(TestResources.EncodedHexPubModulus)); BigInteger testExp = new BigInteger(TestResources.PubExponentTextValue.ToString()); // Check the RSA Assert.IsTrue(modulus.CompareTo(testModulus) == 0); Assert.IsTrue(exp.CompareTo(testExp) == 0); } } }
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Configs; using StructLinq; using System; using System.Linq; using System.Threading.Tasks; namespace NetFabric.Hyperlinq.Benchmarks { [GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] [CategoriesColumn] public class SkipTakeBenchmarks : RandomSkipBenchmarksBase { [BenchmarkCategory("Array")] [Benchmark(Baseline = true)] public int Linq_Array() { var sum = 0; foreach (var item in Enumerable.Skip(array, Skip).Take(Count)) sum += item; return sum; } [BenchmarkCategory("Enumerable_Value")] [Benchmark(Baseline = true)] public int Linq_Enumerable_Value() { var sum = 0; foreach (var item in Enumerable.Skip(enumerableValue, Skip).Take(Count)) sum += item; return sum; } [BenchmarkCategory("Collection_Value")] [Benchmark(Baseline = true)] public int Linq_Collection_Value() { var sum = 0; foreach (var item in Enumerable.Skip(collectionValue, Skip).Take(Count)) sum += item; return sum; } [BenchmarkCategory("List_Value")] [Benchmark(Baseline = true)] public int Linq_List_Value() { var sum = 0; foreach (var item in Enumerable.Skip(listValue, Skip).Take(Count)) sum += item; return sum; } [BenchmarkCategory("AsyncEnumerable_Value")] [Benchmark(Baseline = true)] public async Task<int> Linq_AsyncEnumerable_Value() { var sum = 0; await foreach (var item in AsyncEnumerable.Skip(asyncEnumerableValue, Skip).Take(Count)) sum += item; return sum; } [BenchmarkCategory("Enumerable_Reference")] [Benchmark(Baseline = true)] public int Linq_Enumerable_Reference() { var sum = 0; foreach (var item in Enumerable.Skip(enumerableReference, Skip).Take(Count)) sum += item; return sum; } [BenchmarkCategory("Collection_Reference")] [Benchmark(Baseline = true)] public int Linq_Collection_Reference() { var sum = 0; foreach (var item in Enumerable.Skip(collectionReference, Skip).Take(Count)) sum += item; return sum; } [BenchmarkCategory("List_Reference")] [Benchmark(Baseline = true)] public int Linq_List_Reference() { var sum = 0; foreach (var item in Enumerable.Skip(listReference, Skip).Take(Count)) sum += item; return sum; } [BenchmarkCategory("AsyncEnumerable_Reference")] [Benchmark(Baseline = true)] public async Task<int> Linq_AsyncEnumerable_Reference() { var sum = 0; await foreach (var item in AsyncEnumerable.Skip(asyncEnumerableReference, Skip).Take(Count)) sum += item; return sum; } // ------------------- [BenchmarkCategory("Array")] [Benchmark] public int StructLinq_Array() { var sum = 0; foreach (var item in array.ToStructEnumerable().Skip(Skip, x => x).Take(Count, x => x)) sum += item; return sum; } [BenchmarkCategory("Enumerable_Value")] [Benchmark] public int StructLinq_Enumerable_Value() { var sum = 0; foreach (var item in enumerableValue.ToStructEnumerable().Skip(Skip, x => x).Take(Count, x => x)) sum += item; return sum; } [BenchmarkCategory("Collection_Value")] [Benchmark] public int StructLinq_Collection_Value() { var sum = 0; foreach (var item in collectionValue.ToStructEnumerable().Skip(Skip, x => x).Take(Count, x => x)) sum += item; return sum; } [BenchmarkCategory("List_Value")] [Benchmark] public int StructLinq_List_Value() { var sum = 0; foreach (var item in listValue.ToStructEnumerable().Skip(Skip, x => x).Take(Count, x => x)) sum += item; return sum; } [BenchmarkCategory("Enumerable_Reference")] [Benchmark] public int StructLinq_Enumerable_Reference() { var sum = 0; foreach (var item in enumerableReference.ToStructEnumerable().Skip(Skip, x => x).Take(Count, x => x)) sum += item; return sum; } [BenchmarkCategory("Collection_Reference")] [Benchmark] public int StructLinq_Collection_Reference() { var sum = 0; foreach (var item in collectionReference.ToStructEnumerable().Skip(Skip, x => x).Take(Count, x => x)) sum += item; return sum; } [BenchmarkCategory("List_Reference")] [Benchmark] public int StructLinq_List_Reference() { var sum = 0; foreach (var item in listReference.ToStructEnumerable().Skip(Skip, x => x).Take(Count, x => x)) sum += item; return sum; } // ------------------- [BenchmarkCategory("Array")] [Benchmark] public int Hyperlinq_Array_For() { var source = array.AsValueEnumerable().Skip(Skip).Take(Count).Array; var sum = 0; for (var index = 0; index < Count; index++) sum += source[index]; return sum; } #pragma warning disable HLQ010 // Consider using a 'for' loop instead. [BenchmarkCategory("Array")] [Benchmark] public int Hyperlinq_Array_Foreach() { var sum = 0; foreach (var item in array.Skip(Skip).Take(Count)) sum += item; return sum; } #pragma warning restore HLQ010 // Consider using a 'for' loop instead. [BenchmarkCategory("Array")] [Benchmark] public int Hyperlinq_Span_For() { var source = array.AsSpan().Skip(Skip).Take(Count); var sum = 0; for (var index = 0; index < Count; index++) sum += source[index]; return sum; } #pragma warning disable HLQ010 // Consider using a 'for' loop instead. [BenchmarkCategory("Array")] [Benchmark] public int Hyperlinq_Span_Foreach() { var sum = 0; foreach (var item in array.AsSpan().Skip(Skip).Take(Count)) sum += item; return sum; } #pragma warning restore HLQ010 // Consider using a 'for' loop instead. [BenchmarkCategory("Array")] [Benchmark] public int Hyperlinq_Memory_For() { var source = memory.Skip(Skip).Take(Count).Span; var sum = 0; for (var index = 0; index < Count; index++) sum += source[index]; return sum; } #pragma warning disable HLQ010 // Consider using a 'for' loop instead. [BenchmarkCategory("Array")] [Benchmark] public int Hyperlinq_Memory_Foreach() { var sum = 0; foreach (var item in memory.Skip(Skip).Take(Count).Span) sum += item; return sum; } #pragma warning restore HLQ010 // Consider using a 'for' loop instead. [BenchmarkCategory("Enumerable_Value")] [Benchmark] public int Hyperlinq_Enumerable_Value() { var sum = 0; foreach (var item in EnumerableExtensions.AsValueEnumerable<TestEnumerable.Enumerable, TestEnumerable.Enumerable.Enumerator, int>(enumerableValue, enumerable => enumerable.GetEnumerator()) .Skip(Skip) .Take(Count)) sum += item; return sum; } [BenchmarkCategory("Collection_Value")] [Benchmark] public int Hyperlinq_Collection_Value() { var sum = 0; foreach (var item in ReadOnlyCollectionExtensions.AsValueEnumerable<TestCollection.Enumerable, TestCollection.Enumerable.Enumerator, int>(collectionValue, enumerable => enumerable.GetEnumerator()) .Skip(Skip) .Take(Count)) sum += item; return sum; } [BenchmarkCategory("List_Value")] [Benchmark] public int Hyperlinq_List_Value_For() { var source = listValue.AsValueEnumerable().Skip(Skip).Take(Count); var sum = 0; for (var index = 0; index < Count; index++) { var item = source[index]; sum += item; } return sum; } [BenchmarkCategory("List_Value")] [Benchmark] public int Hyperlinq_List_Value_Foreach() { var sum = 0; foreach (var item in listValue.AsValueEnumerable().Skip(Skip).Take(Count)) sum += item; return sum; } [BenchmarkCategory("AsyncEnumerable_Value")] [Benchmark] public async Task<int> Hyperlinq_AsyncEnumerable_Value() { var sum = 0; await foreach (var item in asyncEnumerableValue.AsAsyncValueEnumerable<TestAsyncEnumerable.Enumerable, TestAsyncEnumerable.Enumerable.Enumerator, int>((enumerable, cancellationToken) => enumerable.GetAsyncEnumerator(cancellationToken)) .Skip(Skip) .Take(Count)) sum += item; return sum; } [BenchmarkCategory("Enumerable_Reference")] [Benchmark] public int Hyperlinq_Enumerable_Reference() { var sum = 0; foreach (var item in enumerableReference.AsValueEnumerable().Skip(Skip).Take(Count)) sum += item; return sum; } [BenchmarkCategory("Collection_Reference")] [Benchmark] public int Hyperlinq_Collection_Reference() { var sum = 0; foreach (var item in collectionReference.AsValueEnumerable().Skip(Skip).Take(Count)) sum += item; return sum; } [BenchmarkCategory("List_Reference")] [Benchmark] public int Hyperlinq_List_Reference_For() { var source = listReference.AsValueEnumerable().Skip(Skip).Take(Count); var sum = 0; for (var index = 0; index < Count; index++) sum += source[index]; return sum; } #pragma warning disable HLQ010 // Consider using a 'for' loop instead. [BenchmarkCategory("List_Reference")] [Benchmark] public int Hyperlinq_List_Reference_Foreach() { var sum = 0; foreach (var item in listReference.AsValueEnumerable().Skip(Skip).Take(Count)) sum += item; return sum; } #pragma warning restore HLQ010 // Consider using a 'for' loop instead. [BenchmarkCategory("AsyncEnumerable_Reference")] [Benchmark] public async Task<int> Hyperlinq_AsyncEnumerable_Reference() { var sum = 0; await foreach (var item in asyncEnumerableReference.AsAsyncValueEnumerable() .Skip(Skip) .Take(Count)) sum += item; return sum; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; 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.Shapes; namespace BPiaoBao.Client.DomesticTicket.View { /// <summary> /// ChoosePassengersWindow.xaml 的交互逻辑 /// </summary> public partial class ChoosePassengersWindow : Window { public ChoosePassengersWindow() { InitializeComponent(); } public ChoosePassengersWindow(int flag) { InitializeComponent(); switch (flag) { case 0: dg.Columns[1].Visibility = Visibility.Visible; break; case 1: dg.Columns[1].Visibility = Visibility.Collapsed; break; default: break; } } } }
namespace OmniGui.VisualStates { using System; public class VisualStateGroup { public VisualStateGroup() { StateTriggers = new TriggerCollection(); StateTriggers.IsActive.Subscribe(ToggleSetters); Setters = new SetterCollection(); } private void ToggleSetters(bool shouldActivate) { foreach (var setter in Setters) { setter.Apply(); } } public TriggerCollection StateTriggers { get; } public SetterCollection Setters { get; set; } } }
using System; namespace OmniSharp.Extensions.JsonRpc { public class InterimJsonRpcServerRegistry<T> : JsonRpcCommonMethodsBase<T> where T : IJsonRpcHandlerRegistry<T> { private readonly IHandlersManager _handlersManager; public InterimJsonRpcServerRegistry(IHandlersManager handlersManager) => _handlersManager = handlersManager; public sealed override T AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions? options = null) { _handlersManager.Add(method, handler, options); return (T) (object) this; } public sealed override T AddHandler(string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions? options = null) { _handlersManager.Add(method, handlerFunc, options); return (T) (object) this; } public sealed override T AddHandler(JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions? options = null) { _handlersManager.Add(handlerFunc, options); return (T) (object) this; } public sealed override T AddHandlers(params IJsonRpcHandler[] handlers) { foreach (var handler in handlers) { _handlersManager.Add(handler); } return (T) (object) this; } public sealed override T AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptions? options = null) { _handlersManager.Add(handler, options); return (T) (object) this; } public sealed override T AddHandler<THandler>(JsonRpcHandlerOptions? options = null) => AddHandler(typeof(THandler), options); public sealed override T AddHandler<THandler>(string method, JsonRpcHandlerOptions? options = null) => AddHandler(method, typeof(THandler), options); public sealed override T AddHandler(Type type, JsonRpcHandlerOptions? options = null) { _handlersManager.Add(type, options); return (T) (object) this; } public sealed override T AddHandler(string method, Type type, JsonRpcHandlerOptions? options = null) { _handlersManager.Add(method, type, options); return (T) (object) this; } public sealed override T AddHandlerLink(string fromMethod, string toMethod) { _handlersManager.AddLink(fromMethod, toMethod); return (T) (object) this; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Trettim.Settings; using Trettim.Sicredi.DocumentLibrary.Services; namespace Trettim.Sicredi.DocumentLibrary { public partial class download : PageBase { protected void Page_Load(object sender, EventArgs e) { //Response.ForceDownload(Param.SiteURL + Param.DocumentLibrary.Replace("~","") + base.GetString("FileName"), base.GetString("FileName")); Response.ForceDownload(Param.DocumentLibrary + base.GetString("FileName"), base.GetString("FileName")); } } }
using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SkillsGardenApi.Services; using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; namespace SkillsGardenApi.Security { public class BearerAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions> { private ITokenService TokenService { get; } public BearerAuthenticationHandler(ITokenService TokenService, IOptionsMonitor<AuthenticationSchemeOptions> Options, ILoggerFactory LoggerFactory, UrlEncoder Encoder, ISystemClock Clock) : base(Options, LoggerFactory, Encoder, Clock) { this.TokenService = TokenService; } protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { string TokenString = GetTokenString(); try { ClaimsPrincipal Principal = await TokenService.GetByValue(TokenString); AuthenticationTicket Ticket = new AuthenticationTicket(Principal, Scheme.Name); return AuthenticateResult.Success(Ticket); } catch { return AuthenticateResult.Fail("Missing Authorization Header"); } } private string GetTokenString() { string AuthorizationHeader = Request.Headers["Authorization"]; if (AuthorizationHeader != null) { if (AuthorizationHeader.StartsWith("Bearer ")) { return AuthorizationHeader.Substring(7); } else return null; } else return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; /// /// Naam: Dhr. Gillade /// Datum: 28/09/2020 /// Project: Oefeningen hoofdstuk 14 /// namespace _5NIT_ConsApp_Oefeningenhfd14 { class Program { static void Main(string[] args) { #region Voorbeeld omgevingsvariabelen /// /// Voorbeeld omgevingsvariabelen /// Console.WriteLine("Voorbeeld omgevingsvariabelen\n-----------------------------"); bool is64bit = Environment.Is64BitOperatingSystem; string pcname = Environment.MachineName; int processorCount = Environment.ProcessorCount; string userName = Environment.UserName; Int64 memory = Environment.WorkingSet; Console.WriteLine($"Deze computer bevat een 64-bit OS: {is64bit}"); Console.WriteLine($"De computernaam is: {pcname}"); Console.WriteLine($"Onze computer telt {processorCount} processoren."); Console.WriteLine($"De gebruiker die nu aangemeld is: {userName}"); Console.WriteLine($"Onze computer beschikt over {memory} geheugen."); Console.ReadKey(); Console.Clear(); #endregion #region Oefening 14.1 /// /// Oefening 14.1 /// Console.WriteLine("Oefening 14.1\n-------------"); Double prijsBenzine, reisKost, afgelegdeAfstand; const Double verbruikAuto = 0.06; Console.Write("Wat is de huidige prijs voor 1L benzine? "); prijsBenzine = Convert.ToDouble(Console.ReadLine()); Console.Write("Hoeveel km reis je? "); afgelegdeAfstand = Convert.ToDouble(Console.ReadLine()); reisKost = afgelegdeAfstand * prijsBenzine * verbruikAuto; Console.WriteLine($"Jouw reis kost {reisKost} EURO."); Console.ReadKey(); Console.Clear(); #endregion #region Oefening 14.2 /// /// Oefening 14.2 /// Console.WriteLine("Oefening 14.2\n-------------"); const Double btwTarief = 1.21; Double bedragExclBTW, bedragInclBTW; Console.Write("Hoeveel bedraagt de prijs exclusief BTW? "); bedragExclBTW = Convert.ToDouble(Console.ReadLine()); bedragInclBTW = bedragExclBTW * btwTarief; Console.WriteLine($"Het bedrag inclusief BTW is: {bedragInclBTW}"); Console.ReadKey(); Console.Clear(); #endregion #region Oefening 14.3 /// /// Oefening 14.3 /// Console.WriteLine("Oefening 14.3\n-------------"); Int16 gewonnen, verloren, gelijk; Int32 punten; Console.Write("Hoeveel wedstrijden heb je gewonnen? "); gewonnen = Convert.ToInt16(Console.ReadLine()); Console.Write("Hoeveel wedstrijden heb je verloren? "); verloren = Convert.ToInt16(Console.ReadLine()); Console.Write("Hoeveel wedstrijden heb je gelijk gespeeld? "); gelijk = Convert.ToInt16(Console.ReadLine()); punten = gewonnen * 3 + gelijk; Console.WriteLine($"Jouw ploeg behaalde {punten} punten."); Console.ReadKey(); Console.Clear(); #endregion #region Oefening 14.4 /// /// Oefening 14.4 /// Console.WriteLine("Oefening 14.4\n-------------"); String ingegevenWoord, omgedraaidWoord; Console.Write("Gelieve een woord in te vullen: "); ingegevenWoord = Console.ReadLine(); omgedraaidWoord = ""; omgedraaidWoord += ingegevenWoord.Substring(ingegevenWoord.Length - 1, 1); omgedraaidWoord += "_"; omgedraaidWoord += ingegevenWoord.Substring(0,1); Console.WriteLine($"Jouw woord telt {ingegevenWoord.Length} letters;"); Console.WriteLine($"Jouw initialen zijn {omgedraaidWoord}"); Console.ReadKey(); Console.Clear(); #endregion #region Oefening 14.5 /// /// Oefening 14.5 /// Console.WriteLine("Oefening 14.5"); Console.Write("Gelieve een datum in te vullen: "); DateTime ingevoerdeDatum; ingevoerdeDatum = Convert.ToDateTime(Console.ReadLine()); //DateTime ingevoerdeDatum = Convert.ToDateTime(Console.ReadLine()); Console.WriteLine($"De naam van de maand is: {ingevoerdeDatum.ToString("MMMM")}"); Console.ReadKey(); Console.Clear(); #endregion #region Oefening 14.6 /// /// Oefening 14.6 /// Console.WriteLine("Oefening 14.6"); Console.Write("Gelieve een getal in te vullen tussen 1 en 20: "); Int16 ingevoerdGetal = Convert.ToInt16(Console.ReadLine()); Int32 berekendGetal = ingevoerdGetal * 2; Console.WriteLine(berekendGetal); berekendGetal += 6; Console.WriteLine(berekendGetal); berekendGetal /= 2; Console.WriteLine(berekendGetal); berekendGetal -= ingevoerdGetal; Console.WriteLine(berekendGetal); Console.ReadKey(); Console.Clear(); #endregion #region Oefening 14.7 /// /// Oefening 14.7 /// Console.WriteLine("Oefening 14.7\n-------------"); Double TF, TC; Console.Write("Gelieve de temperatuur in graden Celcius in te voeren: "); TC = Convert.ToDouble(Console.ReadLine()); TF = 1.8 * TC + 32; Console.WriteLine($"Temperatuur in °C: {TC} \n Temperatuur in °F: {TF}"); Console.ReadKey(); Console.Clear(); #endregion #region Oefening 14.8 /// /// Oefening 14.8 /// Console.WriteLine("Oefening 14.8"); bool OS64bit = Environment.Is64BitOperatingSystem; string pcnaam = Environment.MachineName; int aantalProcessors = Environment.ProcessorCount; string gebruikersnaam = Environment.UserName; Int64 geheugen = (Environment.WorkingSet/1024)/1024; String OSVersie = Environment.OSVersion.ToString(); String machineNaam = Environment.MachineName; Console.WriteLine($"Deze computer bevat een 64-bit OS: {OS64bit}"); Console.WriteLine($"De computernaam is: {pcnaam}"); Console.WriteLine($"De machinenaam is: {machineNaam}"); Console.WriteLine($"Onze computer telt {aantalProcessors} processoren."); Console.WriteLine($"De gebruiker die nu aangemeld is: {gebruikersnaam}"); Console.WriteLine($"Het huidige proces gebruikt {geheugen} Mb geheugen."); Console.WriteLine($"Onze computer gebruikt versie {OSVersie} als OS."); Console.ReadKey(); Console.Clear(); #endregion #region Oefening 14.9 /// /// Oefening 14.9 /// Console.WriteLine("Oefening 14.9"); Int64 driveInBytes = DriveInfo.GetDrives()[0].AvailableFreeSpace; Int64 totalSize = DriveInfo.GetDrives()[0].TotalSize; String driveName = DriveInfo.GetDrives()[0].Name; Console.WriteLine($"Naam van de schijf: {driveName}"); Console.WriteLine($"Vrije ruimte van de schijf: {driveInBytes}"); Console.WriteLine($"Totale grootte van de schijf: {totalSize}"); Console.ReadKey(); Console.Clear(); #endregion } } }
using System.Windows; using System.Windows.Markup; [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: XmlnsPrefix("https://github.com/Acorisoft/Gensokyo/Components", "components")] [assembly: XmlnsDefinition("https://github.com/Acorisoft/Gensokyo/Components", "Gensokyo.Components.Colors")] [assembly: XmlnsDefinition("https://github.com/Acorisoft/Gensokyo/Components", "Gensokyo.Components.Controls")] [assembly: XmlnsDefinition("https://github.com/Acorisoft/Gensokyo/Components", "Gensokyo.Components.Interactives")] [assembly: XmlnsDefinition("https://github.com/Acorisoft/Gensokyo/Components", "Gensokyo.Components.Windows")]
using LePapeo.Models; using LePapeoGenNHibernate.CAD.LePapeo; using LePapeoGenNHibernate.CEN.LePapeo; using LePapeoGenNHibernate.EN.LePapeo; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WEBLEPAPEO.Controllers { public class NotificacionGenericaController : BasicController { // GET: Registrado public ActionResult Index() { NotificacionGenericaCEN NotificacionGenericaCEN = new NotificacionGenericaCEN(); IList<NotificacionGenericaEN> listNotigeEN = NotificacionGenericaCEN.ReadAll(0, -1); IEnumerable<NotificacionGenericaViewModel> listreg = new AssemblerNotificacionGenerica().ConvertListENToModel(listNotigeEN); return View(listreg); } // GET: Registrado/Details/5 public ActionResult Details(int id) { return View(); } // GET: Registrado/Create public ActionResult Create() { NotificacionGenericaViewModel notige = new NotificacionGenericaViewModel(); return View(notige); } // POST: Registrado/Create [HttpPost] public ActionResult Create(NotificacionGenericaViewModel notige) { try { // TODO: Add insert logic here NotificacionGenericaCEN cen = new NotificacionGenericaCEN(); cen.New_(notige.tipo, notige.texto, notige.nombre); return RedirectToAction("Index"); } catch { return View(); } } // GET: Registrado/Edit/5 public ActionResult Edit(int id) { NotificacionGenericaViewModel notige = null; SessionInitialize(); NotificacionGenericaEN notiEN = new NotificacionGenericaCAD(session).ReadOIDDefault(id); notige = new AssemblerNotificacionGenerica().ConvertENToModelUI(notiEN); SessionClose(); return View(notige); } // POST: Registrado/Edit/5 [HttpPost] public ActionResult Edit(NotificacionGenericaViewModel notige) { try { // TODO: Add update logic here NotificacionGenericaCEN cen = new NotificacionGenericaCEN(); cen.Modify(notige.id, notige.tipo, notige.texto, notige.nombre); return RedirectToAction("Index"); } catch { return View(); } } // GET: Registrado/Delete/5 public ActionResult Delete(int id) { try { SessionInitialize(); NotificacionGenericaCAD notigeCAD = new NotificacionGenericaCAD(session); NotificacionGenericaCEN cen = new NotificacionGenericaCEN(notigeCAD); NotificacionGenericaEN notigeEN = cen.ReadOID(id); NotificacionGenericaViewModel notige = new AssemblerNotificacionGenerica().ConvertENToModelUI(notigeEN); SessionClose(); return View(notige); } catch { //Meter aqui el mensaje de error return View(); } } // POST: Registrado/Delete/5 [HttpPost] public ActionResult Delete(NotificacionGenericaViewModel notige) { try { // TODO: Add delete logic here new NotificacionGenericaCEN().Destroy(notige.id); return RedirectToAction("Index"); } catch { return View(); } } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Whatsdown_Location_Service.Model; namespace Whatsdown_Location_Service.Logic { public class FoxLogic { public async Task<Fox> GetFoxImage() { using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://randomfox.ca/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var result = await client.GetAsync("floof/?ref=apilist.fun"); if (result.IsSuccessStatusCode) { // Read all of the response and deserialise it into an instace of // WeatherForecast class var content = await result.Content.ReadAsStringAsync(); Fox fox = JsonConvert.DeserializeObject<Fox>(content); return fox; } } return null; } } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using PropertyManager.Data; using PropertyManager.Models; using System.Collections.Generic; using System.Linq; using PropertyManager.DTOs; namespace PropertyManager.Controllers { [Route("api/[controller]")] public class PropertyController : ControllerBase { private readonly DBContext _db; public PropertyController(DBContext db) { _db = db; } [HttpGet] public async Task<ActionResult> GetAllProperties() { var properties = await _db.Property.ToListAsync(); return Ok(properties); } [HttpGet("{Id}", Name = "GetPropertyById")] public async Task<ActionResult> GetPropertyById(int Id) { var property = await _db.Property.FirstOrDefaultAsync(x => x.Id == Id); return Ok(new PropertyDTO { Id = property.Id, Description = property.Description, PropertyType = property.PropertyType, ImageUrl = property.ImageUrl, Address = property.Address, IsActive = property.IsActive, CreatedDate = property.CreatedDate, CreatedUser = property.CreatedUser, UpdatedDate = property.UpdatedDate, UpdatedUser = property.UpdatedUser, IsDeleted = property.IsDeleted, Files = _db.Files.Where(x => x.OriginID == property.Id && x.Type == 1).ToList() }); } // POST api/property [HttpPost] public async Task<ActionResult> CreateProperty([FromBody] PropertyDTO modelDTO) { try { var model = new Property() { Description = modelDTO.Description, PropertyType = modelDTO.PropertyType, ImageUrl = modelDTO.ImageUrl, Address = modelDTO.Address }; model.CreatedDate = DateTime.Now; model.UpdatedDate = DateTime.Now; _db.Property.Add(model); modelDTO.Files.ForEach(file => { file.OriginID = modelDTO.Id; file.Type = 1; //[Type 1 indicates property] file.CreatedUser = modelDTO.CreatedUser; file.CreatedDate = modelDTO.CreatedDate; file.UpdatedUser = modelDTO.UpdatedUser; file.UpdatedDate = modelDTO.UpdatedDate; }); var files = modelDTO.Files; _db.Files.AddRange(files); await _db.SaveChangesAsync(); return CreatedAtRoute(nameof(GetPropertyById), new { model.Id }, model); } catch (Exception ex) { return Ok(ex); } } // PUT api/property/{id} [HttpPut("{Id}")] public async Task<ActionResult> UpdateProperty(int Id, [FromBody] PropertyDTO modelDTO) { try { Property prop = await _db.Property.FirstOrDefaultAsync(x => x.Id == Id); if (prop == null) { return NotFound(); } prop.PropertyType = modelDTO.PropertyType; prop.Description = modelDTO.Description; prop.Address = modelDTO.Address; prop.UpdatedUser = modelDTO.UpdatedUser; prop.UpdatedDate = DateTime.Now; _db.Entry(prop).State = EntityState.Modified; byte type = 1; var filesToRemove = _db.Files.Where(x => x.OriginID == Id && x.Type == type).ToList(); if (filesToRemove.Count() > 0) { _db.Files.RemoveRange(filesToRemove); } modelDTO.Files.ForEach(file => { file.OriginID = Id; file.Type = type; //[Type 1 indicates property] // checkout how to bring files file.CreatedUser = modelDTO.CreatedUser; file.CreatedDate = modelDTO.CreatedDate; file.UpdatedUser = modelDTO.UpdatedUser; file.UpdatedDate = modelDTO.UpdatedDate; }); var files = modelDTO.Files; _db.Files.AddRange(files); await _db.SaveChangesAsync(); return NoContent(); } catch (Exception ex) { return Ok(ex); } } } }
/* * Title:"UIFW"项目框架 * 主题:"UIFW"项目帮助脚本 * Descriptions: * 1.查找"对应物体"的子节点 * 2.给子节点添加组件 * 3.从子节点上获取组件 * 4.设置父物体 */ using System.Collections; using System.Collections.Generic; using UnityEngine; namespace UIFW { public class UIFWHelper : MonoBehaviour { /// <summary> /// 查找子节点; /// </summary> /// <param name="traParent"><c>父节点</c></param> /// <param name="childNode"><c>子节点名称</c></param> /// <returns></returns> public static Transform FindTheChildNode(Transform traParent, string childNode) { Transform resultNode = null; resultNode = traParent.Find(childNode); if (resultNode == null) { foreach (Transform item in traParent.transform) { //递归查找 resultNode = FindTheChildNode(traParent, childNode); if (resultNode != null) return resultNode; } } return resultNode; } /// <summary> /// 给子节点添加组件; /// Descriptions: /// 1.先找到子节点; /// 2.如果子节点上有相同组件则先移除,再重新添加; /// </summary> /// <typeparam name="T"><c>类型</c></typeparam> /// <param name="traParent"><c>父节点</c></param> /// <param name="childNode"><c>子节点名称</c></param> /// <returns></returns> public static T AddChildNodeComponent<T>(Transform traParent,string childNode) where T:Component { Transform traChild = null; T result = null; //找到对应的子物体 traChild = FindTheChildNode(traParent, childNode); //先判断身上是否有相同的组件 if (traChild != null) { T[] componentArrary = traChild.GetComponents<T>(); //如果身上有相同的组件,先移除这个组件 if (componentArrary != null) { foreach (T item in componentArrary) { Destroy(item); } //再重新添加组件 result = traChild.gameObject.AddComponent<T>(); } else { result = traChild.gameObject.AddComponent<T>(); } return result; } else { Debug.Log("没有在 物体:" + traParent.ToString() + "下找到子物体 " + childNode.ToString() + " ..."); return null; } } /// <summary> /// 从子物体上获取组件; /// </summary> /// <typeparam name="T"><c>类型</c></typeparam> /// <param name="traParent"><c>父节点</c></param> /// <param name="childNode"><c>子节点名称</c></param> /// <returns></returns> public static T GetComponentFromChildNode<T>(Transform traParent, string childNode) where T : Component { Transform traChild = null; T result = null; //先找到子节点 traChild = FindTheChildNode(traParent, childNode); if (traChild != null) { result = traChild.GetComponent<T>(); if (result == null) { Debug.Log("子物体 :" + childNode.ToString() + " 上没有该组件..."); } return result; } else { Debug.Log("没有在 物体:" + traParent.ToString() + "下找到子物体 " + childNode.ToString() + " ..."); return null; } } /// <summary> /// 给子物体添加父物体 /// </summary> /// <param name="traParent"></param> /// <param name="traChild"></param> public static void AddParent(Transform traParent, Transform traChild) { traChild.SetParent(traParent); traChild.localPosition = Vector3.zero; traChild.localScale = Vector3.one; traChild.localEulerAngles = Vector3.zero; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using CefSharp.WinForms; using MilkBot.Core; using MilkBot.Core.Logging; namespace MilkBot.Forms { public partial class BrowserForm : Form { private const int INTERNET_OPTION_END_BROWSER_SESSION = 42; [DllImport("wininet.dll", SetLastError = true)] private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength); public string Url { get; } public string DomMember { get; } public TextBox LinkedTextbox { get; } public ChromiumWebBrowser Browser { get; } public BrowserForm(string url, bool resetInfo = false, string getInputById = null, TextBox linkedTextBox = null) { Url = url; DomMember = getInputById; LinkedTextbox = linkedTextBox; if (resetInfo) { InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero, 0); } InitializeComponent(); Browser = new ChromiumWebBrowser(url) { Dock = DockStyle.Fill, }; BrowserPanel.Controls.Add(Browser); Browser.FrameLoadEnd += Browser_FrameLoadEnd; } private void Browser_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e) { if (DomMember != null && LinkedTextbox != null) { var frame = e.Frame; var task = frame.EvaluateScriptAsync($"(function() {{return document.getElementById('{DomMember}').value;}})();", null); task.ContinueWith(t => { if (!t.IsFaulted) { var response = t.Result; if (response == null) { Logger.Log<BrowserForm>( Logger.Level.Severe, "BrowserForm.JavascriptResponseNull: The response given by the Evaluate task was null." ); } else if (response.Success) { var result = (string)response.Result; if (!string.IsNullOrEmpty(result)) { Invoke(new MethodInvoker(() => { LinkedTextbox.Text = result; Close(); })); } } else { Logger.Log<BrowserForm>( Logger.Level.Severe, "BrowserForm.JavascriptResponseUnsuccessful: The Evaluate task was unsuccessful." ); } } }); } } private void CloseButton_Click(object sender, EventArgs e) { if (!IsDisposed) { Close(); } } } }