text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Data.Linq; using System.Linq; using System.Text; using System.Threading.Tasks; using DataAccessLayer.basis; namespace Uxnet.Com.DataAccessLayer.Models { public class ModelSource<T, TEntity> : GenericManager<T, TEntity> where T : DataContext, new() where TEntity : class,new() { protected IQueryable<TEntity> _items; protected ModelSourceInquiry<T, TEntity> _inquiry; public ModelSource() : base() { } public ModelSource(GenericManager<T> manager) : base(manager) { } public IQueryable<TEntity> Items { get { if (_items == null) _items = this.EntityList; return _items; } set { _items = value; } } public T GetDataContext() { return (T)this._db; } public void BuildQuery() { if (_inquiry != null) { _inquiry.BuildQueryExpression(this); } } public ModelSourceInquiry<T, TEntity> Inquiry { get { return _inquiry; } set { _inquiry = value; _inquiry.ApplyModelSource(this); } } //private void applyModelSource() //{ // _inquiry.ModelSource = this; //} public String DataSourcePath { get; set; } public bool InquiryHasError { get; set; } } public partial class ModelSourceInquiry<T, TEntity> : ModelSourceInquiry where T : DataContext, new() where TEntity : class,new() { protected List<ModelSourceInquiry<T, TEntity>> _chainedInquiry; public void ApplyModelSource(ModelSource<T, TEntity> models) { this.ModelSource = models; if (_chainedInquiry != null) { foreach (var inquiry in _chainedInquiry) { inquiry.ApplyModelSource(models); } } } public virtual void BuildQueryExpression(ModelSource<T, TEntity> models) { HasError = QueryRequired && !HasSet; if (HasError) { models.Items = models.EntityList.Where(f => false); ModelSource.InquiryHasError = true; } else { if (_chainedInquiry != null) { foreach (var inquiry in _chainedInquiry) { inquiry.BuildQueryExpression(models); } } } } public ModelSourceInquiry<T, TEntity> Append(ModelSourceInquiry<T, TEntity> inquiry) { if (_chainedInquiry == null) { _chainedInquiry = new List<ModelSourceInquiry<T, TEntity>>(); } _chainedInquiry.Add(inquiry); return this; } public ModelSource<T, TEntity> ModelSource { get; set; } } public partial class ModelSourceInquiry { public bool QueryRequired { get; set; } protected bool effective; public bool HasSet { get => effective; protected set => effective = value; } public String AlertMessage { get; set; } public string ActionName { get; set; } public String ControllerName { get; set; } public bool HasError { get; protected set; } public String ViewName { get; set; } public String QueryMessage { get; set; } } }
using LogicBuilder.RulesDirector; namespace Enrollment.Spa.Flow { public interface IFlowActivityFactory { IFlowActivity Create(IFlowManager flowManager); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel.Store; using Windows.UI.Popups; using Windows.UI.Xaml.Controls; using Microsoft.Xaml.Interactions.Core; using Stock_Management.Model.Interface; using Stock_Management.Persistency; using Stock_Management.Viewmodel; namespace Stock_Management.Model { public class ProductCatalogSingleton : IProductCatalogSingleton { //Lazy Loading is initializing the member the first time it is requested. private static ProductCatalogSingleton _instance; public static ProductCatalogSingleton Instance { get { return _instance ?? (_instance = new ProductCatalogSingleton()); } } public ObservableCollection<Product> ProductList { get; set; } public ObservableCollection<Supplier> SupplierList { get; set; } public ObservableCollection<Order> OrderList { get; set; } public ObservableCollection<ProductReturn> ProductReturnList { get; set; } private ProductCatalogSingleton() { SupplierList = new ObservableCollection<Supplier>(); LoadSuppliersAsync(); OrderList = new ObservableCollection<Order>(); LoadOrdersAsync(); ProductReturnList = new ObservableCollection<ProductReturn>(); LoadProductReturnsAsync(); ProductList = new ObservableCollection<Product>(); LoadProductsAsync(); } /// <summary> /// Takes a product (p) as argument /// it checks if the product has a supplier and then it will call a method from PersistencyService /// and add the new product in our database. /// </summary> /// <param name="p">P is the variable we use for our product object</param> public void CreateProduct(Product p) { // Check if product name already exists in the collection if (ProductList.Any(product => product.Name.Equals(p.Name))) throw new ArgumentException("Kan ikke oprette produkt. Produkt med dette navn findes i forvejen"); // Check if product ItemNr already exists in the collection if(ProductList.Any(product => product.ItemNr.Equals(p.ItemNr))) throw new ArgumentException("Kan ikke oprette produkt. Produkt med dette Vare Nr. findes i forvejen"); if (p.Supplier == null) { // Supplier or any of suppliers properties are null throw new ArgumentNullException("Leverandør mangler"); } // Instantiate a Supplier from the Product.Supplier Supplier pSupplier = p.Supplier; if (p.Supplier.Id != 0) { // If the supplier is not 0, that means the Supplier was selected from the dropdownlist // Set the SupplierId on the Product p.SupplierId = p.Supplier.Id; // HACK: Set Supplier to Null again, because the database sends an error // if we pass an entire Supplier with the Product p.Supplier = null; } else { // The supplier id is zero, which means it was typed in and not selected // Check if values are null if (p.Supplier.Name == null || p.Supplier.Address == null || p.Supplier.Phone == null) { throw new ArgumentException("Leverandørens oplysninger mangler at blive udfyldt"); } // should now check if a supplier already exists with that name or create a new one // Check if the Supplier already exists in the list if (SupplierList.Where(s => s.Id.Equals(p.SupplierId)).Count() > 0) //TODO Virker ikke endnu { // Exists in the list update the Supplier instead UpdateSupplier(p.Supplier); } else { // Does not exist in the list, create a new one CreateSupplier(p.Supplier); } } try { // Add to db, returns id if succesful, returns 0 if fail p.Id = PersistencyService.InsertProductAsync(p).Result; } catch (Exception e) { Debug.WriteLine(e); throw; } // Set the Product.Supplier to the instantiated Supplier p.Supplier = pSupplier; // Add to ProductList ProductList.Add(p); } public void DeleteProduct(Product p) { if (p.OrderList != null || p.ProductReturns != null && (p.OrderList.Count > 0 || p.ProductReturns.Count > 0)) { throw new ArgumentException("Kan ikke slette produktet, da det indeholder Ordre/Returns"); } try { // Remove from DB PersistencyService.DeleteProductAsync(p); // Remove from List ProductList.Remove(p); new MessageDialog("Produkt er slettet").ShowAsync(); } catch (Exception e) { Debug.WriteLine(e); throw; } } public void UpdateProduct(Product p) { // Skal bestille hvis under minstock og indenfor periode if (p.Stock <= p.MinStock && p.RestockPeriod >= DateTime.Now) { OrderProduct(p, p.RestockAmount); } // Update product in DB PersistencyService.UpdateProductAsync(p); } public void OrderProduct(Product p, int amount) { // Makes sure you can't order 0 or a negative amount of products if (amount <= 0) { throw new ArgumentException("Du skal bestille mindst èt produkt"); } // Create an order // Sets datetime variable for date and estDelivery. As DateTime can't be null so we set // the property to the same thing. If they are the same, that means estDilevery has not been set DateTime now = DateTime.Now; // EnumStatus: I am using the built in EnumStatus' and do a toString on them as the DB takes a string Order o = new Order(p.Id, p.SupplierId, "På vej", amount, now, now ); // Insert order try { // Add to db, returns id if succesful, returns 0 if fail o.Id = PersistencyService.InsertOrder(o).Result; } catch (Exception e) { Debug.WriteLine(e); } // Set the product supplier on Order o.Supplier = p.Supplier; if (p.OrderList == null) { p.OrderList = new ObservableCollection<Order>(); } p.OrderList.Add(o); } public void ApproveOrder(Product p) { Order o = null; // Gets the top order to approve try { List<Order> orders = p.OrderList.Where(order => order.Approved.Equals(0)).ToList(); o = orders[0]; } catch (Exception e) { Debug.WriteLine(e); } // If order is available, approves it, and updates it through persistency if (o != null) { o.Approved = 1; o.Status = "Godkendt"; //Adds the amount from manual order to the actual order p.Stock += o.Amount; try { UpdateOrder(o); } catch (Exception e) { Debug.WriteLine(e); throw; } } else { throw new NullReferenceException(); } // Update product with the new amount try { UpdateProduct(p); } catch (Exception e) { Debug.WriteLine(e); throw; } } public void UpdateOrder(Order o) { PersistencyService.UpdateOrder(o); } /// <summary> /// Load all Products, and product properties (Supplier, OrderList, ProductReturnList) /// from the DB into the app ProductList /// </summary> public async void LoadProductsAsync() { List<Product> products = null; try { products = await PersistencyService.LoadProductsAsync(); } catch (Exception e) { Debug.WriteLine(e); throw; } if (products != null) { foreach (Product p in products) { // Set the Supplier, Orders, and ProductReturns for the current Product // Product has a required supplier try { // Find the single supplier matching the supplier foreign key on the product p.Supplier = SupplierList.Single(s => s.Id.Equals(p.SupplierId)); } catch (Exception e) { Debug.WriteLine(e); throw; } // Get Orders in the OrderList with a foreign key to the current Product in the foreach List<Order> productOrderList = OrderList.Where(o => o.ProductId.Equals(p.Id)).ToList(); if (productOrderList != null && productOrderList.Count > 0) { p.FillOrderList(productOrderList); } // Get ProductReturns in the prList with a foreign key to the current Product in the foreach List<ProductReturn> prList = ProductReturnList.Where(pr => pr.ProductId.Equals(p.Id)).ToList(); if (prList != null && prList.Count > 0) { p.FillProductReturnList(prList); } // At last, add the product the productList ProductList.Add(p); } } else { throw new ArgumentNullException("Products list null"); } } public async void LoadSuppliersAsync() { List<Supplier> suppliers = null; try { suppliers = await PersistencyService.LoadSuppliersAsync(); } catch (Exception e) { Debug.WriteLine(e); throw; } if (suppliers != null) { foreach (Supplier supplier in suppliers) { SupplierList.Add(supplier); } } else { throw new ArgumentNullException("Suppliers list null"); } } public async void LoadOrdersAsync() { List<Order> orders = null; try { orders = await PersistencyService.LoadOrdersAsync(); } catch (Exception e) { Debug.WriteLine(e); throw; } if (orders != null) { foreach (Order order in orders) { order.Supplier = SupplierList.Single(supplier => supplier.Id.Equals(order.SupplierId)); OrderList.Add(order); } } else { throw new ArgumentNullException("Orders list null"); } } public async void LoadProductReturnsAsync() { List<ProductReturn> productReturns = null; try { productReturns = await PersistencyService.LoadProductReturnsAsync(); } catch (Exception e) { Debug.WriteLine(e); throw; } if (productReturns != null) { foreach (ProductReturn pr in productReturns) { ProductReturnList.Add(pr); } } else { throw new ArgumentNullException("ProductReturns list null"); } } public void CreateSupplier(Supplier s) { try { PersistencyService.InsertSupplier(s); } catch (Exception e) { Debug.WriteLine(e); throw; } } public void UpdateSupplier(Supplier s) { PersistencyService.UpdateSupplier(s); } public void CreateProductReturn(Product p, ProductReturn r) { if (r.Amount < 1) { throw new ArgumentException("Du skal returnere mindst ét produkt"); } if (r.Description == null) { throw new ArgumentException("Beskrivelse skal indtastes"); } if (p.Stock < r.Amount) { throw new ArgumentException("Kan ikke returnere flere end antallet af vare på lager"); } try { PersistencyService.InsertProductReturnAsync(r); } catch (Exception e) { Debug.WriteLine(e); } // Reduce the product stock, as we return those products p.Stock -= r.Amount; // Update product with the new amount try { UpdateProduct(p); } catch (Exception e) { Debug.WriteLine(e); throw; } // Add ReturnProduct to the list of the corresponding product (the ReturnProduct owner) if (p.ProductReturns == null) { p.ProductReturns = new ObservableCollection<ProductReturn>(); } p.ProductReturns.Add(r); } } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game.Mono; [Attribute38("CardSoundData")] public class CardSoundData : MonoClass { public CardSoundData(IntPtr address) : this(address, "CardSoundData") { } public CardSoundData(IntPtr address, string className) : base(address, className) { } public float m_DelaySec { get { return base.method_2<float>("m_DelaySec"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace jumpHelper { public class FormationsGridViewAdapter : BaseAdapter { private List<string> formationList; private Activity context; public FormationsGridViewAdapter(List<string> formationList, Activity context) { this.formationList = formationList; this.context = context; } public override int Count { get { return this.formationList.Count; } } public override Java.Lang.Object GetItem(int position) { return this.formationList[position]; } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) view = context.LayoutInflater.Inflate(Resource.Layout.FormationGridCell, null); view.FindViewById<TextView>(Resource.Id.formationInGrid).Text = this.formationList[position]; return view; } } }
using UnityEngine; using System; using System.Collections.Generic; [Serializable] public class CurveClipData { [Serializable] public enum PropertyType { LocalPosition, Rotation_x, Scale, } [Serializable] public class CurveData { public AnimationCurve[] m_animationCurves; public string m_path; public PropertyType m_propertyType; } public CurveData[] m_curveDatas; public void Sample(GameObject obj, float time) { foreach(var curveData in m_curveDatas) { Transform temp = obj.transform; if (!string.IsNullOrEmpty(curveData.m_path)) { temp = obj.transform.Find(curveData.m_path); } switch (curveData.m_propertyType) { case PropertyType.LocalPosition: var vector3 = new Vector3 { x = curveData.m_animationCurves[0].Evaluate(time), y = curveData.m_animationCurves[1].Evaluate(time), z = curveData.m_animationCurves[2].Evaluate(time) }; temp.localPosition = vector3; break; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using JobCommon; namespace SchedulerService { public static class ConfigFactory { public static ServiceConfig SchedulerConfig = null;//ConfigHelper.LoadConfig<ServiceConfig>(ConfigFileType.SchedulerService_ServiceConfig); public static List<JobConfig> JobList = null;//ConfigHelper.LoadConfig<List<JobConfig>>(ConfigFileType.SchedulerService_JobInfo); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using Random = UnityEngine.Random; // need specify, because Random is contained in both System and UnityEngine public class BoardManager : MonoBehaviour { [Serializable] public class Count { public int min; public int max; public Count(int min, int max) { this.min = min; this.max = max; } } public int cols = 10; public int rows = 10; private Count trapCount = new Count(10, 15); private Count treeCount = new Count(2, 3); public GameObject home; public GameObject[] fogTile; public GameObject trapTile; public GameObject treeTile; public GameObject flowerTile; private Transform boardHolder; //A variable to store a reference to the transform of our Board object. private List<Vector3> gridPositions = new List<Vector3>(); //A list of possible locations to place tiles. private HashSet<int> roadToHome = new HashSet<int>(); void BoardSetup() { boardHolder = new GameObject("Board").transform; int fogIndex = 0; for (int x = 0; x < cols; x++) { for (int y = 0; y < rows; y++) { if (x <= 2 && y <= 1) { continue; } GameObject toInstantiate = fogTile[fogIndex++]; GameObject instance = Instantiate(toInstantiate, new Vector3(x, y, 0), Quaternion.identity); instance.transform.SetParent(boardHolder); } } } //Clears our list gridPositions and prepares it to generate a new board. void InitialiseList(Vector3 homePosition) { gridPositions.Clear(); roadToHome.Clear(); float homeX = homePosition.x; float homeY = homePosition.y; int midX = Random.Range(0, (int)homePosition.x + 1); int midY = Random.Range(0, (int)homePosition.y + 1); int roadDirection = Random.Range(0, 2); // 0 -> up, 1 -> right if (roadDirection == 0) { int startX = Random.Range(0, 3); for (int i = 0; i < midY; i++) { int gridID = 10 * i + startX; roadToHome.Add(gridID); } for (int i = startX; i < midX; i++) { int gridID = 10 * midY + i; roadToHome.Add(gridID); } for (int i = midY; i < homeY; i++) { int gridID = 10 * i + midX; roadToHome.Add(gridID); } for (int i = midX; i < homeX; i++) { int gridID = 10 * (int)homeY + i; roadToHome.Add(gridID); } } else { int startY = Random.Range(0, 2); for (int i = 0; i < midX; i++) { int gridID = 10 * startY + i; roadToHome.Add(gridID); } for (int i = startY; i < midY; i++) { int gridID = 10 * i + midX; roadToHome.Add(gridID); } for (int i = midX; i < homeX; i++) { int gridID = 10 * midY + i; roadToHome.Add(gridID); } for (int i = midY; i < homeY; i++) { int gridID = 10 * i + (int)homeX; roadToHome.Add(gridID); } } roadToHome.Add((int)homeY * 10 + (int)homeX); for (int x = 0; x < cols; x++) { for (int y = 0; y < rows; y++) { if (x >= 0 && x <= 2 && y >= 0 && y <= 1) { continue; } int gridID = 10 * y + x; if (roadToHome.Contains(gridID)) { continue; } gridPositions.Add(new Vector3(x, y, 0f)); } } } Vector3 RandomHomePosition() { int posX = Random.Range(6, 10); int posY = Random.Range(6, 10); Vector3 randomPosition = new Vector3((float) posX, (float) posY); return randomPosition; } //此函数返回一个随机的位置,用于放置trees Vector3 RandomTreePosition() { int posX = Random.Range(1, 9); int posY = Random.Range(1, 9); int posID = 10 * posY + posX; while ((posX <= 3 && posY <= 2) || roadToHome.Contains(posID) || roadToHome.Contains(posID + 1) || roadToHome.Contains(posID - 1) || roadToHome.Contains(posID + 10) || roadToHome.Contains(posID - 10)) { posX = Random.Range(1, 9); posY = Random.Range(1, 9); posID = 10 * posY + posX; } int treeIndex = 0; Vector3 randomPosition = new Vector3(posX, posY, 0); for (int i = 0; i < gridPositions.Count; i++) { if ((int)gridPositions[i].x == posX && (int)gridPositions[i].y == posY) { treeIndex = i; } } gridPositions.RemoveAt(treeIndex); //Return the randomly selected Vector3 position. return randomPosition; } //此函数返回一个随机的位置,用于放置traps Vector3 RandomTrapPosition() { int randomIndex = Random.Range(0, gridPositions.Count); Vector3 randomPosition = gridPositions[randomIndex]; gridPositions.RemoveAt(randomIndex); return randomPosition; } void LayoutTreesAtRandom(GameObject tile, int minimum, int maximum) { int objectCount = Random.Range(minimum, maximum + 1); for (int i = 0; i < objectCount; i++) { Vector3 randomPosition = RandomTreePosition(); GameObject tileChoice = tile; Instantiate(tileChoice, randomPosition, Quaternion.identity); LayoutFlowers(randomPosition); } } void LayoutFlowers(Vector3 treePosition) { float posX = treePosition.x; float posY = treePosition.y; Vector3 f1 = new Vector3(posX - 1, posY, 0); int f1Index = -1; Vector3 f2 = new Vector3(posX + 1, posY, 0); int f2Index = -1; Vector3 f3 = new Vector3(posX, posY - 1, 0); int f3Index = -1; Vector3 f4 = new Vector3(posX, posY + 1, 0); int f4Index = -1; for (int i = 0; i < gridPositions.Count; i++) { if ((int)gridPositions[i].x == (int)f1.x && (int)gridPositions[i].y == (int)f1.y) { f1Index = i; GameObject flower = flowerTile; Instantiate(flower, f1, Quaternion.identity); break; } } if (f1Index != -1) { gridPositions.RemoveAt(f1Index); } for (int i = 0; i < gridPositions.Count; i++) { if ((int)gridPositions[i].x == (int)f2.x && (int)gridPositions[i].y == (int)f2.y) { f2Index = i; GameObject flower = flowerTile; Instantiate(flower, f2, Quaternion.identity); break; } } if (f2Index != -1) { gridPositions.RemoveAt(f2Index); } for (int i = 0; i < gridPositions.Count; i++) { if ((int)gridPositions[i].x == (int)f3.x && (int)gridPositions[i].y == (int)f3.y) { f3Index = i; GameObject flower = flowerTile; Instantiate(flower, f3, Quaternion.identity); break; } } if (f3Index != -1) { gridPositions.RemoveAt(f3Index); } for (int i = 0; i < gridPositions.Count; i++) { if ((int)gridPositions[i].x == (int)f4.x && (int)gridPositions[i].y == (int)f4.y) { f4Index = i; GameObject flower = flowerTile; Instantiate(flower, f4, Quaternion.identity); break; } } if (f4Index != -1) { gridPositions.RemoveAt(f4Index); } } void LayoutTrapsAtRandom(GameObject tile, int minimum, int maximum) { int objectCount = Random.Range(minimum, maximum + 1); for (int i = 0; i < objectCount; i++) { Vector3 randomPosition = RandomTrapPosition(); GameObject tileChoice = tile; Instantiate(tileChoice, randomPosition, Quaternion.identity); } } //SetupScene用于初始化关卡,并调用上面的函数来布置items的位置 public void SetupScene() { //Creates the outer walls and floor. BoardSetup(); SetupLayoutObjects(); } private void SetupLayoutObjects() { Vector3 homePosition = RandomHomePosition(); Instantiate(home, homePosition, Quaternion.identity); InitialiseList(homePosition); if (MenuNavigation.levelDifficulty == "Easy") { Debug.Log("Easy Difficulty Confirmed"); trapCount = new Count(7, 9); treeCount = new Count(2, 3); } else if (MenuNavigation.levelDifficulty == "Hard") { Debug.Log("Hard Difficulty Confirmed"); trapCount = new Count(20, 25); treeCount = new Count(5, 6); } else { Debug.Log("Normal Difficulty Confirmed"); trapCount = new Count(10, 15); treeCount = new Count(2, 3); } LayoutTreesAtRandom(treeTile, treeCount.min, treeCount.max); LayoutTrapsAtRandom(trapTile, trapCount.min, trapCount.max); } }
using System; using System.Collections.Generic; using UnityEngine; public class BluetoothDeviceScript : MonoBehaviour { public List<string> DiscoveredDeviceList; public Action InitializedAction; public Action DeinitializedAction; public Action<string> ErrorAction; public Action<string> ServiceAddedAction; public Action StartedAdvertisingAction; public Action StoppedAdvertisingAction; public Action<string, string> DiscoveredPeripheralAction; public Action<string, string, int, byte[]> DiscoveredPeripheralWithAdvertisingInfoAction; public Action<string, string> RetrievedConnectedPeripheralAction; public Action<string, byte[]> PeripheralReceivedWriteDataAction; public Action<string> ConnectedPeripheralAction; public Action<string> ConnectedDisconnectPeripheralAction; public Action<string> DisconnectedPeripheralAction; public Action<string, string> DiscoveredServiceAction; public Action<string, string, string> DiscoveredCharacteristicAction; public Action<string> DidWriteCharacteristicAction; public Action<string> DidUpdateNotificationStateForCharacteristicAction; public Action<string, string> DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction; public Action<string, byte[]> DidUpdateCharacteristicValueAction; public Action<string, string, byte[]> DidUpdateCharacteristicValueWithDeviceAddressAction; private bool Initialized; // Use this for initialization void Start () { DiscoveredDeviceList = new List<string>(); } // Update is called once per frame void Update () { } const string deviceInitializedString = "Initialized"; const string deviceDeInitializedString = "DeInitialized"; const string deviceErrorString = "Error"; const string deviceServiceAdded = "ServiceAdded"; const string deviceStartedAdvertising = "StartedAdvertising"; const string deviceStoppedAdvertising = "StoppedAdvertising"; const string deviceDiscoveredPeripheral = "DiscoveredPeripheral"; const string deviceRetrievedConnectedPeripheral = "RetrievedConnectedPeripheral"; const string devicePeripheralReceivedWriteData = "PeripheralReceivedWriteData"; const string deviceConnectedPeripheral = "ConnectedPeripheral"; const string deviceDisconnectedPeripheral = "DisconnectedPeripheral"; const string deviceDiscoveredService = "DiscoveredService"; const string deviceDiscoveredCharacteristic = "DiscoveredCharacteristic"; const string deviceDidWriteCharacteristic = "DidWriteCharacteristic"; const string deviceDidUpdateNotificationStateForCharacteristic = "DidUpdateNotificationStateForCharacteristic"; const string deviceDidUpdateValueForCharacteristic = "DidUpdateValueForCharacteristic"; public void OnBluetoothMessage (string message) { if (message != null) { char[] delim = new char[] { '~' }; string[] parts = message.Split (delim); for (int i = 0; i < parts.Length; ++i) { BluetoothLEHardwareInterface.Log(string.Format("Part: {0} - {1}", i, parts[i])); } if (message.Length >= deviceInitializedString.Length && message.Substring (0, deviceInitializedString.Length) == deviceInitializedString) { Initialized = true; if (InitializedAction != null) InitializedAction (); } else if (message.Length >= deviceDeInitializedString.Length && message.Substring (0, deviceDeInitializedString.Length) == deviceDeInitializedString) { BluetoothLEHardwareInterface.FinishDeInitialize (); Initialized = false; if (DeinitializedAction != null) DeinitializedAction (); } else if (message.Length >= deviceErrorString.Length && message.Substring (0, deviceErrorString.Length) == deviceErrorString) { string error = ""; if (parts.Length >= 2) error = parts[1]; if (ErrorAction != null) ErrorAction (error); } else if (message.Length >= deviceServiceAdded.Length && message.Substring (0, deviceServiceAdded.Length) == deviceServiceAdded) { if (parts.Length >= 2) { if (ServiceAddedAction != null) ServiceAddedAction (parts[1]); } } else if (message.Length >= deviceStartedAdvertising.Length && message.Substring (0, deviceStartedAdvertising.Length) == deviceStartedAdvertising) { BluetoothLEHardwareInterface.Log("Started Advertising"); if (StartedAdvertisingAction != null) StartedAdvertisingAction (); } else if (message.Length >= deviceStoppedAdvertising.Length && message.Substring (0, deviceStoppedAdvertising.Length) == deviceStoppedAdvertising) { BluetoothLEHardwareInterface.Log("Stopped Advertising"); if (StoppedAdvertisingAction != null) StoppedAdvertisingAction (); } else if (message.Length >= deviceDiscoveredPeripheral.Length && message.Substring (0, deviceDiscoveredPeripheral.Length) == deviceDiscoveredPeripheral) { if (parts.Length >= 3) { // the first callback will only get called the first time this device is seen // this is because it gets added to the a list in the DiscoveredDeviceList // after that only the second callback will get called and only if there is // advertising data available if (!DiscoveredDeviceList.Contains (parts[1])) { DiscoveredDeviceList.Add (parts[1]); if (DiscoveredPeripheralAction != null) DiscoveredPeripheralAction (parts[1], parts[2]); } if (parts.Length >= 5 && DiscoveredPeripheralWithAdvertisingInfoAction != null) { // get the rssi from the 4th value int rssi = 0; if (!int.TryParse (parts[3], out rssi)) rssi = 0; // parse the base 64 encoded data that is the 5th value byte[] bytes = System.Convert.FromBase64String(parts[4]); DiscoveredPeripheralWithAdvertisingInfoAction(parts[1], parts[2], rssi, bytes); } } } else if (message.Length >= deviceRetrievedConnectedPeripheral.Length && message.Substring (0, deviceRetrievedConnectedPeripheral.Length) == deviceRetrievedConnectedPeripheral) { if (parts.Length >= 3) { DiscoveredDeviceList.Add (parts[1]); if (RetrievedConnectedPeripheralAction != null) RetrievedConnectedPeripheralAction (parts[1], parts[2]); } } else if (message.Length >= devicePeripheralReceivedWriteData.Length && message.Substring (0, devicePeripheralReceivedWriteData.Length) == devicePeripheralReceivedWriteData) { if (parts.Length >= 3) OnPeripheralData (parts[1], parts[2]); } else if (message.Length >= deviceConnectedPeripheral.Length && message.Substring (0, deviceConnectedPeripheral.Length) == deviceConnectedPeripheral) { if (parts.Length >= 2 && ConnectedPeripheralAction != null) ConnectedPeripheralAction (parts[1]); } else if (message.Length >= deviceDisconnectedPeripheral.Length && message.Substring (0, deviceDisconnectedPeripheral.Length) == deviceDisconnectedPeripheral) { if (parts.Length >= 2) { if (ConnectedDisconnectPeripheralAction != null) ConnectedDisconnectPeripheralAction (parts[1]); if (DisconnectedPeripheralAction != null) DisconnectedPeripheralAction (parts[1]); } } else if (message.Length >= deviceDiscoveredService.Length && message.Substring (0, deviceDiscoveredService.Length) == deviceDiscoveredService) { if (parts.Length >= 3 && DiscoveredServiceAction != null) DiscoveredServiceAction (parts[1], parts[2]); } else if (message.Length >= deviceDiscoveredCharacteristic.Length && message.Substring (0, deviceDiscoveredCharacteristic.Length) == deviceDiscoveredCharacteristic) { if (parts.Length >= 4 && DiscoveredCharacteristicAction != null) DiscoveredCharacteristicAction (parts[1], parts[2], parts[3]); } else if (message.Length >= deviceDidWriteCharacteristic.Length && message.Substring (0, deviceDidWriteCharacteristic.Length) == deviceDidWriteCharacteristic) { if (parts.Length >= 2 && DidWriteCharacteristicAction != null) DidWriteCharacteristicAction (parts[1]); } else if (message.Length >= deviceDidUpdateNotificationStateForCharacteristic.Length && message.Substring (0, deviceDidUpdateNotificationStateForCharacteristic.Length) == deviceDidUpdateNotificationStateForCharacteristic) { if (parts.Length >= 3) { if (DidUpdateNotificationStateForCharacteristicAction != null) DidUpdateNotificationStateForCharacteristicAction (parts[2]); if (DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction != null) DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction (parts[1], parts[2]); } } else if (message.Length >= deviceDidUpdateValueForCharacteristic.Length && message.Substring (0, deviceDidUpdateValueForCharacteristic.Length) == deviceDidUpdateValueForCharacteristic) { if (parts.Length >= 4) OnBluetoothData (parts[1], parts[2], parts[3]); } } } public void OnBluetoothData (string base64Data) { OnBluetoothData ("", "", base64Data); } public void OnBluetoothData (string deviceAddress, string characteristic, string base64Data) { if (base64Data != null) { byte[] bytes = System.Convert.FromBase64String(base64Data); if (bytes.Length > 0) { BluetoothLEHardwareInterface.Log("Device: " + deviceAddress + " Characteristic Received: " + characteristic); string byteString = ""; foreach (byte b in bytes) byteString += string.Format("{0:X2}", b); BluetoothLEHardwareInterface.Log(byteString); if (DidUpdateCharacteristicValueAction != null) DidUpdateCharacteristicValueAction (characteristic, bytes); if (DidUpdateCharacteristicValueWithDeviceAddressAction != null) DidUpdateCharacteristicValueWithDeviceAddressAction (deviceAddress, characteristic, bytes); } } } public void OnPeripheralData (string characteristic, string base64Data) { if (base64Data != null) { byte[] bytes = System.Convert.FromBase64String(base64Data); if (bytes.Length > 0) { BluetoothLEHardwareInterface.Log("Peripheral Received: " + characteristic); string byteString = ""; foreach (byte b in bytes) byteString += string.Format("{0:X2}", b); BluetoothLEHardwareInterface.Log(byteString); if (PeripheralReceivedWriteDataAction != null) PeripheralReceivedWriteDataAction (characteristic, bytes); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using System.Windows.Interactivity; using System.Windows.Media; namespace Grisaia.SpriteViewer { /// <summary> /// https://stackoverflow.com/a/46427503/7517185 /// </summary> public class ZoomOnMouseWheel : Behavior<FrameworkElement> { public Key? ModifierKey { get; set; } = null; public TransformMode TranformMode { get; set; } = TransformMode.Render; private Transform _transform; protected override void OnAttached() { if (TranformMode == TransformMode.Render) _transform = AssociatedObject.RenderTransform = new MatrixTransform(); else _transform = AssociatedObject.LayoutTransform = new MatrixTransform(); AssociatedObject.MouseWheel += AssociatedObject_MouseWheel; } protected override void OnDetaching() { AssociatedObject.MouseWheel -= AssociatedObject_MouseWheel; } private void AssociatedObject_MouseWheel(object sender, MouseWheelEventArgs e) { if ((!ModifierKey.HasValue || !Keyboard.IsKeyDown(ModifierKey.Value)) && ModifierKey.HasValue) return; if (!(_transform is MatrixTransform transform)) return; Point pos1 = e.GetPosition(AssociatedObject); double scale = e.Delta > 0 ? 1.125 : 1 / 1.125; Matrix mat = transform.Matrix; mat.ScaleAt(scale, scale, pos1.X, pos1.Y); transform.Matrix = mat; e.Handled = true; } } public enum TransformMode { Layout, Render, } }
using UnityEngine; using System.Collections; public class CombatProperty : MonoBehaviour { public int HPMax = 100; public int HP = 100; public int Attack = 5; public Transform m_headUI; public UISlider m_xue; public bool isPlayer; private Object m_goDamage; private Animation m_animation; private AI m_ai; // Use this for initialization void Start () { m_goDamage = Resources.Load("Damage"); if (!isPlayer) { m_ai = GetComponent<AI>(); } else m_animation = GetComponent<Animation>(); } void LateUpdate() { m_headUI.rotation = Camera.main.transform.rotation; } public bool IsDead() { return HP == 0; } public bool BeAttacked(int attack) { if (HP == 0) return false; HP -= attack; if (HP < 0) { HP = 0; } m_xue.value = (float)HP/HPMax; GameObject da = Instantiate(m_goDamage, Vector3.zero, Quaternion.identity) as GameObject; da.GetComponent<HurtItem>().ChangeData(attack, transform.position, Camera.main); if(HP == 0) { if (!isPlayer) { m_ai.SetDead(); } else m_animation.CrossFade("Death"); } return true; } }
using System.ComponentModel.DataAnnotations.Schema; namespace GitlabManager.Services.Database.Model { /// <summary> /// Database model for ef-core for the Projects-Table /// </summary> [Table("Projects")] public class DbProject { /// <summary> /// Internal project id /// </summary> public int Id { get; set; } /// <summary> /// reference to the corresponding account /// </summary> public DbAccount Account { get; set; } /// <summary> /// External Gitlab-Project (may be the same for different gitlab accounts) /// </summary> public int GitlabProjectId { get; set; } /// <summary> /// Human readable name with namespace /// </summary> public string NameWithNamespace { get; set; } /// <summary> /// Project Description /// </summary> public string Description { get; set; } /// <summary> /// Timestamp when project was updated the last time /// </summary> public long LastUpdated { get; set; } /// <summary> /// List of tags /// </summary> public string[] TagList { get; set; } /// <summary> /// Boolean, whether project is starred /// </summary> public bool Stared { get; set; } /// <summary> /// Timestamp when user changed star (feature coming in later version) /// </summary> public long StaredChangeSaved { get; set; } /// <summary> /// Path to local folder /// </summary> public string LocalFolder { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ArteVida.GestorWeb.ViewModels { public class TabelaAuxiliarViewModel { [Key] public int Id { get; set; } [Required(ErrorMessage = "O campo NOME deve ser preenchido.")] [MaxLength(200), MinLength(2, ErrorMessage = "Nome deverá ter no mínimo 2 e no máximo 200 carateres")] public String Nome { get; set; } //public string Cargo { get; set; } public string Tipo { get; set; } public bool Ativo { get; set; } public String EstaAtivo { get { return Ativo ? "Sim" : "Não"; } } } }
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 Calorie_CalculatorCS { public partial class CaloriesCalculator : Form { public double[] activityCoefList = { 1.0, 1.2, 1.375, 1.55, 1.725, 1.9 }; public string[] activity = { "Basal Metabolic Rate (BMR)", "Sedentary (little or no excersize)", "Light Activity (exercise 1-3 days/week)", "Moderately activity (exercise/sports 4-5 days/week)", "Very activity (intense exercise/sports 6-7 days/week)", "Extreme activity (intense hard exercise/sports & physical job)", }; public int age = 25, ageMetric = 25; public char gender = 'M'; public int totalHeightInch = 72; public int heightFeet = 6, heightInch = 0; public double heightCm = 183; public double weightPound = 145; public double weightKg = 65; public double activityCoef = 1.0; public double BMR = 1.0; public double result = 0; public CaloriesCalculator() { InitializeComponent(); activityBox.DataSource = activity; activityBoxMetric.DataSource = activity; } private void ageBox_TextChanged(object sender, EventArgs e) { if (ageBox.Text == String.Empty) age = 25; else int.TryParse(ageBox.Text, out age); } // Printing results for US units private void button1_Click(object sender, EventArgs e) { totalHeightInch = heightFeet * 12 + heightInch; heightCm = totalHeightInch * 2.54; weightKg = weightPound * 0.453592; if (genderFemale.Checked) BMR = 9.247 * weightKg + 3.098 * heightCm - 4.33 * age + 447.593; else BMR = 13.397 * weightKg + 4.799 * heightCm - 5.677 * age + 88.362; result = Math.Ceiling(BMR * activityCoef); labelResultMaintenance.Text = result.ToString(); labelResultSlow.Text = (result - 250).ToString(); labelResultModerate.Text = (result - 500).ToString(); labelResultFast.Text = (result - 1000).ToString(); } private void activityBox_SelectedIndexChanged(object sender, EventArgs e) { for (int i = 0; i < activity.Length; i++) { if (activityBox.Text == activity[i]) activityCoef = activityCoefList[i]; } } private void heightBoxUSFeet_TextChanged(object sender, EventArgs e) { if (heightBoxUSFeet.Text == String.Empty) heightFeet = 6; else int.TryParse(heightBoxUSFeet.Text, out heightFeet); } private void heightBoxUSInch_TextChanged(object sender, EventArgs e) { if(heightBoxUSInch.Text == String.Empty) heightInch = 0; else int.TryParse(heightBoxUSInch.Text, out heightInch); } private void weightBoxUS_TextChanged(object sender, EventArgs e) { if (weightBoxUS.Text == String.Empty) weightPound = 145; else double.TryParse(weightBoxUS.Text, out weightPound); } private void ageBoxMetric_TextChanged(object sender, EventArgs e) { if (ageBoxMetric.Text == String.Empty) ageMetric = 25; else int.TryParse(ageBoxMetric.Text, out ageMetric); } private void activityBoxMetric_SelectedIndexChanged(object sender, EventArgs e) { for (int i = 0; i < activity.Length; i++) { if (activityBox.Text == activity[i]) activityCoef = activityCoefList[i]; } } private void heightBoxMetric_TextChanged(object sender, EventArgs e) { if (heightBoxMetric.Text == String.Empty) heightCm = 183; else double.TryParse(heightBoxMetric.Text, out heightCm); } private void weightBoxMetric_TextChanged(object sender, EventArgs e) { if (weightBoxMetric.Text == String.Empty) weightKg = 65; else double.TryParse(weightBoxMetric.Text, out weightKg); } // Printing results for metric units private void button2_Click(object sender, EventArgs e) { if (genderFemaleMetric.Checked) BMR = 9.247 * weightKg + 3.098 * heightCm - 4.33 * ageMetric + 447.593; else BMR = 13.397 * weightKg + 4.799 * heightCm - 5.677 * ageMetric + 88.362; result = Math.Ceiling(BMR * activityCoef); labelResultMaintenanceMetric.Text = result.ToString(); labelResultSlowMetric.Text = (result - 250).ToString(); labelResultModerateMetric.Text = (result - 500).ToString(); labelResultFastMetric.Text = (result - 1000).ToString(); } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; using System.Text.RegularExpressions; public class TextFieldRestrict : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Replace() { string text = GetComponent<Text>().text; text = Regex.Replace(text, @"[^a-zA-Z0-9 ]", ""); } }
using AdventOfCode2019; using NUnit.Framework; using System.Collections.Generic; namespace AdventOfCode2019Tests { public class Day04Tests { [SetUp] public void Setup() { } [Test] public void Part1() { var range = Day04.GeneratePasswords("1-10"); Assert.AreEqual(range.Count, 10); var input = new List<string>() { "111111", "223450", "123789" }; var results = Day04.ParsePasswordsP1(input); Assert.AreEqual(results, new List<string>() { "111111" }); } [Test] public void Part2() { var input = new List<string>() { "112233", "123444", "111122" }; var results = Day04.ParsePasswordsP2(input); Assert.AreEqual(results, new List<string>() { "112233", "111122" }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; namespace GODRenderPipeline { public class ContextDrawingSettings : MonoBehaviour, IRenderTreeItem { public void Render(ref ScriptableRenderContext context, GODRPParameters p) { p.filteringSettings = new FilteringSettings(RenderQueueRange.opaque, -1); p.sortingSettings = new SortingSettings(p.camera) { criteria = SortingCriteria.CommonOpaque }; p.drawingSettings = new DrawingSettings(new ShaderTagId(lightMode), p.sortingSettings); foreach (Transform child in transform) { if (!child.gameObject.activeInHierarchy) continue; child.GetComponents(components); for (int i = 0; i < components.Count; i++) { if (components[i] is IRenderTreeItem renderTreeItem) { renderTreeItem.Render(ref context, p); } } } } List<MonoBehaviour> components = new List<MonoBehaviour>(); public string lightMode = "LightMode "; public RenderQueueRange renderQueueRange; } }
using ApartmentManager.DAO; 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 ApartmentManager { public partial class frmBlock : frmCommon { public frmBlock() { InitializeComponent(); LoadDataInit(); } private void LoadDataInit() { var data = BlockDAO.Instance.GetAllBlock(); grvBlock.DataSource = data; cbBlockCode.DataSource = data; cbBlockCode.DisplayMember = "MABLOCK"; cbBlockCode.ValueMember = "MABLOCK"; } private void label2_Click(object sender, EventArgs e) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MoveToScene : MonoBehaviour { [SerializeField] private string sceneToCall; // Start is called before the first frame update void Start() { SceneManager.LoadScene(sceneToCall); Debug.Log("will fill in later, sorry future Denise"); } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using DiabeticsHelper; namespace DiabeticsHelper.Controllers { public class Log_BookController : Controller { private Diabetes_Helper_Entities db = new Diabetes_Helper_Entities(); // GET: Log_Book public ActionResult Index() { var log_Book = db.Log_Book.Include(l => l.Meal_Routine).Include(l => l.User); return View(log_Book.ToList()); } // GET: Log_Book/Details/5 public ActionResult Details(long? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Log_Book log_Book = db.Log_Book.Find(id); if (log_Book == null) { return HttpNotFound(); } return View(log_Book); } // GET: Log_Book/Create public ActionResult Create() { ViewBag.Routine_ID = new SelectList(db.Meal_Routine, "Routine_ID", "Routine_ID"); ViewBag.User_ID = new SelectList(db.Users, "User_ID", "First_Name"); return View(); } // POST: Log_Book/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Log_Book_ID,User_ID,Log_Date,Log_Time,Meter_Reading,Log_Notes,Routine_ID")] Log_Book log_Book) { if (ModelState.IsValid) { db.Log_Book.Add(log_Book); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.Routine_ID = new SelectList(db.Meal_Routine, "Routine_ID", "Routine_ID", log_Book.Routine_ID); ViewBag.User_ID = new SelectList(db.Users, "User_ID", "First_Name", log_Book.User_ID); return View(log_Book); } // GET: Log_Book/Edit/5 public ActionResult Edit(long? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Log_Book log_Book = db.Log_Book.Find(id); if (log_Book == null) { return HttpNotFound(); } ViewBag.Routine_ID = new SelectList(db.Meal_Routine, "Routine_ID", "Routine_ID", log_Book.Routine_ID); ViewBag.User_ID = new SelectList(db.Users, "User_ID", "First_Name", log_Book.User_ID); return View(log_Book); } // POST: Log_Book/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Log_Book_ID,User_ID,Log_Date,Log_Time,Meter_Reading,Log_Notes,Routine_ID")] Log_Book log_Book) { if (ModelState.IsValid) { db.Entry(log_Book).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.Routine_ID = new SelectList(db.Meal_Routine, "Routine_ID", "Routine_ID", log_Book.Routine_ID); ViewBag.User_ID = new SelectList(db.Users, "User_ID", "First_Name", log_Book.User_ID); return View(log_Book); } // GET: Log_Book/Delete/5 public ActionResult Delete(long? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Log_Book log_Book = db.Log_Book.Find(id); if (log_Book == null) { return HttpNotFound(); } return View(log_Book); } // POST: Log_Book/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(long id) { Log_Book log_Book = db.Log_Book.Find(id); db.Log_Book.Remove(log_Book); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System.Xml.Serialization; namespace GrandCloud.CS.Model { /// <summary> /// The DeleteObjectRequest contains the parameters used for the DeleteObject operation. /// <br />Required Parameters: BucketName, Key /// <br />The MfaCodes property is required if the bucket containing this object has been /// configured with the EnableMfaDelete property. For more information, please see: /// <see cref="P:GrandCloud.CS.Model.CSBucketVersioningConfig.EnableMfaDelete"/>. /// </summary> public class DeleteObjectRequest : CSRequest { #region Private Members private string bucketName; private string key; private string versionId; private Tuple<string, string> mfaCodes; #endregion #region BucketName /// <summary> /// Gets and sets the BucketName property. /// </summary> [XmlElementAttribute(ElementName = "BucketName")] public string BucketName { get { return this.bucketName; } set { this.bucketName = value; } } /// <summary> /// Sets the BucketName property for this request. /// This is the CS Bucket that contains the CS Object /// you want to delete. /// </summary> /// <param name="bucketName">The value that BucketName is set to</param> /// <returns>the request with the BucketName set</returns> public DeleteObjectRequest WithBucketName(string bucketName) { this.bucketName = bucketName; return this; } /// <summary> /// Checks if BucketName property is set. /// </summary> /// <returns>true if BucketName property is set.</returns> internal bool IsSetBucketName() { return !System.String.IsNullOrEmpty(this.bucketName); } #endregion #region Key /// <summary> /// Gets and sets the Key property. /// </summary> [XmlElementAttribute(ElementName = "Key")] public string Key { get { return this.key; } set { this.key = value; } } /// <summary> /// Sets the Key property for this request. /// This is the Key for the CS Object you want to delete. /// </summary> /// <param name="key">The value that Key is set to</param> /// <returns>the request with the Key set</returns> public DeleteObjectRequest WithKey(string key) { this.key = key; return this; } /// <summary> /// Checks if Key property is set. /// </summary> /// <returns>true if Key property is set.</returns> internal bool IsSetKey() { return !System.String.IsNullOrEmpty(this.key); } #endregion } }
using System; using System.Collections.Generic; namespace NgTs.Entities { #region entity factory public class NgTsUser{ long _userid; public long UserId { get {return this._userid;} set { this._userid = value;} } string _username; public string UserName { get {return this._username;} set { this._username = value;} } string _usercode; public string UserCode { get {return this._usercode;} set { this._usercode = value;} } string _firstname; public string FirstName { get {return this._firstname;} set { this._firstname = value;} } string _lastname; public string LastName { get {return this._lastname;} set { this._lastname = value;} } string _password; public string Password { get {return this._password;} set { this._password = value;} } } #endregion }
using Logic.Resource; using System; namespace Logic.Buildings { [Serializable] public class HabitatBuilder : Builder { public HabitatBuilder(string habitatName) : base(24, new ReadOnlyResources(10E9, 100E9, 100E6), new Habitat(habitatName)) { } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using Common; using Common.Utils; using OpenTK; using OpenTK.Graphics.OpenGL4; namespace Glass.Graphics { class SkyBoxRenderer { public int SkyBoxTextureId { get; set; } private Vector3[] _verticesForCube = null; private float _size; public SkyBoxRenderer(float size) { _size = size; _verticesForCube = GeometryHelper.GetVerticesForSkyBoxCube(size); SkyBoxTextureId = LoadTextures(size); } public void Render(Vector3 playerPos, Matrix4 modelView, Matrix4 projection) { Shaders.BindSkybox(_verticesForCube, playerPos, modelView, projection, SkyBoxTextureId); GL.DrawArrays(PrimitiveType.Triangles, 0, _verticesForCube.Length); GL.BindTexture(TextureTarget.TextureCubeMap, 0); } private int LoadTextures(float size) { GL.ActiveTexture(TextureUnit.Texture0); var textureId = GL.GenTexture(); GL.BindTexture(TextureTarget.TextureCubeMap, textureId); for (int i = 0; i < 6; i++) { var png = new Bitmap(@"Assets\Textures_p\Skybox\" + skyboxPaths[i]); var width = png.Width; var height = png.Height; var bitmapData = png.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexImage2D(TextureTarget.TextureCubeMapPositiveX + i, 0, PixelInternalFormat.Rgba, width, height, 0, OpenTK.Graphics.OpenGL4.PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); GL.TexSubImage2D(TextureTarget.TextureCubeMapPositiveX + i, 0, 0, 0, width, height, OpenTK.Graphics.OpenGL4.PixelFormat.Bgra, PixelType.UnsignedByte, bitmapData.Scan0); png.UnlockBits(bitmapData); GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMinFilter, (int)All.Linear); GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMagFilter, (int)All.Linear); GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapR, (int)All.ClampToEdge); GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); } GL.BindTexture(TextureTarget.TextureCubeMap, 0); return textureId; } private static string[] skyboxPaths = new string[] { "right.png", "left.png", "top.png", "bottom.png", "front.png", "back.png", }; } }
using ReadyGamerOne.View; using PurificationPioneer.Const; namespace PurificationPioneer.View { public partial class AndroidBattlePanel : AbstractPanel { partial void OnLoad(); protected override void Load() { Create(PanelName.AndroidBattlePanel); OnLoad(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using SEGU_ENTI; using SEGU_ENTI.Interfaz; using CAPA_NEGO; using System.Data; using System.Data.SqlClient; using SEGU_ENTI.Entidades; using System.Web.Mvc; namespace SEGU_JC.Models { public class M_PERSONA : IEN_USUARIO { clsNEGOCIO oclsNEGOCIO = new clsNEGOCIO(); [Authorize] public List<clsEN_USUARIO> fn_Login(string sCO_USUA, string sDE_PASS) { //throw new NotImplementedException(); List<clsEN_USUARIO> lEN_USUARIO = new List<clsEN_USUARIO>(); DataTable dt = oclsNEGOCIO.fn_LOGU_USUA(sCO_USUA.ToUpper(), sDE_PASS.ToUpper()); if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { lEN_USUARIO.Add( new clsEN_USUARIO() { CO_USUA = dr["CO_USUA"].ToString(), ID_USUA = int.Parse(dr["ID_USUA"].ToString() == "" ? "0" : dr["ID_USUA"].ToString()), PERSONA = fn_PERSONA(dr["NO_USUA"].ToString()), } ); } } return lEN_USUARIO; } public List<clsEN_PERSONA> fn_PERSONA(string sNO_USUA) { List<clsEN_PERSONA> lEN_PERSONA = new List<clsEN_PERSONA>(); lEN_PERSONA.Add(new clsEN_PERSONA() { NO_USUA = sNO_USUA, }); return lEN_PERSONA; } public List<clsEN_USUARIO> fn_MOST_USUA(string sCO_USUA) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Text; using FileProcessor.Entities; using NLog; using System.Configuration; using System.Data.SqlClient; using System.Data; using System.Linq; namespace FileProcessor.Repository { public class ClubRepo { private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public static int AddClub(ClubEntity club) { SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AODB"].ConnectionString); string insertStatement = "INSERT into Clubs " + "(ClubCode,ClubName) " + "VALUES (@ClubCode,@ClubName)"; SqlCommand insertCommand = new SqlCommand(insertStatement, connection); insertCommand.Parameters.AddWithValue( "@ClubCode", club.ClubCode); insertCommand.Parameters.AddWithValue( "@ClubName", club.ClubName); try { connection.Open(); int value = insertCommand.ExecuteNonQuery(); return value; } catch (SqlException ex) { if (ex.Message.Contains("Violation of PRIMARY KEY constraint")) logger.Error("Duplicate:" + club.ClubCode); return 0; } finally { connection.Close(); } } public static ClubEntity GetClub(String ClubCode) { SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AODB"].ConnectionString); string selectStatement = "SELECT * " + "FROM Clubs " + "WHERE ClubCode = @Code"; SqlCommand selectCommand = new SqlCommand(selectStatement, connection); selectCommand.Parameters.AddWithValue( "@Code", ClubCode); try { connection.Open(); SqlDataReader proReader = selectCommand.ExecuteReader( System.Data.CommandBehavior.SingleRow); if (proReader.Read()) { ClubEntity club = new ClubEntity(); club.ClubCode = proReader["ClubCode"].ToString(); club.ClubName = proReader["ClubName"].ToString(); return club; } else { return null; } } catch (SqlException ex) { throw ex; } finally { connection.Close(); } } public static List<ClubEntity> GetClubs() { List<ClubEntity> clubEntities = new List<ClubEntity>(); SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AODB"].ConnectionString); string selectStatement = "SELECT * " + "FROM Clubs "; SqlCommand selectCommand = new SqlCommand(selectStatement, connection); try { connection.Open(); SqlDataReader proReader = selectCommand.ExecuteReader(); if (proReader.HasRows) { DataTable dt = new DataTable(); dt.Load(proReader); clubEntities = (from x in dt.AsEnumerable() select new ClubEntity() { ClubCode = x["ClubCode"].ToString(), ClubName = x["ClubName"].ToString() }).ToList(); } return clubEntities; } catch (SqlException ex) { throw ex; } finally { connection.Close(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.ComponentModel; using System.Windows.Forms; namespace QuestStudio { [TypeConverter(typeof(QuestDataConverter))] public class QUEST_DATA_CONDITION { public ushort VarNo { get; set; } public QuestVarType VarType { get; set; } public short Value { get; set; } public Operator_Cond op { get; set; } }; [TypeConverter(typeof(QuestDataConverter))] public class QUEST_DATA_REWARD { public QUEST_DATA_REWARD() { op = Operator_Act.OP_SET; } public ushort VarNo { get; set; } public QuestVarType VarType { get; set; } public short Value { get; set; } public Operator_Act op { get; set; } }; [TypeConverter(typeof(QuestDataConverter))] public class ABIL_DATA_CONDITION { public Ability type { get; set; } public int value { get; set; } public Operator_Cond op { get; set; } }; [TypeConverter(typeof(QuestDataConverter))] public class ABIL_DATA_REWARD { public ABIL_DATA_REWARD() { op = SetAddSubOperator.OP_SET; } public Ability type { get; set; } public int value { get; set; } public SetAddSubOperator op { get; set; } // Ability doesn't need Set ON/OFF }; [TypeConverter(typeof(QuestDataConverter))] public class ITEM_DATA_CONDITION { public uint itemsn { get; set; } public EquipIndex equipslot { get; set; } public int cnt { get; set; } public Operator_Cond op { get; set; } }; [TypeConverter(typeof(EnumDescriptionConverter))] public enum ConditionType { [Description("Select quest")] COND000 = 0, [Description("Quest variable check")] COND001 = 1, [Description("User variable check")] COND002 = 2, [Description("Ability check")] COND003 = 3, [Description("Item check")] COND004 = 4, [Description("Party check")] COND005 = 5, [Description("Position check")] COND006 = 6, [Description("World time check [unused]")] COND007 = 7, [Description("Remaining quest time")] COND008 = 8, [Description("Skill check")] COND009 = 9, [Description("Random percent")] COND010 = 10, [Description("Check NPC/eventobj variable")] COND011 = 11, [Description("Select eventobj")] COND012 = 12, [Description("Select NPC")] COND013 = 13, [Description("Quest switch check")] COND014 = 14, [Description("Party member count")] COND015 = 15, [Description("Zone time check")] COND016 = 16, [Description("Compare NPC variables")] COND017 = 17, [Description("Time of day (month)")] COND018 = 18, [Description("Time of day (week) [unused]")] COND019 = 19, [Description("Team check [unused]")] COND020 = 20, [Description("Distance to NPC/eventobj")] COND021 = 21, [Description("Channel check")] COND022 = 22, [Description("In Clan")] COND023 = 23, [Description("Clan rank")] COND024 = 24, [Description("Clan contribution [unused]")] COND025 = 25, [Description("Clan grade")] COND026 = 26, [Description("Clan points")] COND027 = 27, [Description("Clan money")] COND028 = 28, [Description("Clan member count [unused]")] COND029 = 29, [Description("Clan skill")] COND030 = 30, /* Custom Conditions */ [Description("Does not have quest")] COND050 = 50, [Description("In ArenaGroup")] COND051 = 51, [Description("Compare arena status to eventvalue")] COND052 = 52, [Description("Check quest switch by eventvalue")] COND053 = 53, [Description("Arena game check")] COND054 = 54, }; [TypeConverter(typeof(EnumDescriptionConverter))] public enum RewardType { [Description("Quest action")] REWD000, [Description("Give/take item")] REWD001, [Description("Change quest variable")] REWD002, [Description("Change ability")] REWD003, [Description("Change user variable")] REWD004, [Description("Give item/exp/money")] REWD005, [Description("Set HP/MP %")] REWD006, [Description("Warp user/party")] REWD007, [Description("Spawn mob")] REWD008, [Description("Set next trigger")] REWD009, [Description("Reset stats")] REWD010, [Description("Set NPC/eventobj variable")] REWD011, [Description("NPC message")] REWD012, [Description("Set next NPC/eventobj trigger")] REWD013, [Description("Add/remove Skill")] REWD014, [Description("Set quest switch")] REWD015, [Description("Reset switch group [unused]")] REWD016, [Description("Reset all quest switches [unused]")] REWD017, [Description("NPC Announce [unused]")] REWD018, [Description("Do zone trigger")] REWD019, [Description("Set team")] REWD020, [Description("Set revive location")] REWD021, [Description("Set regen mode [unused]")] REWD022, [Description("Increase clan grade")] REWD023, [Description("Set clan money")] REWD024, [Description("Set clan points")] REWD025, [Description("Add/remove clan skill")] REWD026, [Description("[bug27] [unused]")] // Contribute bugged REWD027, [Description("Warp clan members in range")] REWD028, [Description("LUA function")] REWD029, [Description("Reset skills")] REWD030, [Description("[bug31] [unused]")] REWD031, [Description("Give item [unused]")] REWD032, [Description("[bug33] [unused]")] REWD033, [Description("Show/hide NPC")] REWD034, /* Custom Rewards */ [Description("Reward from break")] REWD050 = 50, [Description("Write message")] REWD051 = 51, [Description("Set quest switch by eventvalue")] REWD052 = 52, }; public enum QuestVarType : ushort { //[Description("Per-Quest Variables (0-9)")] QuestVar = 0x0000, //[Description("Per-Quest Switches (0-31)")] QuestSwitch = 0x0100, //[Description("Remaining quest time.")] QuestTime = 0x0200, //[Description("Used in the Episode Quest (0-4)")] EpisodeVar = 0x0300, //[Description("Used in Job Quests (0-2)")] JobVar = 0x0400, //[Description("Planet Variables (0-6)")] PlanetVar = 0x0500, //[Description("Used in Union Quests (0-9)")] UnionVar = 0x0600, }; [TypeConverter(typeof(EnumDescriptionConverter))] public enum Operator_Cond : byte { [Description("==")] OP_EQUALS = 0, [Description(">")] OP_G = 1, [Description(">=")] OP_GE = 2, [Description("<")] OP_L = 3, [Description("<=")] OP_LE = 4, [Description("!=")] OP_INEQ = 10, }; [TypeConverter(typeof(EnumDescriptionConverter))] public enum Operator_Act : byte { [Description("=")] OP_SET = 5, [Description("+=")] OP_ADD = 6, [Description("-=")] OP_SUB = 7, [Description("SET(0/OFF)")] OP_OFF = 8, [Description("SET(1/ON)")] OP_ON = 9, }; [TypeConverter(typeof(EnumDescriptionConverter))] public enum Operator : byte { [Description("==")] OP_EQUALS = 0, [Description(">")] OP_G = 1, [Description(">=")] OP_GE = 2, [Description("<")] OP_L = 3, [Description("<=")] OP_LE = 4, [Description("=")] OP_SET = 5, [Description("+=")] OP_ADD = 6, [Description("-=")] OP_SUB = 7, [Description("SET(0/OFF)")] OP_OFF = 8, [Description("SET(1/ON)")] OP_ON = 9, [Description("!=")] OP_INEQ = 10, }; [TypeConverter(typeof(EnumDescriptionConverter))] public enum AddSubOperator : byte { [Description("+=")] OP_ADD = 6, [Description("-=")] OP_SUB = 7, }; [TypeConverter(typeof(EnumDescriptionConverter))] public enum SetAddSubOperator : byte { [Description("=")] OP_SET = 5, [Description("+=")] OP_ADD = 6, [Description("-=")] OP_SUB = 7, }; [TypeConverter(typeof(EnumDescriptionConverter))] public enum QuestActionOperator : byte { Remove = 0, Append = 1, [Description("Set (keep timer)")] Set_Keep = 2, [Description("Set (reset timer)")] Set_Reset = 3, Select = 4, }; [TypeConverter(typeof(EnumDescriptionConverter))] public enum Ability : int { [Description("Ability 0")] ABILITY0 = 0, //[Description("Ability 1")] //ABILITY1 = 1, [Description("Gender")] ABILITY2 = 2, [Description("Birth Stone")] ABILITY3 = 3, [Description("Job")] ABILITY4 = 4, [Description("Union")] ABILITY5 = 5, [Description("Rank")] ABILITY6 = 6, [Description("Fame")] ABILITY7 = 7, [Description("Face")] ABILITY8 = 8, [Description("Hair")] ABILITY9 = 9, [Description("Strength")] ABILITY10 = 10, [Description("Dexterity")] ABILITY11 = 11, [Description("Intelligence")] ABILITY12 = 12, [Description("Concentration")] ABILITY13 = 13, [Description("Charm")] ABILITY14 = 14, [Description("Sensibility")] ABILITY15 = 15, // Stats recalculated frequently, not affected by quest rewards. //[Description("HP")] //ABILITY16 = 16, //[Description("MP")] //ABILITY17 = 17, //[Description("Attack Power")] //ABILITY18 = 18, //[Description("Defense")] //ABILITY19 = 19, //[Description("Hit Rate")] //ABILITY20 = 20, //[Description("Magic Defense")] //ABILITY21 = 21, //[Description("Dodge Rate")] //ABILITY22 = 22, //[Description("Moving Speed")] //ABILITY23 = 23, //[Description("Attack Speed")] //ABILITY24 = 24, //[Description("Weight")] //ABILITY25 = 25, //[Description("Critical")] //ABILITY26 = 26, //[Description("HP Recovery Rate")] //ABILITY27 = 27, //[Description("MP Recovery Rate")] //ABILITY28 = 28, //[Description("MP Decrease")] //ABILITY29 = 29, [Description("Experience")] ABILITY30 = 30, [Description("Level")] ABILITY31 = 31, [Description("Stat Points")] ABILITY32 = 32, [Description("PK Flag")] ABILITY33 = 33, [Description("Team")] ABILITY34 = 34, [Description("Head Size")] ABILITY35 = 35, [Description("Body Size")] ABILITY36 = 36, [Description("Skill Points")] ABILITY37 = 37, [Description("Max HP")] ABILITY38 = 38, [Description("Max MP")] ABILITY39 = 39, [Description("Money")] ABILITY40 = 40, //[Description("[Passive] Bare Hand Attack Power")] //ABILITY41 = 41, //[Description("[Passive] Attack Power of One-Hand Weapon")] //ABILITY42 = 42, //[Description("[Passive] Attack Power of Two-Hand Weapon")] //ABILITY43 = 43, //[Description("[Passive] Attack Power of Bow")] //ABILITY44 = 44, //[Description("[Passive] Attack Power of Gun")] //ABILITY45 = 45, //[Description("[Passive] Attack Power of Magick Weapon")] //ABILITY46 = 46, //[Description("[Passive] Attack Power of Bow gun")] //ABILITY47 = 47, //[Description("[Passive] Attack Power of Combat Weapon")] //ABILITY48 = 48, //[Description("[Passive] Attack Speed of Bow")] //ABILITY49 = 49, //[Description("[Passive] Attack Speed of Gun")] //ABILITY50 = 50, //[Description("[Passive] Attack Speed of Combat Weapon")] //ABILITY51 = 51, //[Description("[Passive] Moving Speed")] //ABILITY52 = 52, //[Description("[Passive] Defense Power")] //ABILITY53 = 53, //[Description("[Passive] Max HP")] //ABILITY54 = 54, //[Description("[Passive] Max MP")] //ABILITY55 = 55, //[Description("[Passive] HP Recovery Amount")] //ABILITY56 = 56, //[Description("[Passive] MP Recovery Rate")] //ABILITY57 = 57, //[Description("[Passive] Capacity of Bag Pack")] //ABILITY58 = 58, //[Description("[Passive] Discount in Purchase")] //ABILITY59 = 59, //[Description("[Passive] Sales Premium")] //ABILITY60 = 60, //[Description("[Passive] Decrease of required MP spending")] //ABILITY61 = 61, //[Description("[Passive] Expansion of Summoning Gauge")] //ABILITY62 = 62, //[Description("[Passive] Extra Drop Chance")] //ABILITY63 = 63, [Description("Pay Planet Tax")] ABILITY73 = 73, [Description("Current Planet")] ABILITY75 = 75, [Description("Stamina")] ABILITY76 = 76, //[Description("Fuel")] //ABILITY77 = 77, [Description("Union Points 1 [Junon Order]")] ABILITY81 = 81, //[Description("Union Points 2")] //ABILITY82 = 82, [Description("Union Points 3 [Crusaders]")] ABILITY83 = 83, [Description("Union Points 4 [Arumic]")] ABILITY84 = 84, [Description("Union Points 5 [Ferrell]")] ABILITY85 = 85, //[Description("Union Points 6")] //ABILITY86 = 86, [Description("Valor")] ABILITY87 = 87, [Description("Premium Points")] ABILITY88 = 88, //[Description("Union Points 9")] //ABILITY89 = 89, //[Description("Union Points 10")] //ABILITY90 = 90, // Clan [Description("Clan ID")] ABILITY91 = 91, [Description("Clan Points")] ABILITY92 = 92, [Description("Clan Position")] ABILITY93 = 93, // MaintainAbility coupons //[Description("Free warehouse")] //ABILITY94 = 94, //[Description("Warehouse Extension")] //ABILITY95 = 95, //[Description("Change private shop appearance")] //ABILITY96 = 96, //[Description("[Medal] Experience Rate")] //ABILITY97 = 97, [Description("Farming Permit (Junon)")] ABILITY105 = 105, [Description("Farming Permit (Luna)")] ABILITY106 = 106, [Description("Farming Permit (Eldeon)")] ABILITY107 = 107, [Description("Farming Permit (Oro)")] ABILITY108 = 108, [Description("Cartel ELO")] ABILITY115 = 115, //[Description("Gathering Double Speed")] //ABILITY110 = 110, //[Description("Gathering Double Drop")] //ABILITY111 = 111, //[Description("Gathering Speed")] //ABILITY112 = 112, //[Description("[Passive] Magic Resistance")] //ABILITY121 = 121, //[Description("[Passive] Hitting Rate")] //ABILITY122 = 122, //[Description("[Passive] Critical Rate")] //ABILITY123 = 123, //[Description("[Passive] Dodge Rate")] //ABILITY124 = 124, //[Description("[Passive] Shield Defense Power")] //ABILITY125 = 125, [Description("Soulmate Points")] ABILITY141 = 141, [Description("Soulmate Level")] ABILITY142 = 142, [Description("Soulmate Party Lvl ")] ABILITY143 = 143, [Description("Str, Dex, Int, Con, Cha, Sen")] ABILITY144 = 144, [Description("Current Union Points")] ABILITY146 = 146, //// Prestige stats //[Description("Posion Chance")] //ABILITY147 = 147, //[Description("Poison Rate")] //ABILITY148 = 148, //[Description("Stun Chance")] //ABILITY149 = 149, //[Description("Life Steal")] //ABILITY150 = 150, //[Description("Damage Reflect")] //ABILITY151 = 151, //[Description("Stun Deflect")] //ABILITY152 = 152, //[Description("Stealth Extend")] //ABILITY153 = 153, //[Description("Assist Survival")] //ABILITY154 = 154, }; public enum ItemRewardOperator : byte { Take = 0, Give = 1 }; public enum OnOffOperator : byte { Off = 0, On = 1 }; public enum ArenaGameOperator : byte { GameID = 0, GameType = 1 }; public enum HasOperator : byte { HasNot = 0, Has = 1 }; public enum Who08 : byte { Player = 0, NPC = 1, EventObject = 2, Coordinate = 3, }; public enum PlayerOrParty : byte { Player = 0, Party = 1, } public enum Who016 : byte { NPC = 0, EventObject = 1, Player = 2, }; public enum EquipIndex : int { Inventory = 0, Faceitem = 1, Helmet = 2, Armor = 3, Backitem = 4, Arm = 5, Boots = 6, Weapon_R = 7, Weapon_L = 8, Necklace = 9, Ring = 10, Earring = 11, Inventory2 = 12, QuestItem = 13, }; public enum NpcOrEvent : byte { NPC = 0, EventObject = 1 }; public enum MsgType : byte { Chat = 0, Shout = 1, Announce = 2, }; public enum ChatType : byte { ALL, SHOUT, PARTY, WHISPER, NOTICE, SYSTEM, ERROR, QUEST, QUESTREWARD, CLAN, TRADE, ALLIED, FRIEND, GROUP, DEBUG, ANNOUNCE, }; public enum AddRemoveOperator : byte { Remove = 0, Add = 1, }; public enum TeamNoType : byte { Player = 0, Clan = 1, Party = 2, }; public enum OffOnToggle : byte { Off = 0, On = 1, Toggle = 2, }; public enum NpcVisibility : byte { Hide = 0, Show = 1, Toggle = 2, }; public enum ItemRewardType : byte { Experience = 0, Money = 1, Item = 2, }; [TypeConverter(typeof(EnumDescriptionConverter))] public enum ItemRewardEquation : byte { [Description("0 (lower by lvl)")] Equation0 = 0, [Description("1 (exponential by lvl)")] Equation1 = 1, [Description("2 (zulie, value * questvar9)")] Equation2 = 2, [Description("3 (lower by lvl)")] Equation3 = 3, [Description("4 (higher by lvl & charm)")] Equation4 = 4, [Description("5 (lower by lvl)")] Equation5 = 5, [Description("6 (higher by lvl & charm)")] Equation6 = 6, [Description("15 (none, value is amount)")] Equation15 = 15, }; public enum ClanPos : short { PenaltyRookie = 0, Rookie = 1, Veteran = 2, Captain = 3, Commander = 4, DeputyMaster = 5, Master = 6, }; public enum DayOfWeek : byte { Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, }; }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("StoreButton")] public class StoreButton : PegUIElement { public StoreButton(IntPtr address) : this(address, "StoreButton") { } public StoreButton(IntPtr address, string className) : base(address, className) { } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public bool IsVisualClosed() { return base.method_11<bool>("IsVisualClosed", Array.Empty<object>()); } public void OnButtonOut(UIEvent e) { object[] objArray1 = new object[] { e }; base.method_8("OnButtonOut", objArray1); } public void OnButtonOver(UIEvent e) { object[] objArray1 = new object[] { e }; base.method_8("OnButtonOver", objArray1); } public void OnStoreStatusChanged(bool isOpen, object userData) { object[] objArray1 = new object[] { isOpen, userData }; base.method_8("OnStoreStatusChanged", objArray1); } public void Start() { base.method_8("Start", Array.Empty<object>()); } public void Unload() { base.method_8("Unload", Array.Empty<object>()); } public GameObject m_highlight { get { return base.method_3<GameObject>("m_highlight"); } } public HighlightState m_highlightState { get { return base.method_3<HighlightState>("m_highlightState"); } } public GameObject m_storeClosed { get { return base.method_3<GameObject>("m_storeClosed"); } } public UberText m_storeClosedText { get { return base.method_3<UberText>("m_storeClosedText"); } } public UberText m_storeText { get { return base.method_3<UberText>("m_storeText"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace database { public partial class Players { public static bool Login(string username, string password) { try{ tarotContainer t = new tarotContainer(); if (t.Accounts.OfType<Players>().Single(p => p.Username == username).Pwd == password) return true; }catch(Exception e) { Console.WriteLine("error: username doesn't exist."); } return false; } public static void Create(Players p) { tarotContainer t = new tarotContainer(); p.Id = Guid.NewGuid(); t.Accounts.AddObject(p); t.SaveChanges(); } public void Update(Players p) { tarotContainer t = new tarotContainer(); Players oldP = t.Accounts.OfType<Players>().Single(a => a.Id == p.Id); if (oldP.ScreenName != p.ScreenName) { t.Accounts.OfType<Players>().Single(a => a.Id == p.Id).ScreenName = p.ScreenName; } if (oldP.Username != p.Username) { t.Accounts.OfType<Players>().Single(a => a.Id == p.Id).Username = p.Username; } if (oldP.Pwd != p.Pwd) { t.Accounts.OfType<Players>().Single(a => a.Id == p.Id).Pwd = p.Pwd; } t.SaveChanges(); } public static Players Get(string login) { tarotContainer t = new tarotContainer(); return t.Accounts.OfType<Players>().Single(p => p.Username == login); } public static Players Get(Guid id) { tarotContainer t = new tarotContainer(); return t.Accounts.OfType<Players>().SingleOrDefault(p => p.Id == id); } public static List<Players> GetAll() { tarotContainer t = new tarotContainer(); return t.Accounts.OfType<Players>().ToList(); } public static void UpdateLoginDate(Guid id) { tarotContainer t=new tarotContainer(); t.Accounts.OfType<Players>().Single(p => p.Id == id).LastLogin = DateTime.Now; t.SaveChanges(); } public static void LogOff(Guid id) { tarotContainer t = new tarotContainer(); t.Accounts.OfType<Players>().Single(p => p.Id == id).LastLogin = new DateTime(); t.SaveChanges(); } } }
using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using System; using System.Collections.Generic; using System.Xml; using System.Linq; using System.IO; using System.Diagnostics; public class VunglePostBuilder : MonoBehaviour { private static string _postBuildDirectoryKey { get { return "VunglePostBuildPath-" + PlayerSettings.productName; } } private static string postBuildDirectory { get { return EditorPrefs.GetString( _postBuildDirectoryKey ); } set { EditorPrefs.SetString( _postBuildDirectoryKey, value ); } } [PostProcessBuild( 800 )] private static void onPostProcessBuildPlayer( BuildTarget target, string pathToBuiltProject ) { #if UNITY5_SCRIPTING_IN_UNITY4 if( target == BuildTarget.iPhone ) #else if( target == BuildTarget.iOS ) #endif { postBuildDirectory = pathToBuiltProject; // grab the path to the postProcessor.py file var scriptPath = Path.Combine( Application.dataPath, "Editor/Vungle/VunglePostProcessor.py" ); // sanity check if( !File.Exists( scriptPath ) ) { UnityEngine.Debug.LogError( "Vungle post builder could not find the VunglePostProcessor.py file. Did you accidentally delete it?" ); return; } var pathToNativeCodeFiles = Path.Combine( Application.dataPath, "Editor/Vungle/VungleSDK" ); var args = string.Format( "\"{0}\" \"{1}\" \"{2}\"", scriptPath, pathToBuiltProject, pathToNativeCodeFiles ); var proc = new Process { StartInfo = new ProcessStartInfo { FileName = "python", Arguments = args, UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; proc.Start(); proc.WaitForExit(); UnityEngine.Debug.Log( "Vungle post processor completed" ); } } [UnityEditor.MenuItem( "Tools/Vungle/Open Documentation Website..." )] static void documentationSite() { UnityEditor.Help.BrowseURL( "https://github.com/Vungle/vungle-resources/tree/master/English/Unity" ); } [UnityEditor.MenuItem( "Tools/Vungle/Run iOS Post Processor" )] static void runPostBuilder() { onPostProcessBuildPlayer( #if UNITY5_SCRIPTING_IN_UNITY4 BuildTarget.iPhone #else BuildTarget.iOS #endif , postBuildDirectory ); } [UnityEditor.MenuItem( "Tools/Vungle/Run iOS Post Processor", true )] static bool validateRunPostBuilder() { var iPhoneProjectPath = postBuildDirectory; if( iPhoneProjectPath == null || !Directory.Exists( iPhoneProjectPath ) ) return false; var projectFile = Path.Combine( iPhoneProjectPath, "Unity-iPhone.xcodeproj/project.pbxproj" ); if( !File.Exists( projectFile ) ) return false; return true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace Sklep.Products { public class Updater : ICommand { private Action commandTask; private Action<Product> taskParameter; public Updater(Action workToDo) { commandTask = workToDo; } public Updater(Action<Product> workToDo) { taskParameter = workToDo; } public bool CanExecute(object parameter) { if (commandTask != null) return true; if (parameter != null) return true; return false; } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public void Execute(object parameter) { if (parameter == null) commandTask(); else taskParameter(parameter as Product); } } }
using BPiaoBao.DomesticTicket.Platform.Plugin; using JoveZhao.Framework; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Web; namespace BPiaoBao.DomesticTicket.Platforms._YeeXing { //POST public class _YeeYingPlatformNotify : BasePlatform, IPlatformNotify { public override string Code { get { return "YeeXing"; } } public bool CanProcess(System.Collections.Specialized.NameValueCollection nameValueCollection) { bool IsCanProcess = false; try { //通知类型必须和订单号 签名 必须有 if (!string.IsNullOrEmpty(nameValueCollection["type"]) && !string.IsNullOrEmpty(nameValueCollection["orderid"]) && !string.IsNullOrEmpty(nameValueCollection["sign"]) && !string.IsNullOrEmpty(nameValueCollection["areaCity"]) ) { string areaCity = nameValueCollection["areaCity"]; var parames = platformConfig.Areas.GetByArea(ref areaCity); string _privateKey = parames["_privateKey"].Value; //签名验证 string decrSign = getSign(nameValueCollection, _privateKey); string sign = nameValueCollection["sign"]; if (sign == decrSign) { string type = nameValueCollection["type"].ToString(); if (type == "1")//出票 { if (!string.IsNullOrEmpty(nameValueCollection["passengerName"]) && !string.IsNullOrEmpty(nameValueCollection["airId"]) ) { IsCanProcess = true; } } else if (type == "2")//支付成功通知 { if (!string.IsNullOrEmpty(nameValueCollection["totalPrice"]) && !string.IsNullOrEmpty(nameValueCollection["payid"]) && decimal.Parse(nameValueCollection["totalPrice"]) > 0 ) { IsCanProcess = true; } } else if (type == "3")//取消成功通知(乘客或订单) { if (!string.IsNullOrEmpty(nameValueCollection["passengerName"])) { //passengerName 需要使用urldecode解密 IsCanProcess = true; } } else if (type == "4")//退废票通知 { if (!string.IsNullOrEmpty(nameValueCollection["refundPrice"]) && !string.IsNullOrEmpty(nameValueCollection["procedures"]) && !string.IsNullOrEmpty(nameValueCollection["airId"]) && decimal.Parse(nameValueCollection["refundPrice"]) > 0 ) { IsCanProcess = true; } } else if (type == "5")//改期通知 { if (!string.IsNullOrEmpty(nameValueCollection["changeMemo"])//改期或改证件备注 && !string.IsNullOrEmpty(nameValueCollection["changeStatus"])//改期状态 1—成功 2—拒绝 && !string.IsNullOrEmpty(nameValueCollection["refuseMemo"])//拒绝理由 ) { IsCanProcess = true; } } else if (type == "6")//拒绝出票通知 { if (!string.IsNullOrEmpty(nameValueCollection["passengerName"]) && !string.IsNullOrEmpty(nameValueCollection["refuseMemo"]) ) { IsCanProcess = true; } } } } } catch (Exception ex) { } return IsCanProcess; } public string Process(System.Collections.Specialized.NameValueCollection nameValueCollection) { string responseResult = string.Empty; //验证通知信息正常 if (CanProcess(nameValueCollection)) { string _OrderId = nameValueCollection["orderid"]; string _type = nameValueCollection["type"]; //判断通知类型 if (_type == "2")//支付 { #region 支付通知 decimal _TotalPay = decimal.Parse(nameValueCollection["totalPrice"]); string _TradeID = nameValueCollection["payid"]; if (OnPaid != null) { OnPaid(this, new PaidEventArgs() { OutOrderId = _OrderId, PaidMeony = _TotalPay, SerialNumber = _TradeID, PlatformCode = this.Code }); } #endregion } else if (_type == "1")//出票 { #region 出票通知 NameValueCollection nvTicketInfo = new NameValueCollection(); string[] passengerNames = nameValueCollection["passengerName"].Split(new string[] { "^" }, StringSplitOptions.RemoveEmptyEntries); string[] ticketNumbers = nameValueCollection["airId"].Split(new string[] { "^" }, StringSplitOptions.RemoveEmptyEntries); string passengerName = string.Empty; string ticketNo = string.Empty; for (int i = 0; i < passengerNames.Length; i++) { passengerName = passengerNames[i].ToUpper().Replace("CHD", "").Trim(); if (!string.IsNullOrEmpty(passengerName)) { ticketNo = ticketNumbers[i].Replace("--", "-").Trim(); if (!string.IsNullOrEmpty(ticketNo)) nvTicketInfo.Add(passengerName, ticketNo); } } if (nvTicketInfo.Count > 0 && OnIssue != null) { OnIssue(this, new IssueEventArgs() { OutOrderId = _OrderId, TicketInfo = nvTicketInfo, PlatformCode = this.Code, Remark = string.Empty }); } #endregion } else if (_type == "4")//退废票通知 { #region 退款通知 //退票的票号 多个用^分割 string airId = nameValueCollection["airId"]; //退款金额 decimal refundPrice = decimal.Parse(nameValueCollection["refundPrice"]); //退款手续费 decimal procedures = decimal.Parse(nameValueCollection["procedures"]); //退款理由 string refuseMemo = nameValueCollection["refuseMemo"]; if (refundPrice > 0) { if (OnRefund != null) { OnRefund(this, new PlatformRefundEventArgs() { OutOrderId = _OrderId, RefundMoney = refundPrice, PlatformCode = this.Code, RefundRemark = refuseMemo + airId, RefundSerialNumber = "", TotalRefundPoundage = procedures, RefundType = "退废票通知", NotifyCollection = nameValueCollection }); } } #endregion } else if (_type == "6")//拒绝出票通知 { #region 取消出票 string passengerName = nameValueCollection["passengerName"]; string refuseMemo = nameValueCollection["refuseMemo"]; //取消出票 if (OnCancelIssue != null) { OnCancelIssue(this, new CancelIssueEventArgs() { OutOrderId = _OrderId, PlatformCode = this.Code, Ramark = "拒绝乘客:" + passengerName + "拒绝理由:" + refuseMemo, NotifyCollection = nameValueCollection }); } //全退款 if (OnRefund != null) { OnRefund(this, new PlatformRefundEventArgs() { OutOrderId = _OrderId, RefundMoney = 0m, PlatformCode = this.Code, RefundRemark = "取消出票", RefundSerialNumber = "", RefundType = "", NotifyCollection = nameValueCollection }); } #endregion } } return responseResult; } #region 签名 //MD5加密方法 private string userMd5(string str, Encoding enco) { MD5 md5 = MD5.Create(); byte[] s = md5.ComputeHash(enco.GetBytes(str)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < s.Length; i++) { sBuilder.Append(s[i].ToString("x2")); } return sBuilder.ToString(); } //获取签名 private string getSign(System.Collections.Specialized.NameValueCollection nameValueCollection, String privateKey) { SortedDictionary<String, String> param = new SortedDictionary<string, string>(); foreach (string key in nameValueCollection.Keys) { if (key.ToLower() != "sign" && key.ToLower() != "areacity") { if (!param.ContainsKey(key)) { param.Add(key, nameValueCollection[key]); } } } //获取哈希表中的所有的key ArrayList keys = new ArrayList(param.Keys); //将key进行排序 keys.Sort(); //将排序后的哈希表中key对应的值取出来 String prestr = ""; for (int i = 0; i < keys.Count; i++) { String s = Convert.ToString(keys[i]); String value = Convert.ToString(param["" + s + ""]); prestr = prestr + value; } //将排序后的结果加上key String resultstr = prestr + privateKey; //将上一步的结果,然后进行utf-8编码,变大写,MD5加密 String sign = userMd5(HttpUtility.UrlEncode(resultstr).ToUpper(), System.Text.Encoding.UTF8); return sign; } #endregion public event PaidEventHandler OnPaid; public event IssueEventHandler OnIssue; public event CancelIssueHandler OnCancelIssue; public event PlatformRefundHandler OnRefund; } }
using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Document; using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace SampleServer { internal class FoldingRangeHandler : IFoldingRangeHandler { public FoldingRangeRegistrationOptions GetRegistrationOptions() => new FoldingRangeRegistrationOptions { DocumentSelector = DocumentSelector.ForLanguage("csharp") }; public Task<Container<FoldingRange>?> Handle( FoldingRangeRequestParam request, CancellationToken cancellationToken ) => Task.FromResult<Container<FoldingRange>?>( new Container<FoldingRange>( new FoldingRange { StartLine = 10, EndLine = 20, Kind = FoldingRangeKind.Region, EndCharacter = 0, StartCharacter = 0 } ) ); public FoldingRangeRegistrationOptions GetRegistrationOptions(FoldingRangeCapability capability, ClientCapabilities clientCapabilities) => new FoldingRangeRegistrationOptions { DocumentSelector = DocumentSelector.ForLanguage("csharp") }; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SalemOptimizer { class Skill { public int Id { get; set; } public string Name { get; set; } public Skill(string name,int[] proficiencies) { this.Name = name; this.Proficiencies = proficiencies; } public int[] Proficiencies; } class SkillDatabase { private static readonly Lazy<List<Skill>> skills = new Lazy<List<Skill>>(Load); public static List<Skill> Skills { get { return skills.Value; } } static List<Skill> Load() { return File.ReadAllLines("Skills.tab") .Select(row => row.Split('\t')) .Select ( (cols, index) => new Skill ( cols[0], cols .Select((val, idx) => new { Index = idx, Value = val }) .Where(i => i.Index >= 1 && i.Index <= 15) .OrderBy(i => i.Index) .Select(i => string.IsNullOrWhiteSpace(i.Value) ? 0 : int.Parse(i.Value)) .ToArray() ) ) .Where(i => i.Proficiencies.Length > 0) .Select((inspirational, index) => { inspirational.Id = index; return inspirational; }) .ToList(); } } }
 using System; namespace Whimsy.Precondition.Annotation.Attributes { [AttributeUsage(AttributeTargets.Parameter)] public sealed class CanBeNullAttribute : Attribute {} }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab5 { class Program { static void Main(string[] args) { int userInput; string yes; do { Console.WriteLine("Welcome to the Factorial Calculator!"); Console.WriteLine("Please enter a whole number between 1 and 20:"); userInput = int.Parse(Console.ReadLine()); while (userInput < 0) { Console.WriteLine("Please enter a positive number."); userInput = int.Parse(Console.ReadLine()); } long num = Convert.ToInt64(userInput); long result = num; for (int i = 1; i < userInput; i++) { result = result * i; } Console.WriteLine(result); Console.WriteLine("Do you want to go again? (yes/no)"); yes = Console.ReadLine(); } while ((yes == "yes") || (yes == "y") || (yes == "Y") || (yes == "Yes") || (yes == "YES")); Console.WriteLine("Goodbye!"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class StartGame : MonoBehaviour { [SerializeField] int LevelNumber; public void StartFirstLevel() { SceneManager.LoadScene(1); } public void ReloadLevel() { SceneManager.LoadScene(LevelNumber); } public void MainMenu() { GameObject.Find("Audio Source").SetActive(false); SceneManager.LoadScene(0); } }
// Copyright 2020 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Runtime.InteropServices; namespace NtApiDotNet.Win32.AppModel { internal enum ACTIVATEOPTIONS { AO_NONE = 0x00000000, // No flags set AO_DESIGNMODE = 0x00000001, // The application is being activated for design mode, and thus will not be able to // to create an immersive window. Window creation must be done by design tools which // load the necessary components by communicating with a designer-specified service on // the site chain established on the activation manager. The splash screen normally // shown when an application is activated will also not appear. Most activations // will not use this flag. AO_NOERRORUI = 0x00000002, // Do not show an error dialog if the app fails to activate. AO_NOSPLASHSCREEN = 0x00000004, // Do not show the splash screen when activating the app. AO_PRELAUNCH = 0x02000000, // The application is being activated in Prelaunch mode. } [Guid("2e941141-7f97-4756-ba1d-9decde894a3d")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport] internal interface IApplicationActivationManager { [PreserveSig] NtStatus ActivateApplication( string appUserModelId, string arguments, ACTIVATEOPTIONS options, out int processId); [PreserveSig] NtStatus ActivateForFile( string appUserModelId, IntPtr itemArray, // IShellItemArray string verb, out int processId); [PreserveSig] NtStatus ActivateForProtocol( string appUserModelId, IntPtr itemArray, // IShellItemArray out int processId); } [Guid("45BA127D-10A8-46EA-8AB7-56EA9078943C")] [ComImport] class ApplicationActivationManager { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Minesweeper { public class Coordinate { public int x { get; set; } public int y { get; set; } public Coordinate(int x, int y) { this.x = x; this.y = y; } override public int GetHashCode() { int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } override public bool Equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (this.GetType() != obj.GetType()) return false; Coordinate other = (Coordinate)obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } }
#region Copyright Syncfusion Inc. 2001 - 2015 // Copyright Syncfusion Inc. 2001 - 2015. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // licensing@syncfusion.com. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class StackedArea : SampleView { public StackedArea () { SFChart chart = new SFChart (); SFCategoryAxis primaryAxis = new SFCategoryAxis (); primaryAxis.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift; chart.PrimaryAxis = primaryAxis; chart.SecondaryAxis = new SFNumericalAxis (); StackingAreaDataSource dataModel = new StackingAreaDataSource (); chart.DataSource = dataModel as SFChartDataSource; this.control = chart; } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Frame; } base.LayoutSubviews (); } } } public class StackingAreaDataSource : SFChartDataSource { NSMutableArray DataPoints; NSMutableArray DataPoints1; NSMutableArray DataPoints2; public StackingAreaDataSource () { DataPoints = new NSMutableArray (); DataPoints1 = new NSMutableArray (); DataPoints2 = new NSMutableArray (); AddDataPointsForChart("2010", 45,54,14); AddDataPointsForChart("2011", 89,24,54); AddDataPointsForChart("2012", 23,53,23); AddDataPointsForChart("2013", 43,63,53); AddDataPointsForChart("2014", 54,35,25); } void AddDataPointsForChart (String XValue, Double YValue, Double YValue1, Double YValue2) { DataPoints.Add (new SFChartDataPoint (NSObject.FromObject (XValue), NSObject.FromObject(YValue))); DataPoints1.Add (new SFChartDataPoint (NSObject.FromObject (XValue), NSObject.FromObject(YValue1))); DataPoints2.Add (new SFChartDataPoint (NSObject.FromObject (XValue), NSObject.FromObject(YValue2))); } [Export ("numberOfSeriesInChart:")] public override nint NumberOfSeriesInChart (SFChart chart) { return 3; } [Export ("chart:seriesAtIndex:")] public override SFSeries GetSeries (SFChart chart, nint index) { SFStackingAreaSeries series = new SFStackingAreaSeries (); series.Alpha = 0.6f; series.BorderWidth = 3; if(index == 0) series.BorderColor = UIColor.FromRGBA( 255.0f/255.0f ,191.0f/255.0f,0.0f/255.0f,1.0f); else if(index ==1) series.BorderColor = UIColor.FromRGBA( 81.0f/255.0f ,72.0f/255.0f,57.0f/255.0f,1.0f); else series.BorderColor = UIColor.FromRGBA( 195.0f/255.0f ,81.0f/255.0f,64.0f/255.0f,1.0f); return series; } [Export ("chart:dataPointAtIndex:forSeriesAtIndex:")] public override SFChartDataPoint GetDataPoint (SFChart chart, nint index, nint seriesIndex) { if (seriesIndex == 0) return DataPoints.GetItem<SFChartDataPoint> ((nuint)index); else if (seriesIndex == 1) return DataPoints1.GetItem<SFChartDataPoint> ((nuint)index); else return DataPoints2.GetItem<SFChartDataPoint> ((nuint)index); } [Export ("chart:numberOfDataPointsForSeriesAtIndex:")] public override nint GetNumberOfDataPoints (SFChart chart, nint index) { if(index == 0) return (int)DataPoints.Count; else if(index ==1) return (int)DataPoints1.Count; else return (int)DataPoints2.Count; } }
using Newtonsoft.Json; namespace StarWarsApi.DataAccess.Entities { public class FilmPlanetMapping { [JsonProperty("id")] public int FilmPlanetMappingId { get; set; } public int FilmId { get; set; } public Film Film { get; set; } public int PlanetId { get; set; } public Planet Planet { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class UIManager : MonoBehaviour { public Text scoreUI; public Text highScoreUI; public GameObject panelGameOver; public Transform player; private bool gameOver = false; private int score; private int highScore; private void Awake() { panelGameOver.SetActive(false); highScore = PlayerPrefs.GetInt("HighScore"); highScoreUI.text = "" + highScore; } private void Update() { if (gameOver) { if (Input.GetMouseButtonDown(0) || Input.GetButtonDown("Fire1")) SceneManager.LoadScene("Game"); } else if (player != null) { score = Mathf.RoundToInt(Mathf.Clamp(player.position.x, 0, Mathf.Infinity)); scoreUI.text = "" + score; } if (Input.GetKeyDown(KeyCode.F1)) { PlayerPrefs.SetInt("HighScore", 0); highScore = 0; highScoreUI.text = "" + 0; } if (Input.GetKeyDown(KeyCode.Escape)) { SceneManager.LoadScene("Menu"); } if (Input.GetKeyDown(KeyCode.F2)) { Time.timeScale = Time.timeScale == 1 ? 0 : 1; } } public void GameOver() { gameOver = true; panelGameOver.SetActive(true); if (score > highScore) { highScore = score; PlayerPrefs.SetInt("HighScore", highScore); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using ArticleSubmitTool.Web.Models.InstantArticles; using ArticleSubmitTool.Web.Models.InstantArticles.Items; namespace ArticleSubmitTool.Code.Facebook.API { /// <summary> /// builds instant article view model from domain model /// </summary> public static class InstantArticleModelFactory { private static readonly Dictionary<InstantArticleItemType, System.Func<InstantArticleItemModel, InstantArticleItemModel>> _createFromDic = new Dictionary <InstantArticleItemType, System.Func<InstantArticleItemModel, InstantArticleItemModel>>() { {InstantArticleItemType.Image, (x) => new ImageItem(x) }, {InstantArticleItemType.Video, (x) => new VideoItem(x) }, {InstantArticleItemType.BodyText, (x) => new TextItem(x)}, {InstantArticleItemType.PullQuote, (x) => new PullQuoteItem(x) }, {InstantArticleItemType.BlockQuote, (x) => new BlockQuoteItem(x) }, {InstantArticleItemType.Ad, (x) => new AdItem(x) }, {InstantArticleItemType.Map, (x) => new MapItem(x) }, {InstantArticleItemType.Twitter, (x) => new TwitterEmbedItem(x) }, {InstantArticleItemType.Facebook, (x) => new FacebookEmbedItem(x) }, {InstantArticleItemType.Instagram, (x) => new InstagramEmbedItem(x) }, {InstantArticleItemType.YouTube, (x) => new YouTubeEmbedItem(x) }, {InstantArticleItemType.Caption, (x) => new CaptionItem(x) }, {InstantArticleItemType.SlideShow, (x) => new SlideShowItem(x) } }; public static readonly Dictionary<InstantArticleItemType, InstantArticleItemModel> Items = new Dictionary <InstantArticleItemType, InstantArticleItemModel>() { {InstantArticleItemType.Image, new ImageItem()}, {InstantArticleItemType.Video, new VideoItem()}, {InstantArticleItemType.BodyText, new TextItem()}, {InstantArticleItemType.PullQuote, new PullQuoteItem()}, {InstantArticleItemType.BlockQuote, new BlockQuoteItem()}, {InstantArticleItemType.Ad, new AdItem()}, {InstantArticleItemType.Map, new MapItem()}, {InstantArticleItemType.Twitter, new TwitterEmbedItem()}, {InstantArticleItemType.Facebook, new FacebookEmbedItem()}, {InstantArticleItemType.Instagram, new InstagramEmbedItem()}, {InstantArticleItemType.YouTube, new YouTubeEmbedItem()}, {InstantArticleItemType.Caption, new CaptionItem()}, {InstantArticleItemType.SlideShow, new SlideShowItem()}, }; public static InstantArticleItemModel CreateFrom(int type, InstantArticleItemModel model) { _createFromDic.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); return _createFromDic[(InstantArticleItemType)type](model); } public static InstantArticleItemModel Create(int type) { var itemdic = Items.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); return itemdic[(InstantArticleItemType)type]; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace DataValidation { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { } #region UserName private string _UserName; public string UserName { get { return _UserName; } set { _UserName = value; } } #endregion #region EmailID private string _EmailID; public string EmailID { get { return _EmailID; } set { _EmailID = value; } } #endregion #region word private string _word; public string word { get { return _word; } set { _word = value; } } #endregion #region Age private string _Age; public string Age { get { return _Age; } set { _Age = value; } } #endregion private void Button_Click_1(object sender, RoutedEventArgs e) { if (txtUserName.Text.Length < 6) { namvalidate.Visibility = Windows.UI.Xaml.Visibility.Visible; namvalidate.Text = "User Name should contain atleast 6 chars"; } if (!txtEmailID.Text.Contains("@") || !txtEmailID.Text.Contains(".")) { emailvalidate.Visibility = Windows.UI.Xaml.Visibility.Visible; emailvalidate.Text = "Invalid Email ID"; } if (Convert.ToInt32(txtAge.Text) < 18 || Convert.ToInt32(txtAge.Text) > 40) { agevalidate.Visibility = Windows.UI.Xaml.Visibility.Visible; agevalidate.Text = "Age should be range in 18 ~ 40"; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sets { class Program { static void Main(string[] args) { var cities = new SortedSet<string>(StringComparer.InvariantCultureIgnoreCase) {"NY", "Manc", "Shef", "Par"}; cities.Add("SHEF"); cities.Add("PAR"); foreach (string item in cities) { Console.WriteLine(item); } } } }
using System.Collections.Generic; namespace stottle_shop_api.Filters.Data { public class FilterSetsDTO { public IEnumerable<FilterSetDTO> FilterSets { get; set; } } public class FilterSetDTO { public string DisplayName { get; set; } public string Code { get; set; } public IEnumerable<FilterSetItemDTO> Items { get; set; } } public class FilterSetItemDTO { public string Code { get; set; } public string Name { get; set; } public bool IsHiddenOnLoad { get; set; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Thrift; using Thrift.Protocol; using Thrift.Transport; using tutorial; namespace CSharpAsyncTutorial.Client { class Program { static void Main(string[] args) { Task.Run(async () => { await Run(); }).Wait(); } static async Task Run() { try { var transport = new TSocket("localhost", 9090, 100000); TBufferedTransport transportBuff = new TBufferedTransport(transport, 2048); TProtocol protocol = new TBinaryProtocol(transportBuff); transport.Open(); Calculator.Client client = new Calculator.Client(protocol); Console.WriteLine($"run Client host:{transport.Host},port:{transport.Port}"); await client.pingAsync(); int testCount = 100000; var sw = Stopwatch.StartNew(); foreach (var m in Enumerable.Range(0, testCount)) { int sum = client.add(1, 1); } sw.Stop(); Console.WriteLine($"TBufferedTransport Execute client.add(1, 1) do:{testCount} ms:{sw.ElapsedMilliseconds}"); sw.Restart(); foreach (var m in Enumerable.Range(0, testCount)) { int sum = await client.addAsync(1, 1); } sw.Stop(); Console.WriteLine($"TBufferedTransport Execute client.addAsync(1, 1) do:{testCount} ms:{sw.ElapsedMilliseconds}"); await client.calculateAsync(1,new Work() { Op=Operation.ADD,Comment="add Comment"});//InvalidOperation transport.Close(); } catch (InvalidOperation ex) { Console.WriteLine($"InvalidOperation why:{ex.Why} op:{ex.WhatOp} ex:{ex.GetType()} message:{ex.Message} {ex.StackTrace}"); } catch (TApplicationException x) { Console.WriteLine($"TApplicationException ex:{x.Type} message:{x.Message} {x.StackTrace}"); } } } }
using System; using System.Collections.Generic; using System.IO; namespace BalacedBrackets { class MainClass { public static void createParenthesesStack(string toEvaluate, ref Stack<char> parentheses) { int characterNotFound = -1; for (int i = toEvaluate.IndexOf(')'); i > characterNotFound; i = toEvaluate.IndexOf(')', i + 1)) { if (0 == i) { parentheses.Push(toEvaluate[i]); } else if (toEvaluate[i - 1] == (':')) { continue; } else { parentheses.Push(toEvaluate[i]); } } for (int j = toEvaluate.IndexOf('('); j > characterNotFound; j = toEvaluate.IndexOf('(', j + 1)) { if (0 == j) { parentheses.Push(toEvaluate[j]); } else if (toEvaluate[j - 1] == (':')) { continue; } else { parentheses.Push(toEvaluate[j]); } } } public static bool isBalanced(string toEvaluate) { if (0 == toEvaluate.Length) { return true; } Stack<char> parentheses = new Stack<char>(); createParenthesesStack(toEvaluate, ref parentheses); if (parentheses.Count % 2 != 0) { return false; } int openParenthesis = 0; int closeParenthesis = 0; char current; while (parentheses.Count > 0) { current = parentheses.Pop(); if (current == '(') { openParenthesis++; } else { closeParenthesis++; } } if (openParenthesis == closeParenthesis) { return true; } else { return false; } } public static void Main(string[] args) { string pathToFile = "../../resources/strings.in"; string[] lines = System.IO.File.ReadAllLines(pathToFile); pathToFile = "../../resources/balance.out"; StreamWriter sw = new StreamWriter(new FileStream(pathToFile, FileMode.Create)); for (int i = 0; i < Int32.Parse(lines[0]); i++) { if (isBalanced(lines[i + 1])) { sw.WriteLine("Caso #" + (i + 1) + ": SI"); } else { sw.WriteLine("Caso #" + (i + 1) + ": NO"); } } sw.Dispose(); } } }
using Com.PDev.PCG.Actions; using System.Collections; using System.Collections.Generic; using System; namespace Com.PDev.PCG.Actions { public class Event { string name; public Event(string name) { this.Name = name; } public string Name { get { return name; } set { name = value; } } } public class EventStack { static Stack<Event> events = new Stack<Event>(); public static void PushEvent(Event ev) { events.Push(ev); } public static Event PopEvent() { return events.Pop(); } public static bool IsEmpty { get { return events.Count == 0; } } } }
using System; using UnityEngine; public class TintColor : MonoBehaviour { private const string TINT_COLOR = "_TintColor"; public Color col; private Renderer render; private void Start() { this.render = base.GetComponent<Renderer>(); this.col = this.render.get_material().GetColor("_TintColor"); } private void Update() { this.render.get_material().SetColor("_TintColor", this.col); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace console { public class _044_Subsets { /// <summary> /// Given a set of distinct integers, S, return all possible subsets. /// Note: /// Elements in a subset must be in non-descending order. /// The solution set must not contain duplicate subsets. /// For example, /// If S = [1,2,3], a solution is: /// [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] /// </summary> /// <param name="input"></param> public List<List<int>> FindAllSubSet(List<int> input) { _036_Combinations obj = new _036_Combinations(); obj.res.Clear(); obj.hashSet.Clear(); for (int i = 0; i <= input.Count; i++) { obj.FindAllCombinations(input, i,0); } return obj.res; } /// <summary> /// Same function different way. This one is kind of DP solution... /// I need to get familar with this DP method. /// </summary> /// <param name="input"></param> /// <returns></returns> public List<List<int>> FindAllSubSet2(List<int> input) { List<List<int>> res = new List<List<int>>(); List<int> empty = new List<int>(); res.Add(empty); for(int i = 0;i < input.Count;i ++) { int resCount = res.Count; for(int j = 0; j< resCount ;j ++) { List<int> tmp = new List<int>(res[j]); tmp.Add(input[i]); res.Add(tmp); } } return res; } /// <summary> /// Same function different way, this time try to use recursive. /// </summary> /// <param name="input"></param> /// <returns></returns> public List<List<int>> FindAllSubSet3(List<int> input) { List<List<int>> res = new List<List<int>>(); FindAllSubSet3Working(res, input, 0); return res; } private void FindAllSubSet3Working(List<List<int>> res, List<int> input, int index) { if (index == input.Count) { res.Add(new List<int>()); } else { FindAllSubSet3Working(res, input, index + 1); int count = res.Count; for (int i = 0; i < count; i++) { List<int> tmp = new List<int>(res[i]); tmp.Add(input[index]); res.Add(tmp); } } } /// <summary> /// Same goal with another method. /// 代码分析: ///   介绍一种比较不一样的方法——Combinatoric。 ///     例子: S = { 1, 2, 3} ///     i = 0 : (1 << S.Count - 1) = 0 : 111 (就是S有3个数,i 最大到 111, 4个数, i 最大就到 1111 。。。) ///       然后 k = i; k & 1 == 1 就把相应 S[index] 加到答案里面。然后k >>= 1; ///         k = 0;(0x0)  {} ///         k = 1;(0x1)  {1} ///         k = 2;(0x10)  {2},    /// k = 3;(0x11)  {1,2}; /// k = 4;(0x100) {3}; /// k = 5;(0x101) {1,3}; /// k = 6;(0x110) {2,3}; /// k = 7;(0x111) {1,2,3};   /// </summary> /// <param name="S"></param> /// <returns></returns> public List<List<int>> SubsetsCombinatoric(List<int> S) { S.Sort(); List<List<int>> ret = new List<List<int>>(); for (int i = 0; i < (1 << S.Count); i++) { int k = i; int index = 0; List<int> subset = new List<int>(); while (k > 0) { if ((k & 1) > 0) { subset.Add(S[index]); } k >>= 1; index++; } ret.Add(subset); } return ret; } /// <summary> /// Given a collection of integers that might contain duplicates, S, return all possible subsets. /// Note: /// Elements in a subset must be in non-descending order. /// The solution set must not contain duplicate subsets. /// For example, /// If S = [1,2,2], a solution is: /// [ [2], [1], [1,2,2], [2,2], [1,2], [] ] /// </summary> /// <param name="input"></param> /// <returns></returns> public List<List<int>> FindSubSetsWithDup(List<int> input) { //First though I have is remove dup from the input list. then do the normal thing, but [1,2,2] is a valid output. //So I can not just remove the dup. //then I think a hashset can help. but need extra space. input.Sort(); List<List<int>> res = new List<List<int>>(); res.Add(new List<int>()); int start = 0; for (int i = 0; i < input.Count; i++) { int count = res.Count; for (int j = start; j < count; j++) { List<int> tmp = new List<int>(res[j]); tmp.Add(input[i]); res.Add(tmp); } if (i < input.Count - 1 && input[i] == input[i + 1]) { start = count; } else { start = 0; } } return res; } } }
using System.Linq; using System.Reflection; namespace Rabbit.DataUp { public static class DataUpExecution { /// <summary> /// Initialize all data revisions from specified assemblies /// </summary> public static DataUpWorker Initialize(params Assembly[] assemblies) { return Initialize(Enumerable.Empty<string>().ToArray(), assemblies); } /// <summary> /// Initialize all data revisions from specified assemblies and tag /// </summary> public static DataUpWorker Initialize(string[] tags, params Assembly[] assemblies) { return new DataUpWorker(new DefaultDataUpHandlerSearchWorker(), tags, assemblies); } /// <summary> /// Initialize all data revisions from specified assemblies, tag /// </summary> public static DataUpWorker Initialize(IDataUpHandlerSearchWorker dataUpHandlerSearchWorker, string[] tags, params Assembly[] assemblies) { return new DataUpWorker(dataUpHandlerSearchWorker, tags, assemblies); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using YzkSoftWare.Data; namespace YzkSoftWare.DataModel { /// <summary> /// 数据模型接口 /// </summary> public interface IDataModel : IExtendProperty, IInnerExtendProperty { /// <summary> /// 数据对象的名称 /// </summary> string Name { get; } /// <summary> /// 数据对象的显示名称 /// </summary> string DisplayName { get; } /// <summary> /// 数据库对象的原型:.net类型 /// </summary> Type ClrType { get; } /// <summary> /// 数据库对象类型 /// </summary> DbTypeForDataModel DbType { get; } /// <summary> /// 获取该模型的主键 /// </summary> IEnumerable<IDataModelFieldIndex> PrimaryKeys { get; } /// <summary> /// 获取该模型的索引 /// </summary> IEnumerable<IDataModelFieldIndex> IndexKeys { get; } /// <summary> /// 字段模型集合 /// </summary> IDataFieldModelCollection Fields { get; } } /// <summary> /// 定义数据类型的数据库对象类型 /// </summary> [ResourceDisplayName(typeof(LocalResource), "DbTypeForDataModel")] [ResourceDescription(typeof(LocalResource), "DbTypeForDataModel_Des")] public enum DbTypeForDataModel { /// <summary> /// 未知 /// </summary> [ResourceDisplayName(typeof(LocalResource), "Unkown")] Unkown = 0, /// <summary> /// 基础表 /// </summary> [ResourceDisplayName(typeof(LocalResource), "Table")] Table = 1, /// <summary> /// 视图 /// </summary> [ResourceDisplayName(typeof(LocalResource), "View")] View = 2, /// <summary> /// 存储过程 /// </summary> [ResourceDisplayName(typeof(LocalResource), "Store")] Store = 3, /// <summary> /// Sql表达式 /// </summary> [ResourceDisplayName(typeof(LocalResource), "Sql")] Sql = 4 } internal sealed class TypeDataModel : ExtendProperty, IDataModel { public TypeDataModel(Type clrtype) { p_InnerExtend.SetExtendPropertyValue("ClrType", clrtype); p_InnerExtend.SetExtendPropertyValue("Name", clrtype.GetNameForDatabase()); p_InnerExtend.SetExtendPropertyValue("DisplayName", clrtype.GetDisplayName()); p_InnerExtend.SetExtendPropertyValue("DbType", clrtype.GetDatabaseObjectType()); DataModelHelper.SetExtendProperty_Fields(p_InnerExtend, clrtype); } private IExtendProperty p_InnerExtend = new ExtendProperty(); string IDataModel.Name { get { return p_InnerExtend.GetExtendPropertyValue<string>("Name", null); } } string IDataModel.DisplayName { get { return p_InnerExtend.GetExtendPropertyValue<string>("DisplayName", null); } } DbTypeForDataModel IDataModel.DbType { get { return p_InnerExtend.GetExtendPropertyValue<DbTypeForDataModel>("DbType", DbTypeForDataModel.Unkown); } } Type IDataModel.ClrType { get { return p_InnerExtend.GetExtendPropertyValue<Type>("ClrType", null); } } IEnumerable<IDataModelFieldIndex> IDataModel.PrimaryKeys { get { return DataModelHelper.GetExtendProperty_PrimaryKeys(p_InnerExtend); } } IEnumerable<IDataModelFieldIndex> IDataModel.IndexKeys { get { return DataModelHelper.GetExtendProperty_IndexKeys(p_InnerExtend); } } IExtendProperty IInnerExtendProperty.InnerExtend { get { return p_InnerExtend; } } IDataFieldModelCollection IDataModel.Fields { get { return DataModelHelper.GetExtendProperty_Fields(p_InnerExtend); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using eIVOGo.Module.Base; using Model.DataEntity; using Utility; namespace eIVOGo.Module.SAM { public partial class UserProfileEntityManager : InquireEntity { protected void Page_Load(object sender, EventArgs e) { } protected override UserControl _itemList { get { return itemList; } } protected override void buildQueryItem() { Expression<Func<UserProfile, bool>> queryExpr = i => true; if (!String.IsNullOrEmpty(PID.Text)) { queryExpr = queryExpr.And(i => i.PID == PID.Text); } if (!String.IsNullOrEmpty(UserName.Text)) { queryExpr = queryExpr.And(i => i.UserName == UserName.Text); } if (!String.IsNullOrEmpty(UserStatus.SelectedValue)) { queryExpr = queryExpr.And(i => i.UserProfileStatus.CurrentLevel == int.Parse(UserStatus.SelectedValue)); } if (!String.IsNullOrEmpty(RoleID.SelectedValue)) { int roleID = int.Parse(RoleID.SelectedValue); queryExpr = queryExpr.And(i => i.UserRole.Count(r => r.RoleID == roleID) > 0); } itemList.QueryExpr = queryExpr; } protected override void btnAdd_Click(object sender, EventArgs e) { modelItem.DataItem = null; Server.Transfer(ToEdit.TransferTo); } } }
using System.Collections.Generic; using WebAppCrudSP.Web.Models; namespace WebAppCrudSP.Web.Service { public interface IStudentService { List<Student> GetStudents(string name); void SaveOrUpdate(Student student); void Delete(int id); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Ph.Bouncer { public class TargetManager : MonoBehaviour { private const int GOAL_TARGET_HITS = 5; private TargetHits targetHits; void Start () { var targets = (Target[])FindObjectsOfType(typeof(Target)); targetHits = new TargetHits(targets); } void OnTargetHit(Colour targetColour, int hits) { //Debug.Log("Hit event! " + targetColour + "hits " + hits); targetHits.UpdateHits(targetColour, hits); if(targetHits.AllTargetsHaveHitsGreaterOrEqualTo(GOAL_TARGET_HITS)) Messenger.Broadcast(Events.LevelComplete); } void OnTargetDrain(Colour targetColour, int hits) { //Debug.Log("Drain event! " + targetColour + "hits " + hits); targetHits.UpdateHits(targetColour, hits); } void OnEnable() { Messenger<Colour, int>.AddListener(Events.TargetHit, OnTargetHit); Messenger<Colour, int>.AddListener(Events.TargetDrain, OnTargetDrain); } void OnDisable() { Messenger<Colour, int>.RemoveListener(Events.TargetHit, OnTargetHit); Messenger<Colour, int>.RemoveListener(Events.TargetDrain, OnTargetDrain); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SimpleMathsComparisonTest.cs" company=""> // // </copyright> // <summary> // The simple maths comparison test. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace SimpleMathsComparison { using System; using System.Diagnostics; /// <summary> /// The simple maths comparison test. /// </summary> internal class SimpleMathsComparisonTest { /// <summary> /// The main. /// </summary> internal static void Main() { Console.WriteLine("------------------------------- INT -------------------------------"); var x1 = 0; ExecuteMathTests(x1); Console.WriteLine("------------------------------- LONG -------------------------------"); long x2 = 0; ExecuteMathTests(x2); Console.WriteLine("------------------------------- FLOAT -------------------------------"); float x3 = 0; ExecuteMathTests(x3); Console.WriteLine("------------------------------- DOUBLE -------------------------------"); double x4 = 0; ExecuteMathTests(x4); Console.WriteLine("------------------------------- DECIMAL -------------------------------"); decimal x5 = 0; ExecuteMathTests(x5); } /// <summary> /// The display execution time. /// </summary> /// <param name="action"> /// The action. /// </param> /// <exception cref="Exception"> /// A delegate callback throws an exception. /// </exception> private static void DisplayExecutionTime(Action action) { var stopwatch = new Stopwatch(); stopwatch.Start(); action(); stopwatch.Stop(); Console.WriteLine(stopwatch.Elapsed); } /// <summary> /// The execute math tests. /// </summary> /// <param name="a"> /// The a. /// </param> private static void ExecuteMathTests(dynamic a) { const int LOOP_COUNT = 5000000; Console.Write("Add: "); DisplayExecutionTime( () => { a = a + 0; for (var i = 0; i < LOOP_COUNT; i++) { a = a + 1; } }); Console.Write("Subtract: "); DisplayExecutionTime( () => { a = a + 5000000; for (var i = 0; i < LOOP_COUNT; i++) { a = a - 1; } }); Console.Write("Increment: "); DisplayExecutionTime( () => { a = a + 0; for (var i = 0; i < LOOP_COUNT; i++) { a++; } }); Console.Write("Multiply: "); DisplayExecutionTime( () => { a = a + 1; for (var i = 0; i < LOOP_COUNT; i++) { a = a * 1; } }); Console.Write("Divide: "); DisplayExecutionTime( () => { a = a + 1; for (var i = 0; i < LOOP_COUNT; i++) { a = a / 1; } }); } } }
using System; using Xamarin.Forms; using App1.Interface; namespace App1 { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } private void Button_Clicked(object sender, EventArgs e) { //App.Notification.NotificationOffAll(); App.Notification.Show("title", "contents"); } } }
using Xunit; namespace RepeatedWordTDD { public class UnitTest1 { /// <summary> /// Test for the first repeated word. /// </summary> [Fact] public void RepeatedWordTestOne() { string testOne = "Once upon a time, there was a brave princess who..."; Assert.Equal("a", RepeatedWord.Program.RepeatedWord(testOne)); } [Fact] public void RepeatedWordTestTwo() { string testTwo = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way Ė in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only..."; Assert.Equal("it", RepeatedWord.Program.RepeatedWord(testTwo)); } [Fact] public void RepeatedWordwithCommas() { string testThree = "It was a queer sultry summer, the summer they electrocuted the Rosenbergs, and I didnít know what I was doing in New York..."; Assert.Equal("summer", RepeatedWord.Program.RepeatedWord(testThree)); } /// <summary> /// Test for empty string /// </summary> [Fact] public void EmptyStringTest() { string testOne = ""; Assert.Equal("No repeated word found.", RepeatedWord.Program.RepeatedWord(testOne)); } /// <summary> /// Test for no repeated words found /// </summary> /// <param name="input"></param> [Theory] [InlineData("one two three four five six")] [InlineData("seven eight nine ten eleven")] [InlineData("a b c d fgh ijk loop pool cat")] public void NoRepeatedFoundTest(string input) { Assert.Equal("No repeated word found.", RepeatedWord.Program.RepeatedWord(input)); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using Xunit; using Collections; namespace MyXUnitTests { public class DecodingTest { [Fact] public static void ApplyCommandsTest() { string[] user_input = { "push Привет! Это снова я! Пока!", "pop 5", "push Как твои успехи? Плохо?", "push qwertyuiop", "push 1234567890", "pop 26" }; string vActual = Decoding.ApplyCommands(user_input); string vExpected = "Привет! Это снова я! Как твои успехи? "; Assert.Equal(vExpected, vActual); } } }
using UnityEngine; public class LookAt : MonoBehaviour { public Transform prefab; //var Vector3 = (prefab.position.x, prefab.position.y, prefab.position.z); void Update() { // Point the object at the world origin transform.LookAt(Vector3.zero); //transform.LookAt(Vector3.back); } }
using senai_CZBooks.webapi.Domains; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace senai_CZBooks.webapi.Interfaces { interface ITipoUsuarioRepository { List<TipoUsuario> Listar(); } }
using System; using System.Collections.Generic; using System.Text; namespace Account { class Savings : Account { private int minBalance = 100; public Savings() { } public Savings(int accountID, string accountName, int balance) : base(accountID, accountName, balance) { } public void Transfer(int amount, Account acc) { if ((base.AccountBalance - amount) >= minBalance) base.Transfer(amount, acc); else Console.WriteLine("Insufficient Balance."); } } }
using MyCoolWebServer.Infrastructure; namespace MyCoolWebServer.GameStoreApplication.Controllers { public abstract class BaseController : Controller { protected override string ApplicationDirectory => "GameStoreApplication"; } }
namespace WebApplication1.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("Firebird.NAME_T")] public partial class NameType { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public NameType() { Names = new HashSet<Name>(); SysParamsWhereFN = new HashSet<SystemParameters>(); SysParamsWhereLN = new HashSet<SystemParameters>(); SysParamsWhereSuff = new HashSet<SystemParameters>(); SysParamsWherePref = new HashSet<SystemParameters>(); SysParamsWhereInit = new HashSet<SystemParameters>(); SysParamsWherePN = new HashSet<SystemParameters>(); SysParamsWhereON = new HashSet<SystemParameters>(); } [Key] [Column("ID")] [Index("IX_NAME_T_ID")] public Guid Id { get; set; } [Required] [StringLength(128)] [Column("NAME")] public string Name { get; set; } [Column("SYS")] public short IsSystem { get; set; } [Column("UNIQ")] public short IsUnique { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Name> Names { get; set; } public virtual ICollection<SystemParameters> SysParamsWhereFN {get; set;} public virtual ICollection<SystemParameters> SysParamsWhereLN { get; set; } public virtual ICollection<SystemParameters> SysParamsWhereSuff { get; set; } public virtual ICollection<SystemParameters> SysParamsWherePref { get; set; } public virtual ICollection<SystemParameters> SysParamsWhereInit { get; set; } public virtual ICollection<SystemParameters> SysParamsWherePN { get; set; } public virtual ICollection<SystemParameters> SysParamsWhereON { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CastRod : MonoBehaviour { public GameObject bait; public float hookSpeed; public Transform hookPoint; Vector2 direction; public LineRenderer fishingLine; GameObject fishTarget; GameObject logTarget; public SpringJoint2D springJnt; // Start is called before the first frame update void Start() { fishingLine.enabled = false; springJnt.enabled = false; } // Update is called once per frame void Update() { Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); direction = mousePos - (Vector2)transform.position; FaceMouse(); if (Input.GetMouseButtonDown(0)) { // cast fishing line when mouse button clicked Cast(); } if(fishTarget != null) { fishingLine.SetPosition(0, hookPoint.position); fishingLine.SetPosition(1, fishTarget.transform.position); } if (Input.GetKeyDown(KeyCode.Space)) { Release(); } } void FaceMouse() { transform.right = direction; } void Cast() { GameObject baitInstance = Instantiate(bait, hookPoint.position, Quaternion.identity); baitInstance.GetComponent<Rigidbody2D>().AddForce(transform.right * hookSpeed); } public void FishHit(GameObject hit) { fishTarget = hit; fishingLine.enabled = true; springJnt.enabled = true; springJnt.connectedBody = fishTarget.GetComponent<Rigidbody2D>(); } public void LogHit(GameObject hit) { logTarget = hit; fishingLine.enabled = false; springJnt.enabled = false; } void Release() { fishingLine.enabled = false; springJnt.enabled = false; fishTarget = null; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FerryTerminal { class GasVehicle : Vehicle, IGasUser { public int GasPercent { get; set; } public GasVehicle(VehicleType vehicleType) : base(vehicleType) { GasPercent = RandomPercent(); } public static GasVehicle GetNewInstance(VehicleType vehicleType) { return new GasVehicle(vehicleType); } public bool NeedsRefill() { return GasPercent <= 10; } } }
using Microsoft.Practices.Unity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VendingMachine.Events; using VendingMachine.Interfaces; namespace VendingMachine { class Program { static void Main(string[] args) { IUnityContainer container = DependencyContainer.Configure(); IVendingMachineWorkflow workflow = container.Resolve<IVendingMachineWorkflow>(); IEventBus eventBus = container.Resolve<IEventBus>(); eventBus.RegisterListener(workflow as IEventListener<PaymentTakenWithChangeEvent>); eventBus.RegisterListener(workflow as IEventListener<PaymentTakenEvent>); eventBus.RegisterListener(workflow as IEventListener<VendingProcessRestartingEvent>); eventBus.RegisterListener(workflow as IEventListener<VendingProcessStartingEvent>); eventBus.RegisterListener(workflow as IEventListener<ProductAvailableEvent>); eventBus.RegisterListener(workflow as IEventListener<ProductOutOfStockEvent>); workflow.Begin(); } } }
using System; using System.Collections.Generic; using System.Text; namespace TheSharkGame.Monsters { class MagicalWhaleShark : Sharks { public MagicalWhaleShark() { base.Name = "Magical Whale Shark"; base.Hp = 8; base.FirstAtk = "You say it is quite late in the game for a Magical Whale Shark to appear. " + "\n You fool. The Magical Whale Shark is never late. Nor is he early. " + "\n You are wrong. Dead wrong. Simple as that."; base.FirstDmg = 1; base.SecondAtk = "The Magical Whale Shark pulls a rabbit out of his hat. " + "\n Wow, how did he do that? While you are not looking, he steals your watch."; base.SecondDmg = 2; base.ThirdAtk = "The Magical Whale Shark tries a waterfall attack. Hey, we're below the surface. It has no effect."; base.ThirdDmg = 0; base.GiveExp = 5; } } }
using System.Threading.Tasks; using Meziantou.Analyzer.Rules; using TestHelper; using Xunit; namespace Meziantou.Analyzer.Test.Rules; public sealed class FileNameMustMatchTypeNameAnalyzerTests { private static ProjectBuilder CreateProjectBuilder() { return new ProjectBuilder() .WithAnalyzer<FileNameMustMatchTypeNameAnalyzer>(); } [Fact] public async Task DoesNotMatchFileName() { await CreateProjectBuilder() .WithSourceCode(@" class [||]Sample { }") .ValidateAsync(); } [Fact] public async Task DoesMatchFileNameBeforeDot() { await CreateProjectBuilder() .WithSourceCode("Sample.xaml.cs", @" class Sample { }") .ValidateAsync(); } [Fact] public async Task DoesMatchFileName() { await CreateProjectBuilder() .WithSourceCode(@" class Test0 { }") .ValidateAsync(); } [Fact] public async Task DoesMatchFileName_Generic() { await CreateProjectBuilder() .WithSourceCode(@" class Test0<T> { }") .ValidateAsync(); } [Fact] public async Task DoesMatchFileName_GenericUsingArity() { await CreateProjectBuilder() .WithSourceCode(fileName: "Test0`1.cs", @" class Test0<T> { }") .ValidateAsync(); } [Fact] public async Task DoesMatchFileName_GenericUsingOfT() { await CreateProjectBuilder() .WithSourceCode(fileName: "Test0OfT.cs", @" class Test0<T> { }") .ValidateAsync(); } [Fact] public async Task NestedTypeDoesMatchFileName_Ok() { await CreateProjectBuilder() .WithSourceCode(fileName: "Test0.cs", @" class Test0 { class Test1 { } }") .ValidateAsync(); } [Fact] public async Task Brackets_MatchType() { await CreateProjectBuilder() .WithSourceCode(fileName: "Test0{T}.cs", @" class Test0<T> { }") .ValidateAsync(); } [Fact] public async Task Brackets_MatchTypes() { await CreateProjectBuilder() .WithSourceCode(fileName: "Test0{TKey,TValue}.cs", @" class Test0<TKey, TValue> { }") .ValidateAsync(); } [Fact] public async Task Brackets_DoesNotMatchTypeCount() { await CreateProjectBuilder() .WithSourceCode(fileName: "Test0{TKey}.cs", @" class [||]Test0<TKey, TValue> { }") .ValidateAsync(); } [Fact] public async Task Brackets_DoesNotMatchTypeName() { await CreateProjectBuilder() .WithSourceCode(fileName: "Test0{TKey,TNotSame}.cs", @" class [||]Test0<TKey, TValue> { }") .ValidateAsync(); } #if ROSLYN_4_4_OR_GREATER [Fact] public async Task FileLocalTypes() { await CreateProjectBuilder() .WithSourceCode(fileName: "Dummy.cs", @" class Dummy { } file class Sample { } ") .ValidateAsync(); } [Fact] public async Task FileLocalTypes_Configuration() { await CreateProjectBuilder() .WithSourceCode(fileName: "Dummy.cs", @" class Dummy { } file class [||]Sample { } ") .AddAnalyzerConfiguration("MA0048.exclude_file_local_types", "false") .ValidateAsync(); } #endif }
using System; using System.Configuration; using System.DirectoryServices; using System.Reflection; using System.Web.Mvc; using log4net; using NBTM.Repository.Models; using NBTM.ViewModels; using NBTM.Logic; using NBTM.Repository; namespace NBTM.Controllers { #if !DEBUG [Authorize(Roles = "SalesAppAccountExecutives,SalesAppAdmins")] #endif public class HomeController : BaseController { private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #region Home Page Grids and all public ActionResult Index() { var url = Request.ApplicationPath; var uri = Request.Url.Host; //LoadLists(); // AD Access is quite slow so these lists will need to be built different. // DXCOMMENT: Pass a data model for GridView var model = new ProjectViewModel.Project(); var myDomain = ConfigurationManager.AppSettings["DomainName"]; var myUser = User.Identity.Name; // Currently logged in AD user. myUser = myUser.Replace(myDomain, ""); ViewBag.UserName = myUser; return View(model); } public ActionResult _ProjectsGridViewPartial() { var data = new ProjectViewModel.Project().CurrentProjects; return PartialView("_ProjectsGridViewPartial", data); } public ActionResult _ProjectDetailsGridViewPartial(ProjectViewModel.Project model) { ViewData["ProjectId"] = model.ProjectId; var data = model.CurrentActivityLogEntries; return PartialView("_ProjectDetailsGridViewPartial", data); } public ActionResult _ClosurePopuPartial() { return PartialView("_ClosurePopupPartial"); } public ActionResult _StatusUpdatePopupPartial(ProjectViewModel.Project model, Guid projectId) { int currentStatusId; using (var uow = new UnitOfWork()) { var project = uow.ProjectRepository.GetById(projectId); currentStatusId = project.ProjectStatusId; } ViewBag.ProjectStautses = LookupListLogic.ProjectStatuses(currentStatusId); var fullModel = ProjectLogic.CurrentProject(model.ProjectId, UserContext); return PartialView("_StatusUpdatePopupPartial", fullModel); } [HttpPost] public ActionResult _UpdateProjectStatus(ProjectViewModel.Project model) { var result = model.ProjectStatusId; return Json(result, JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult _OpenSuspendedProject(ProjectViewModel.Project model) { //Note that this is a bit of a hack as we don't have a dialog box to open //a suspended project. model.ReOpenReason = "In-flight re-open"; model.ReOpenExplanation = "In-flight re-open"; var result = ProjectLogic.OpenProject(model, UserContext); return Json(result, JsonRequestBehavior.AllowGet); } // Populate popup public ActionResult _SuspendPopupPartial(ProjectViewModel.Project model) { var fullModel = ProjectLogic.CurrentProject(model.ProjectId, UserContext); return PartialView("_SuspendPopupPartial", fullModel); } public ActionResult _TerminatePopupPartial(ProjectViewModel.Project model) { var fullModel = ProjectLogic.CurrentProject(model.ProjectId, UserContext); return PartialView("_TerminatePopupPartial", fullModel); } public ActionResult _ClosurePopupPartial(ProjectViewModel.Project model) { var fullModel = ProjectLogic.CurrentProject(model.ProjectId, UserContext); return PartialView("_ClosurePopupPartial", fullModel); } [HttpPost] public ActionResult _ConfirmComplete(ProjectViewModel.Project model) { var result = ProjectLogic.CloseProject(model, UserContext); return Json(result, JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult _ConfirmSuspend(ProjectViewModel.Project model) { var result = ProjectLogic.SuspendProject(model, UserContext); return Json(result, JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult _ConfirmTerminate(ProjectViewModel.Project model) { var result = ProjectLogic.TerminateProject(model, UserContext); return Json(result, JsonRequestBehavior.AllowGet); } #endregion #region Add/Edit Project /// <summary> /// Loads Lists for GUI dropdown /// </summary> private void LoadLists() { ViewBag.DevTypes = LookupListLogic.DevelopmentTypes; ViewBag.NrnSegments = LookupListLogic.NRNSegments; ViewBag.ExistingCustomers = LookupListLogic.ExistingCustomers; ViewBag.CustomerClassifications = LookupListLogic.CustomerClassifications; ViewBag.CapacityTypes = LookupListLogic.CapacityTypes; ViewBag.MarginClassifications = LookupListLogic.MarginClassifications; ViewBag.VolumeClassifications = LookupListLogic.VolumeClassifications; // TODO: These need some performance enhancements (this project currently a prototype) ViewBag.SalesLeads = LookupListLogic.SalesLeads; ViewBag.GMTSponsors = LookupListLogic.GMTSponsors; ViewBag.RDLeads = LookupListLogic.RDLeads; ViewBag.ProjectStautses = LookupListLogic.ProjectStatuses(2); } public ActionResult AddEdit(Guid? id) { LoadLists(); if (id != null) { var model = ProjectLogic.CurrentProject((Guid)id, UserContext); ViewData["projectId"] = model.ProjectId; return View(model); } else { var model = new ProjectViewModel.Project {GmtSponsorName = "(none)"}; return View(model); } } [HttpPost] public ActionResult AddEdit(ProjectViewModel.Project model) { ViewData["projectId"] = model.ProjectId; ProjectLogic.SaveProject(model, UserContext); LoadLists(); return View(model); } public string _NewCustomerPartial(string customerName, string nrnSegment) { try { if (string.IsNullOrEmpty(customerName)) { return "ERROR: Customer Name Required."; } if (string.IsNullOrEmpty(nrnSegment)) { return "ERROR: NRN Segment Required."; } using (uow) { // New Customer customerName = customerName.Trim(); nrnSegment = nrnSegment.Trim(); // Run stored proc to update production data. var proc = new SalesApp1Entities().Append_Customer(customerName, nrnSegment); } return "OK"; } catch (Exception ex) { return "ERROR: Check Stored Procedure. " + ex.Message; } } public ActionResult _CustomerComboboxPartial() { ViewBag.ExistingCustomers = LookupListLogic.ExistingCustomers; var model = new ProjectViewModel.Project { }; return PartialView("_CustomerComboboxPartial", model); } #endregion #region Samples public ActionResult _SamplesGridViewPartial(ProjectViewModel.Project model) { ViewData["projectId"] = model.ProjectId; var data = new ProjectViewModel.Project() { ProjectId = model.ProjectId }.CurrentSampleEntries; return PartialView("_SamplesGridViewPartial", data); } [HttpPost] public ActionResult _SamplesPopupPartial(ProjectViewModel.Project model) { ViewData["projectId"] = model.ProjectId; var newModel = SampleLogLogic.CurrentSampleLogEntry(model.SampleEntryId); return PartialView("_SamplesPopupPartial", newModel); } [HttpPost] public ActionResult _SaveSample(LogViewModel.SampleLogEntry model) { try { var freshModel = SampleLogLogic.SaveSampleLogEntry(model, UserContext); return Json(freshModel.ModelMessage, JsonRequestBehavior.AllowGet); } catch (Exception ex) { Logger.Error("Save Sample Error", ex); throw; } } #endregion /// <summary> /// Support Page -- Currently Empty /// </summary> /// <returns></returns> public ActionResult Support() { return View(); } } } public enum HeaderViewRenderMode { Full, Menu, Title }
using System; using System.Collections.Generic; using System.Linq; namespace PICSimulator.Model.Commands { public class BinaryFormatParser { private Dictionary<char, uint> Parameter; private BinaryFormatParser(Dictionary<char, uint> pms) { Parameter = pms; } public uint? GetParam(char c) { if (Parameter.ContainsKey(c)) { return Parameter[c]; } else { return null; } } public bool? GetBoolParam(char c) { if (Parameter.ContainsKey(c)) { return Parameter[c] != 0; } else { return null; } } public static BinaryFormatParser Parse(string fmt, uint val) { string format = fmt.Replace(" ", String.Empty); string value = Convert.ToString(val, 2); if (value.Length > format.Length) return null; while (format.Length > value.Length) value = "0" + value; Dictionary<char, string> parameter_str = new Dictionary<char, string>(); for (int i = 0; i < format.Length; i++) { if (format[i] == '0' || format[i] == '1') { if (format[i] == value[i]) continue; else return null; } else if (format[i] == 'x') { continue; } else { if (parameter_str.ContainsKey(format[i])) { parameter_str[format[i]] += value[i]; } else { parameter_str[format[i]] = "" + value[i]; } } } Dictionary<char, uint> parameter = new Dictionary<char, uint>(); parameter_str.Select(p => new KeyValuePair<char, uint>(p.Key, Convert.ToUInt32(p.Value, 2))).ToList().ForEach(p => parameter.Add(p.Key, p.Value)); return new BinaryFormatParser(parameter); } public static bool TryParse(string fmt, uint val) { return Parse(fmt, val) != null; } } }
using System.ComponentModel.DataAnnotations; namespace Lotto.Models { //result = { // "totSellamnt": 88465183000, //총판매금액 // "returnValue": "success", // "drwNoDate": "2020-01-18", // "firstWinamnt": 2377935959, // "drwtNo6": 43, // "drwtNo4": 40, // "firstPrzwnerCo": 9, //1등당첨인원수 // "drwtNo5": 41, // "bnusNo": 45, // "firstAccumamnt": 21401423631, //1등 당첨금액 // "drwNo": 894, // "drwtNo2": 32, // "drwtNo3": 37, // "drwtNo1": 19 //} public class Lotto_History { public int ID { get; set; } [Display(Name = "회차")] public int seqNo { get; set; } [Display(Name = "1번째 번호")] public int num1 { get; set; } [Display(Name = "2번째 번호")] public int num2 { get; set; } [Display(Name = "3번째 번호")] public int num3 { get; set; } [Display(Name = "4번째 번호")] public int num4 { get; set; } [Display(Name = "5번째 번호")] public int num5 { get; set; } [Display(Name = "6번째 번호")] public int num6 { get; set; } [Display(Name = "+ 보너스")] public int bonus { get; set; } public decimal firstPriceTotal { get; set; } public int firstPriceSelected { get; set; } public decimal eachReceivedFirstPrice { get; set; } public string drawDate { get; set; } } public class Numbers_NCounts { [Display(Name = "SeqNo")] public int ID { get; set; } [Display(Name = "번호")] public int numbers { get; set; } [Display(Name = "횟수")] public int nCounts { get; set; } } public class Two_Numbers { public float Num1 { get; set; } public float Num2 { get; set; } } public class Target_Number { public int targetNumber { get; set; } public int targetNumberCount { get; set; } } public class Target_Numbers { public int targetNumber1 { get; set; } public int targetNumberCount1 { get; set; } public int targetNumber2 { get; set; } public int targetNumberCount2 { get; set; } public int targetNumber3 { get; set; } public int targetNumberCount3 { get; set; } public int targetNumber4 { get; set; } public int targetNumberCount4 { get; set; } public int targetNumber5 { get; set; } public int targetNumberCount5 { get; set; } public int targetNumber6 { get; set; } public int targetNumberCount6 { get; set; } public int targetNumber7 { get; set; } public int targetNumberCount7 { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using CAR_Web_Project.Entity; namespace CAR_Web_Project.Page { public partial class CARDetails : System.Web.UI.Page { protected Bug bug = new Bug(); protected void Page_Load(object sender, EventArgs e) { if (Request.Params["id"] == null || Request.Params["id"] == "") return; bug = Bug.Get_ByID(Int32.Parse(Request.Params["id"])); Label_ID.Text = bug.ID.ToString(); Label_Title.Text = bug.Title; Entity.User Owner = Entity.User.Get_ByID(bug.OwnerID); Label_Owner.Text = Owner.Username; Entity.User Validator = Entity.User.Get_ByID(bug.ValidatorID); Label_Validator.Text = Validator.Username; TextBox_Reproduce.Text = bug.Reproduce; if (Owner.Equals(Session["user"])) { Button_Modify.Visible = false; Label_Owner.Visible = false; } else if (Validator.Equals(Session["user"])) { Label_Validator.Visible = false; } else Response.Redirect("~/Page/Login.aspx"); } } }
using Newtonsoft.Json; namespace Lykke.Service.SmsSender.Services.SmsSenders.Twilio { public class TwilioErrorResponse { public string Status { get; set; } public string Code { get; set; } public string Message { get; set; } [JsonProperty("more_info")] public string MoreInfo { get; set; } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Application.Data.Migrations { public partial class init : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Address", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Flat = table.Column<string>(nullable: true), Street = table.Column<string>(nullable: true), Postcode = table.Column<string>(nullable: true), City = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Address", x => x.Id); }); migrationBuilder.CreateTable( name: "Game", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Opposition = table.Column<string>(nullable: true), Date = table.Column<DateTime>(nullable: false), KO = table.Column<DateTime>(nullable: false), Location = table.Column<int>(nullable: false), Result = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Game", x => x.Id); }); migrationBuilder.CreateTable( name: "Skill", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Name = table.Column<string>(nullable: true), Type = table.Column<int>(nullable: false), ParentId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Skill", x => x.Id); table.ForeignKey( name: "FK_Skill_Skill_ParentId", column: x => x.ParentId, principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Members", columns: table => new { SRU = table.Column<string>(nullable: false), Type = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: true), Surname = table.Column<string>(nullable: true), Email = table.Column<string>(nullable: true), Phone = table.Column<string>(nullable: true), Mobile = table.Column<string>(nullable: true), Active = table.Column<bool>(nullable: false), AddressId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Members", x => x.SRU); table.ForeignKey( name: "FK_Members_Address_AddressId", column: x => x.AddressId, principalTable: "Address", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Scores", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Half = table.Column<int>(nullable: false), Time = table.Column<DateTime>(nullable: false), Points = table.Column<int>(nullable: false), Team = table.Column<int>(nullable: false), Comment = table.Column<string>(nullable: true), GameId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Scores", x => x.Id); table.ForeignKey( name: "FK_Scores_Game_GameId", column: x => x.GameId, principalTable: "Game", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Player", columns: table => new { SRU = table.Column<string>(nullable: false), Position = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Player", x => x.SRU); table.ForeignKey( name: "FK_Player_Members_SRU", column: x => x.SRU, principalTable: "Members", principalColumn: "SRU", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Training", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Date = table.Column<DateTime>(nullable: false), Time = table.Column<DateTime>(nullable: false), Location = table.Column<string>(nullable: true), CoachSRU = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Training", x => x.Id); table.ForeignKey( name: "FK_Training_Members_CoachSRU", column: x => x.CoachSRU, principalTable: "Members", principalColumn: "SRU", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Doctor", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Name = table.Column<string>(nullable: true), Surname = table.Column<string>(nullable: true), Phone = table.Column<string>(nullable: true), PlayerSRU = table.Column<string>(nullable: true), AddressId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Doctor", x => x.Id); table.ForeignKey( name: "FK_Doctor_Address_AddressId", column: x => x.AddressId, principalTable: "Address", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Doctor_Player_PlayerSRU", column: x => x.PlayerSRU, principalTable: "Player", principalColumn: "SRU", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "HealthIssues", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Name = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), Date = table.Column<DateTime>(nullable: false), PlayerSRU = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_HealthIssues", x => x.Id); table.ForeignKey( name: "FK_HealthIssues_Player_PlayerSRU", column: x => x.PlayerSRU, principalTable: "Player", principalColumn: "SRU", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Junior", columns: table => new { SRU = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Junior", x => x.SRU); table.ForeignKey( name: "FK_Junior_Player_SRU", column: x => x.SRU, principalTable: "Player", principalColumn: "SRU", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Profile", columns: table => new { PlayerSRU = table.Column<string>(nullable: false), SkillId = table.Column<int>(nullable: false), Description = table.Column<string>(nullable: true), Score = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Profile", x => new { x.PlayerSRU, x.SkillId }); table.ForeignKey( name: "FK_Profile_Player_PlayerSRU", column: x => x.PlayerSRU, principalTable: "Player", principalColumn: "SRU", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Profile_Skill_SkillId", column: x => x.SkillId, principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Senior", columns: table => new { SRU = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Senior", x => x.SRU); table.ForeignKey( name: "FK_Senior_Player_SRU", column: x => x.SRU, principalTable: "Player", principalColumn: "SRU", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Activities", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Name = table.Column<string>(nullable: true), TrainingId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Activities", x => x.Id); table.ForeignKey( name: "FK_Activities_Training_TrainingId", column: x => x.TrainingId, principalTable: "Training", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Attendance", columns: table => new { Id = table.Column<string>(nullable: false), TrainingId = table.Column<int>(nullable: false), PlayerSRU = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Attendance", x => x.Id); table.UniqueConstraint("AK_Attendance_PlayerSRU_TrainingId", x => new { x.PlayerSRU, x.TrainingId }); table.ForeignKey( name: "FK_Attendance_Player_PlayerSRU", column: x => x.PlayerSRU, principalTable: "Player", principalColumn: "SRU", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Attendance_Training_TrainingId", column: x => x.TrainingId, principalTable: "Training", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Guardians", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Name = table.Column<string>(nullable: true), Surname = table.Column<string>(nullable: true), Phone = table.Column<string>(nullable: true), Relationship = table.Column<string>(nullable: true), Signature = table.Column<DateTime>(nullable: false), JuniorId = table.Column<string>(nullable: true), AddressId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Guardians", x => x.Id); table.ForeignKey( name: "FK_Guardians_Address_AddressId", column: x => x.AddressId, principalTable: "Address", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Guardians_Junior_JuniorId", column: x => x.JuniorId, principalTable: "Junior", principalColumn: "SRU", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Kin", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), SeniorSRU = table.Column<string>(nullable: true), AddressId = table.Column<int>(nullable: false), Name = table.Column<string>(nullable: true), Surname = table.Column<string>(nullable: true), Phone = table.Column<string>(nullable: true), Relationship = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Kin", x => x.Id); table.ForeignKey( name: "FK_Kin_Address_AddressId", column: x => x.AddressId, principalTable: "Address", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Kin_Senior_SeniorSRU", column: x => x.SeniorSRU, principalTable: "Senior", principalColumn: "SRU", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Activities_TrainingId", table: "Activities", column: "TrainingId"); migrationBuilder.CreateIndex( name: "IX_Attendance_TrainingId", table: "Attendance", column: "TrainingId"); migrationBuilder.CreateIndex( name: "IX_Doctor_AddressId", table: "Doctor", column: "AddressId", unique: true); migrationBuilder.CreateIndex( name: "IX_Doctor_PlayerSRU", table: "Doctor", column: "PlayerSRU", unique: true); migrationBuilder.CreateIndex( name: "IX_Guardians_AddressId", table: "Guardians", column: "AddressId", unique: true); migrationBuilder.CreateIndex( name: "IX_Guardians_JuniorId", table: "Guardians", column: "JuniorId"); migrationBuilder.CreateIndex( name: "IX_HealthIssues_PlayerSRU", table: "HealthIssues", column: "PlayerSRU"); migrationBuilder.CreateIndex( name: "IX_Kin_AddressId", table: "Kin", column: "AddressId", unique: true); migrationBuilder.CreateIndex( name: "IX_Kin_SeniorSRU", table: "Kin", column: "SeniorSRU", unique: true); migrationBuilder.CreateIndex( name: "IX_Members_AddressId", table: "Members", column: "AddressId", unique: true); migrationBuilder.CreateIndex( name: "IX_Profile_PlayerSRU", table: "Profile", column: "PlayerSRU"); migrationBuilder.CreateIndex( name: "IX_Profile_SkillId", table: "Profile", column: "SkillId"); migrationBuilder.CreateIndex( name: "IX_Scores_GameId", table: "Scores", column: "GameId"); migrationBuilder.CreateIndex( name: "IX_Skill_ParentId", table: "Skill", column: "ParentId"); migrationBuilder.CreateIndex( name: "IX_Training_CoachSRU", table: "Training", column: "CoachSRU"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Activities"); migrationBuilder.DropTable( name: "Attendance"); migrationBuilder.DropTable( name: "Doctor"); migrationBuilder.DropTable( name: "Guardians"); migrationBuilder.DropTable( name: "HealthIssues"); migrationBuilder.DropTable( name: "Kin"); migrationBuilder.DropTable( name: "Profile"); migrationBuilder.DropTable( name: "Scores"); migrationBuilder.DropTable( name: "Training"); migrationBuilder.DropTable( name: "Junior"); migrationBuilder.DropTable( name: "Senior"); migrationBuilder.DropTable( name: "Skill"); migrationBuilder.DropTable( name: "Game"); migrationBuilder.DropTable( name: "Player"); migrationBuilder.DropTable( name: "Members"); migrationBuilder.DropTable( name: "Address"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using Microsoft.AspNet.SignalR; using ttmControlServer.Models; using Newtonsoft.Json; namespace ttmControlServer.SignalR { public class ttmHub : Hub { public enum interactiveState { sidle = 0, sInteractiveCountdown, sInteractiveStart, sInteractiveResult } const int _cFinishNum = 2; public static int _mode = 0; //0:idle + DJ, 1:interactive public static interactiveState _state = interactiveState.sidle; public static string _hostID = ""; public static string _backendID = ""; public static serverData _serverData = new serverData(); public ttmHub() { if(!_serverData.isInit) { _serverData.init(); } } #region Override public override Task OnDisconnected(bool stopCalled) { if(Context.ConnectionId == _hostID) { _hostID = ""; Clients.All.hostIsDisconnected(); } return base.OnDisconnected(stopCalled); } #endregion #region Unity Host public int registerHost() { _hostID = Context.ConnectionId; Clients.All.hostIsConnected(); return _mode; } public string getNextIdleMsg() { if(_hostID != Context.ConnectionId) { return ""; } return _serverData.getNextIdleMsg(); } public string heartBeat() { if (_hostID != Context.ConnectionId) { return ""; } return string.Format("HearBeat@{0:mm:ss}", DateTime.Now); } #endregion #region Backend public string registerBackend() { _backendID = Context.ConnectionId; response r = new response(); r.active = "registerBackend"; r.result = true; r.index = _mode; r.data = _hostID; var repJson = JsonConvert.SerializeObject(r); return repJson; } public string setMode(int mode) { response r = new response(); r.active = "setMode"; if (_backendID != Context.ConnectionId || _hostID == "") { r.result = false; r.msg = "Wrong connection Id"; } else if(mode != 0 && mode != 1) { r.result = false; r.msg = "Wrong Mode"; } else { _mode = mode; Clients.Client(_hostID).setMode(_mode); r.result = true; } var repJson = JsonConvert.SerializeObject(r); return repJson; } #region DJ Mode public void setDJGreetingMsg(string msg) { if (_backendID != Context.ConnectionId) { return; } if (_hostID != "") { Clients.Client(_hostID).setDJGreetingMsg(msg); } } public void setDJMsg(string msg, int finishId) { if (_backendID != Context.ConnectionId) { return; } if (_hostID != "") { var fid = Math.Min(Math.Max(finishId, 0), _cFinishNum); Clients.Client(_hostID).setDJMsg(msg, fid); } } public void setDJCancal() { if (_backendID != Context.ConnectionId) { return; } if (_hostID != "") { Clients.Client(_hostID).setDJCancal(); } } public string getIdleMsg() { response r = new response(); r.data = _serverData.getAllIdleMsg(); r.result = true; var repJson = JsonConvert.SerializeObject(r); return repJson; } public void updateIdleMsg(string msgSet) { List<serverData.idleMsgData> idleList = JsonConvert.DeserializeObject<List<serverData.idleMsgData>>(msgSet); _serverData.updateIdleMsg(ref idleList); } public string getDJType() { response r = new response(); r.data = _serverData.getDJType(); r.result = true; var repJson = JsonConvert.SerializeObject(r); return repJson; } public string getDJMsg() { response r = new response(); r.data = _serverData.getAllDJMsg(); r.result = true; var repJson = JsonConvert.SerializeObject(r); return repJson; } #endregion #region Interactive Mode public void setCheckerBoard() { if (_backendID != Context.ConnectionId) { return; } if (_hostID != "") { Clients.Client(_hostID).setCheckerBoard(); } } public void setAllWhite() { if (_backendID != Context.ConnectionId) { return; } if (_hostID != "") { Clients.Client(_hostID).setAllWhite(); } } public void readyQuestion() { if (_backendID != Context.ConnectionId) { return; } if (_hostID != "") { Clients.Client(_hostID).readyQuestion(); _state = interactiveState.sInteractiveCountdown; } } public void setAnswer(int idx, string ans) { if (_backendID != Context.ConnectionId) { return; } if (_hostID != "") { Clients.Client(_hostID).setAnswer(idx, ans); } } public void showAnswer(int qid) { if (_backendID != Context.ConnectionId) { return; } if (_hostID != "") { Clients.Client(_hostID).showAnswer(qid); } } public void showCode(int codeId, float t) { if (_backendID != Context.ConnectionId) { return; } if (_hostID != "") { Clients.Client(_hostID).showCode(codeId, t); } } #endregion #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shop { public class ProductsList { public static List<ProductsList> prodList = new List<ProductsList>(); public int id { get; set; } public string name { get; set; } public double price { get; set; } public string description { get; set; } public int ammount { get; set; } public string category { get; set; } public string nameProducer { get; set; } public ProductsList(int i, string n, double p, string d, int a, string c, string np) { id = i; name = n; price = p; description = d; ammount = a; category = c; nameProducer = np; } } }
using System; using ProjetBdd; namespace ConsoleApp.ExistingDb { class Program { static void Main(string[] args) { using (var db = new AirAtlantiqueEntities()) { Console.WriteLine(db.Warehouse); db.Airport.Add(new Airport { id = 10, id_City = 10, Name = "John F. Kennedy", Code_AITA = "JFK" }); Console.WriteLine(db.Airport); Console.ReadKey(); db.Billet.Add(new Billet { id = 10, id_Passenger = 10, id_Price = 10, id_Trip = 10 }); Console.WriteLine(db.Billet); Console.ReadKey(); db.BilletGP.Add(new BilletGP { id = 10, id_Flight = 10, id_Passenger = 10, id_Salaried = 10, Price = 150 }); Console.WriteLine(db.BilletGP); Console.ReadKey(); db.City.Add(new City { id = 10, Name = "New York" }); Console.WriteLine(db.City); Console.ReadKey(); db.Classes.Add(new Classes { id = 10, Prem = "Premiere", Eco_Prem = "EcoPremieres", Eco = "Economique", Business = "Business" }); Console.WriteLine(db.Classes); Console.ReadKey(); db.Flight.Add(new Flight { id = 10, id_Airport_Start = 10, id_Airport_End = 1, id_Airport_End_Real = 1, Hours_Departure = DateTime.Now, Hours_Arrival = DateTime.Today, Hours_Lift_OFF = DateTime.Now, Hours_Landing = DateTime.Today }); Console.WriteLine(db.Flight); Console.ReadKey(); db.Incident.Add(new Incident { id = 10, id_Plane = 10, id_Salaried = 10, Severity = 8, Comment = "Trou dans la cabine de pilotage", Date = DateTime.Now }); Console.WriteLine(db.Incident); Console.ReadKey(); db.Luggage.Add(new Luggage { id = 10, id_Flight = 10, id_Billet = 10, Weight = 20 }); Console.WriteLine(db.Luggage); Console.ReadKey(); db.Maintenance.Add(new Maintenance { id = 10, id_Incident = 10, id_Warehouse = 10, Date_Start = DateTime.Now, Date_End = DateTime.Today, Description = "Trou dans la carlingue", Place = "New Yrok" }); Console.WriteLine(db.Maintenance); Console.ReadKey(); db.Passenger.Add(new Passenger { id = 10, First_Name = "Antoine", Name = "Mazoyer", Mail_Address = "a.mazoyer@gmail.com" }); Console.WriteLine(db.Passenger); Console.ReadKey(); db.Plane.Add(new Plane { id = 10, id_Type=10, id_Warehouse=10, Status=false, Rent=true }); Console.WriteLine(db.Plane); Console.ReadKey(); db.Price.Add(new Price { id = 10, id_Trip=10, id_Classes=10, id_TypePrice=10, Prix=200, Date=DateTime.Today }); Console.WriteLine(db.Price); Console.ReadKey(); db.Salaried.Add(new Salaried { id = 10, id_Airport=10, id_Speciality=10, Name="Janio", First_Name="Mathieu", Registration_Number=10, Availability=true, Date_Birth=DateTime.Parse("10/08/2005"), Date_Hiring=DateTime.Now, Nationality="Mexicain", License=true }); Console.WriteLine(db.Salaried); Console.ReadKey(); db.Speciality.Add(new Speciality { id = 10, Entitled="Pilote", Description="10ans d'expérience dans les longs courriers" }); Console.WriteLine(db.Speciality); Console.ReadKey(); db.Ticket_Boarding.Add(new Ticket_Boarding { id = 10, id_Flight=10, id_Billet=10, id_BilletGP=10, Number=1010 }); Console.WriteLine(db.Ticket_Boarding); Console.ReadKey(); db.Trip.Add(new Trip { id = 10, Max_Weight=45 }); Console.WriteLine(db.Trip); Console.ReadKey(); db.TypePrice.Add(new TypePrice { id = 10, Child="Réduction pour les enfants de moins de 10ans", Reduce="15%", Norm="Le prix de base était de 150€" }); Console.WriteLine(db.TypePrice); Console.ReadKey(); db.Warehouse.Add(new Warehouse { id = 10, id_Airport=10, Name="Hangar New Yrokais", Available=true }); Console.WriteLine(db.Warehouse); Console.ReadKey(); Console.WriteLine("Ajout des données dans la base de donnée effectué avec succès ! "); Console.ReadKey(); db.SaveChanges(); } } } }
using AngleSharp.Parser.Html; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Timers; using Telegram.Bot; using Telegram.Bot.Types; namespace wbprice { class Program { //private static decimal price = 0; static void Main(string[] args) { var items = new List<WbItem>() { new WbItem { Url = $"", Id = 1, CharacteristicId = 1, Name = "1" } }; //Create a (re-usable) parser front-end var parser = new HtmlParser(); // Telegram bot settings var bot = new TelegramBotClient(""); List<int> recipients = new List<int>(); Timer timer = new Timer(15 * 60 * 1000); timer.Elapsed += async (sender, e) => await HandleTimer1(bot, recipients, parser, items, timer); timer.AutoReset = false; timer.Start(); Console.WriteLine("Press any key to exit... "); Console.ReadKey(); } private static async Task HandleTimer(TelegramBotClient bot, List<int> recipients, HtmlParser parser, List<WbItem> items, Timer timer) { try { foreach(var item in items) { Console.Write(">{0}", item.Url); //decimal price = 0; using (WebClient client = new WebClient()) // WebClient class inherits IDisposable { // get the file content without saving it: var data = await client.DownloadDataTaskAsync(new Uri(item.Url)); string html = System.Text.Encoding.UTF8.GetString(data); Console.Write("."); //Parse source to document var document = parser.Parse(html); Console.Write("."); //Do something with document like the following var priceElement = document.QuerySelectorAll("meta[itemprop=\"price\"]").FirstOrDefault(); var nameElement = document.QuerySelectorAll("h1[itemprop=\"name\"]").FirstOrDefault(); Console.Write("."); var culture = System.Globalization.CultureInfo.GetCultureInfo("be-BY"); decimal newPrice = 0; if (!string.IsNullOrEmpty(priceElement?.Attributes["content"]?.Value)) newPrice = Convert.ToDecimal(priceElement.Attributes["content"].Value, culture); item.Name = nameElement.TextContent.Trim('\n').Trim(); Console.Write(">{0}", newPrice); if (item.Price != -1 && newPrice != item.Price) { Console.Write(" !!! {0}", newPrice > item.Price ? "UP" : "DOWN"); int iconHex = newPrice == 0 ? 0x1f440 : item.Price == -1 ? 0x1f449 : newPrice > item.Price ? 0x1f44e : 0x1f44d; string priceText = newPrice == 0 ? "Out of stock" : string.Format("{0} -> {1}", item.Price <= 0 ? "..." : item.Price.ToString("c2", culture), newPrice.ToString("c2", culture)); string text = string.Format("{0}\n{1} {2}\n{3}", item.Name, char.ConvertFromUtf32(iconHex), priceText, item.Url); foreach (int recipient in recipients) await bot.SendTextMessageAsync(new ChatId(recipient), text); } item.Price = newPrice; Console.WriteLine(); } } } catch (Exception ex) { Console.WriteLine(); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } finally { timer.Start(); } } private static async Task HandleTimer1(TelegramBotClient bot, List<int> recipients, HtmlParser parser, List<WbItem> items, Timer timer) { try { foreach (var item in items) { Console.Write(">{0}", item.Url); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest"); string jsonStr = JsonConvert.SerializeObject(item); var content = new StringContent(jsonStr, Encoding.UTF8, "application/json"); var response = await client.PostAsync("https://www.example.com", content); var responseString = await response.Content.ReadAsStringAsync(); dynamic info = JsonConvert.DeserializeObject(responseString); Console.Write(">..."); var culture = System.Globalization.CultureInfo.GetCultureInfo("be-BY"); decimal newPrice = 0; if (info != null && info.Value != null && info.Value.promoInfo != null && info.Value.promoInfo.PriceWithCouponAndDiscount != 0) newPrice = Convert.ToDecimal(info.Value.promoInfo.PriceWithCouponAndDiscount / 10000m); Console.Write(">{0}", newPrice); if (item.Price != -1 && newPrice != item.Price) { Console.Write(" !!! {0}", newPrice > item.Price ? "UP" : "DOWN"); int iconHex = newPrice == 0 ? 0x1f440 : item.Price == -1 ? 0x1f449 : newPrice > item.Price ? 0x1f44e : 0x1f44d; string priceDelta = item.Price <= 0 ? "" : string.Format("({0})", (newPrice - item.Price).ToString("+c2", culture)); string priceText = newPrice == 0 ? "Out of stock" : string.Format("{0} -> {1} {2}", item.Price <= 0 ? "..." : item.Price.ToString("c2", culture), newPrice.ToString("c2", culture), priceDelta); string text = string.Format("{0}\n{1} {2}\n{3}", item.Name, char.ConvertFromUtf32(iconHex), priceText, item.Url); foreach (int recipient in recipients) await bot.SendTextMessageAsync(new ChatId(recipient), text); } item.Price = newPrice; Console.WriteLine(); } } } catch (Exception ex) { Console.WriteLine(); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } finally { timer.Start(); } } } public class WbItem { [JsonIgnore] public string Url { get; set; } [JsonIgnore] public decimal Price { get; set; } = -1; [JsonIgnore] public string Name { get; set; } [JsonProperty("cod1s")] public int Id { get; set; } [JsonProperty("characteristicId")] public int CharacteristicId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace SMSEntities.SMSDBEntities { public class VisitorCheckInOut { //`nricid``name``address``fromcompany``tocompany``telno``persontovisit``eventid``temp``visitortype` //`keys``passid``gateid``vehicleplatenumber``guardname``remarks``checkintime``checkouttime` public Int32 visitorid { get; set; } [Required] public string nricid { get; set; } public string fullnricid { get; set; } [Required] public string name { get; set; } public string address { get; set; } [Required] public string fromcompany { get; set; } public int tocompany { get; set; } //public string visitingcompany { get; set; } [Required] public string telno { get; set; } public string persontovisit { get; set; } public int eventid { get; set; } public int temp { get; set; } [Required] public int visitortypeID { get; set; } public int keyid { get; set; } [Required] public int passid { get; set; } [Required] public int gateid { get; set; } public string vehicleplatenumber { get; set; } [Required] public string guardname { get; set; } public string remarks { get; set; } public string txtPhone { get; set; } public string blockorphone { get; set; } public DateTime checkintime { get; set; } public DateTime checkouttime { get; set; } public string cotime { get; set; } public string snapshotpath { get; set; } public int deploymentid { get; set; } public string CompanyName { get; set; } public string EventName { get; set; } public string CompanyPhone { get; set; } public List<Companies> CompaniesList { get; set; } public List<VisitorTypes> VisitorTypesCol { get; set; } public string GateName { get; set; } public List<Gates> GatesList { get; set; } public List<KEYS> KeysList { get; set; } public List<Passes> PassesList { get; set; } public List<EventMaster> EventsList { get; set; } public string purpose { get; set; } public List<Purpose> PurposeList { get; set; } public int IsBlockGuest { get; set; } public string BlockType { get; set; } public string BlockRemarks { get; set; } public string NRICBack { get; set; } public string NRICFront { get; set; } public int BlockDays { get; set; } public Nullable<DateTime> BlockedDate { get; set; } public Nullable<DateTime> UnblockedDate { get; set; } public string strBlockedDate { get; set; } public string strUnblockedDate { get; set; } public List<BlockGuest> GetBlockGuestType() { List<BlockGuest> objItemStatusCol = new List<BlockGuest>(); objItemStatusCol.Add(new BlockGuest { BlockGuestId = 0, BlockGuestName = "No" }); objItemStatusCol.Add(new BlockGuest { BlockGuestId = 1, BlockGuestName = "Yes" }); return objItemStatusCol; } public List<Day> GetDays() { List<Day> objItemStatusCol = new List<Day>(); objItemStatusCol.Add(new Day { DayId = 1, DayNumber = "1" }); objItemStatusCol.Add(new Day { DayId = 2, DayNumber = "2" }); objItemStatusCol.Add(new Day { DayId = 3, DayNumber = "3" }); objItemStatusCol.Add(new Day { DayId = 4, DayNumber = "4" }); objItemStatusCol.Add(new Day { DayId = 5, DayNumber = "5" }); objItemStatusCol.Add(new Day { DayId = 6, DayNumber = "6" }); objItemStatusCol.Add(new Day { DayId = 7, DayNumber = "7" }); objItemStatusCol.Add(new Day { DayId = 8, DayNumber = "8" }); objItemStatusCol.Add(new Day { DayId = 9, DayNumber = "9" }); objItemStatusCol.Add(new Day { DayId = 10, DayNumber = "10" }); objItemStatusCol.Add(new Day { DayId = 11, DayNumber = "11" }); objItemStatusCol.Add(new Day { DayId = 12, DayNumber = "12" }); objItemStatusCol.Add(new Day { DayId = 13, DayNumber = "13" }); objItemStatusCol.Add(new Day { DayId = 14, DayNumber = "14" }); objItemStatusCol.Add(new Day { DayId = 15, DayNumber = "15" }); objItemStatusCol.Add(new Day { DayId = 16, DayNumber = "16" }); objItemStatusCol.Add(new Day { DayId = 17, DayNumber = "17" }); objItemStatusCol.Add(new Day { DayId = 18, DayNumber = "18" }); objItemStatusCol.Add(new Day { DayId = 19, DayNumber = "19" }); objItemStatusCol.Add(new Day { DayId = 20, DayNumber = "20" }); objItemStatusCol.Add(new Day { DayId = 21, DayNumber = "21" }); objItemStatusCol.Add(new Day { DayId = 22, DayNumber = "22" }); objItemStatusCol.Add(new Day { DayId = 23, DayNumber = "23" }); objItemStatusCol.Add(new Day { DayId = 24, DayNumber = "24" }); objItemStatusCol.Add(new Day { DayId = 25, DayNumber = "25" }); objItemStatusCol.Add(new Day { DayId = 26, DayNumber = "26" }); objItemStatusCol.Add(new Day { DayId = 27, DayNumber = "27" }); objItemStatusCol.Add(new Day { DayId = 28, DayNumber = "28" }); objItemStatusCol.Add(new Day { DayId = 29, DayNumber = "29" }); objItemStatusCol.Add(new Day { DayId = 30, DayNumber = "30" }); objItemStatusCol.Add(new Day { DayId = 31, DayNumber = "31" }); return objItemStatusCol; } public List<Month> GetMonths() { List<Month> objItemStatusCol = new List<Month>(); objItemStatusCol.Add(new Month { MonthId = 1, MonthName = "January" }); objItemStatusCol.Add(new Month { MonthId = 2, MonthName = "February" }); objItemStatusCol.Add(new Month { MonthId = 3, MonthName = "March" }); objItemStatusCol.Add(new Month { MonthId = 4, MonthName = "April" }); objItemStatusCol.Add(new Month { MonthId = 5, MonthName = "May" }); objItemStatusCol.Add(new Month { MonthId = 6, MonthName = "June" }); objItemStatusCol.Add(new Month { MonthId = 7, MonthName = "July" }); objItemStatusCol.Add(new Month { MonthId = 8, MonthName = "August" }); objItemStatusCol.Add(new Month { MonthId = 9, MonthName = "September" }); objItemStatusCol.Add(new Month { MonthId = 10, MonthName = "October" }); objItemStatusCol.Add(new Month { MonthId = 11, MonthName = "November" }); objItemStatusCol.Add(new Month { MonthId = 12, MonthName = "December" }); return objItemStatusCol; } public List<Year> GetYears() { List<Year> objItemStatusCol = new List<Year>(); objItemStatusCol.Add(new Year { YearId = 1, YearNumber = "2013" }); objItemStatusCol.Add(new Year { YearId = 2, YearNumber = "2014" }); objItemStatusCol.Add(new Year { YearId = 3, YearNumber = "2015" }); objItemStatusCol.Add(new Year { YearId = 4, YearNumber = "2016" }); objItemStatusCol.Add(new Year { YearId = 5, YearNumber = "2017" }); objItemStatusCol.Add(new Year { YearId = 6, YearNumber = "2018" }); objItemStatusCol.Add(new Year { YearId = 7, YearNumber = "2019" }); objItemStatusCol.Add(new Year { YearId = 8, YearNumber = "2020" }); objItemStatusCol.Add(new Year { YearId = 9, YearNumber = "2021" }); objItemStatusCol.Add(new Year { YearId = 10, YearNumber = "2022" }); objItemStatusCol.Add(new Year { YearId = 11, YearNumber = "2023" }); objItemStatusCol.Add(new Year { YearId = 12, YearNumber = "2024" }); objItemStatusCol.Add(new Year { YearId = 13, YearNumber = "2025" }); objItemStatusCol.Add(new Year { YearId = 14, YearNumber = "2026" }); objItemStatusCol.Add(new Year { YearId = 15, YearNumber = "2027" }); objItemStatusCol.Add(new Year { YearId = 16, YearNumber = "2028" }); objItemStatusCol.Add(new Year { YearId = 17, YearNumber = "2029" }); objItemStatusCol.Add(new Year { YearId = 18, YearNumber = "2030" }); return objItemStatusCol; } } public class Day { public int DayId { get; set; } public string DayNumber { get; set; } } public class BlockGuest { public int BlockGuestId { get; set; } public string BlockGuestName { get; set; } } public class Month { public int MonthId { get; set; } public string MonthName { get; set; } } public class Year { public int YearId { get; set; } public string YearNumber { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace YzkSoftWare { /// <summary> /// 索引超出范围错误 /// </summary> public class OutIndexException : Exception { public OutIndexException(int index) : base(string.Format(LocalResource.OutIndexException_Message, index)) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MinaOffline : MonoBehaviour { public float poder; public GameObject explocion; //ONDA public GameObject prefab; public string tank; public bool muerte; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(muerte) { Explo(); muerte = false; Destroy(gameObject); } } void OnTriggerEnter (Collider col) { if(col.gameObject.tag == tank) { GetComponent<Animator>().SetBool("explotar", true); } if(col.gameObject.tag == "explo") { GetComponent<Animator>().SetBool("explotar", true); } if(col.gameObject.tag == "bala") { GetComponent<Animator>().SetBool("explotar", true); } } public void sonar() { GetComponent<AudioSource>().Play(); } public void Explotar() { Explo(); } public void Explo() { var explo = (GameObject)Instantiate(explocion, transform.position, Quaternion.identity); var onda = (GameObject)Instantiate(prefab, transform.position, Quaternion.identity); explo.GetComponent<ExploOffline>().poder = poder; Destroy(gameObject); } }
using System; using System.Collections.Generic; using System.Threading; using System.IO; using foobalator; namespace ClipIndexer { public static class Worker { // BrianSp: The main thread will block on this handle until this event is set. Normally get's set on service stop. private static ManualResetEvent m_End = new ManualResetEvent(false); public static readonly string Name = typeof(Worker).Assembly.GetName().ToString(); // BrianSp: This is the main entry point for the main thread. Spins up worker threads and waits for signal to stop. public static void Run() { Log.WriteLine(Name + " started"); try { string value = SystemState.Settings.GetValue("Worker.Run.Directories"); string[] dirs = value.Split('|'); List<Thread> threads = new List<Thread>(); foreach (string dir in dirs) { Thread thread = new Thread(new ParameterizedThreadStart(IndexThread)); thread.Start(dir); threads.Add(thread); } m_End.WaitOne(); foreach (Thread thread in threads) thread.Abort(); } finally { Log.WriteLine(Name + " stopped"); } } public static void End() { m_End.Set(); } public static void IndexThread(object dir) { while (true) { Index((string)dir); System.Threading.Thread.Sleep(TimeSpan.FromMinutes(5)); } } public static void Index(string dir) { Index(dir, TimeSpan.FromDays(1), true); } public static void Index(string dir, TimeSpan minAge, bool act) { DateTime now = DateTime.Now; string[] files = Directory.GetFiles(dir); foreach (string file in files) { try { string name = Path.GetFileName(file); // Expected format is: 'Label' yyyy mm dd 's' hh mm ss lll // Example Back20121125s184423949.jpg // or Driveway20130817_050715.jpg int i; for (i = 0; i < name.Length; i++) { if (name[i] >= '0' && name[i] <= '9') break; } string label = name.Substring(0, i); int year = int.Parse(name.Substring(i, 4)); i += 4; int month = int.Parse(name.Substring(i, 2)); i += 2; int day = int.Parse(name.Substring(i, 2)); i += 2; if (name[i] == 's' || name[i] == '_') i += 1; int hour = int.Parse(name.Substring(i, 2)); i += 2; int minute = int.Parse(name.Substring(i, 2)); i += 2; int second = int.Parse(name.Substring(i, 2)); i += 2; if (name[i] == 'M') i += 1; int millisecond = 0; if (name[i] != '.') { millisecond = int.Parse(name.Substring(i, 3)); i += 3; } string extension = name.Substring(i); if (extension != ".jpg") throw new Exception(string.Format("Expected '.jpg' at location {0}", i)); DateTime time = new DateTime(year, month, day, hour, minute, second, millisecond); TimeSpan age = now - time; if (age < minAge) continue; string destDir = Path.Combine(dir, string.Format("{0:D4}-{1:D2}-{2:D2} {3}", year, month, day, label)); string destFile = Path.Combine(destDir, name); Log.WriteLine(string.Format("{0} -> {1}", file, destFile)); if (act) { if (!Directory.Exists(destDir)) Directory.CreateDirectory(destDir); File.Move(file, destFile); } } catch (Exception e) { Log.Write(e); } } } } }
using FluentValidation; namespace Application.Product.Commands.UpdateDealoftheDayCommands { public class UpdateDealoftheDayCommandValidator : AbstractValidator<UpdateDealoftheDayCommand> { public UpdateDealoftheDayCommandValidator () { RuleFor (e => e.IdProducts) .NotEmpty ().WithMessage ("ID Products cant be empty!") .NotNull ().WithMessage ("ID Products cant be null!"); } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; using System.Threading.Tasks; using Tekla.Structures; using Tekla.Structures.CustomPropertyPlugin; using Tekla.Structures.Model; namespace TeklaCustomProperties { [Export(typeof(ICustomPropertyPlugin))] [ExportMetadata("CustomProperty", "CUSTOM.CNS_VOLUME")] public class Volume : ICustomPropertyPlugin { public double GetDoubleProperty(int objectId) { var model = new Model(); Identifier id = new Identifier(objectId); var obj = model.SelectModelObject(id); double volume = 0; if(obj is Part) { var part = obj as Part; part.GetReportProperty("VOLUME", ref volume); } return volume; } public int GetIntegerProperty(int objectId) { return 0; } public string GetStringProperty(int objectId) { return ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _14.SetOfIntegers { class SetOfIntegers { static void minOfSet(int[] setOfInts) { try { var min = setOfInts[0]; for (int i = 1; i < setOfInts.Length; i++) { if (setOfInts[i] < min) { min = setOfInts[i]; } } Console.WriteLine(min); } catch (IndexOutOfRangeException ex) { Console.WriteLine(ex); } } static void maxOfSet(int[] setOfInts) { try { var max = setOfInts[0]; for (int i = 1; i < setOfInts.Length; i++) { if (setOfInts[i] > max) { max = setOfInts[i]; } } Console.WriteLine(max); } catch (IndexOutOfRangeException ex) { Console.WriteLine(ex); } } static void averageOfSet(int[] setOfInts) { try { int sum = 0; double average = 0d; foreach (var item in setOfInts) { sum += item; } average = (double)sum / setOfInts.Length; Console.WriteLine(average); } catch (IndexOutOfRangeException ex) { Console.WriteLine(ex); } } static void sumOfSet(int[] setOfInts) { try { int sum = 0; foreach (var item in setOfInts) { sum += item; } Console.WriteLine(sum); } catch (IndexOutOfRangeException ex) { Console.WriteLine(ex); } } static void productOfSet(int[] setOfInts) { try { var product = 1; foreach (var item in setOfInts) { product *= item; } Console.WriteLine(product); } catch (IndexOutOfRangeException ex) { Console.WriteLine(ex); } } static void Main(string[] args) { int[] setOfIntegers = { 1, 3, 2, 1, 4 }; maxOfSet(setOfIntegers); minOfSet(setOfIntegers); averageOfSet(setOfIntegers); productOfSet(setOfIntegers); } } }
using UnityEngine; using UnityEngine.UI; [SLua.CustomLuaClass] public class SpriteSwapper : MonoBehaviour { public Sprite enabledSprite; public Sprite disabledSprite; private bool m_swapped = true; private Image m_image; public void Awake() { m_image = GetComponent<Image>(); } public void SetEnable(bool val) { this.m_swapped = !val; if (m_swapped) { m_image.sprite = enabledSprite; } else { m_image.sprite = disabledSprite; } } public void SwapSprite() { if (m_swapped) { m_swapped = false; m_image.sprite = disabledSprite; } else { m_swapped = true; m_image.sprite = enabledSprite; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class TurnHandler : MonoBehaviour { /// <summary> /// Game state /// </summary> public enum State { Placement, Playing, PlayingForceWay }; /// <summary> /// List of players /// </summary> public static Player[] players; /// <summary> /// Random placement flag for testing purposes /// </summary> private readonly bool randomPlacement = false; /// <summary> /// Turn index /// </summary> private int turnIndex; /// <summary> /// The total turns. /// </summary> private int totalTurns; /// <summary> /// The current cycle. All players must have a turn before the next cycle /// </summary> private int currentCycle; /// <summary> /// The move history. /// </summary> private List<PieceMove> moveHistory; /// <summary> /// The first tile selection. /// </summary> private TileNode firstSelection; /// <summary> /// The current moveset for the selected tower /// </summary> private HashSet<TileNode> moves; /// <summary> /// Random object /// </summary> private System.Random rand; // used for the random placement function private int[] dirWheel = { 0, 0, 5, 5, 4, 4, 3, 3, 2, 2, 1, 1 }; private int[,] dirWheelOffset = { { 1, 9 }, { 11, 7 }, { 9, 1 }, { 7, 3 }, { 5, 1 }, { 3, 11 } }; /// <summary> /// The result panel. /// </summary> private GameObject resultPanel; /// <summary> /// The game current state. /// </summary> public State state; /// <summary> /// Float to offset player placement piece. /// </summary> private float playerPlacementOffset; /// <summary> /// List of all the available tiles for placement. /// </summary> private List<TileNode> placementTiles; /// <summary> /// Accessor for placementTiles. /// </summary> public List<TileNode> PlacementTiles { get { return placementTiles; } } /// <summary> /// The placement piece selection. /// </summary> private PlacementPiece placementPiece; /// <summary> /// Accessor for placementPiece. /// </summary> public PlacementPiece PlacementPiece { set { placementPiece = value; } } /// <summary> /// Number of turns skipped in a row /// </summary> private int turnsSkipped; /// <summary> /// Start this instance. /// </summary> void Start() { } /// <summary> /// Initalize this instance. /// </summary> public void Initalize () { turnIndex = -1; totalTurns = 0; currentCycle = 1; moveHistory = new List<PieceMove>(); state = State.Placement; rand = new System.Random(); #region quick ini players if (players == null) { // ini players players = new Player[3]; // player 1 players[0] = new LocalHumanPlayer(); players[0].colour = Player.PlayerColour.Brown; players[0].playerName = players[0].colour + ""; // player 2 players[1] = new LocalHumanPlayer(); players[1].colour = Player.PlayerColour.Blue; players[1].playerName = players[1].colour + ""; // player 3 players[2] = new LocalHumanPlayer(); players[2].colour = Player.PlayerColour.Green; players[2].playerName = players[2].colour + ""; } #endregion #region generate and attach score displays to player for (int i = 0 ; i < players.Length; i++) { GameObject display = Instantiate(Resources.Load("Prefabs/UI/ScoreDisplay")) as GameObject; display.transform.SetParent(GameObject.Find("UICanvas").transform, false); // positioning the display RectTransform rect = display.GetComponent<RectTransform>(); Vector3 pos = new Vector3(rect.anchoredPosition3D.x, rect.anchoredPosition3D.y); Vector3 offset = new Vector3( -(45f * (players.Length / 2f)) + (45f * i) + (10f * i), 0f); pos += offset; rect.anchoredPosition3D = pos; // setting display colour display.GetComponent<Image>().color = players[i].getRealColor(); players[i].scoreDisplay = display; players[i].updateScore(); } #endregion // Generate placement pieces for each player foreach (Player p in players) { GeneratePlacementPieces(p); } // Initialize the placement tiles TaoexBoard board = GameObject.Find("Taoex").GetComponent<TaoexBoard>(); placementTiles = new List<TileNode>(); // Add all edge tiles to the placement tiles list for (int i = 0; i < board.edgeTiles.GetLength(0); i++) { for (int j = 0; j < board.edgeTiles.GetLength(1); j++) { placementTiles.Add(board.edgeTiles[i, j]); } } if (randomPlacement) { // randomly places the pieces RandomPlacement(); } // increments the turn from -1 to 0 which is the first player NextTurn(); } /// <summary> /// handles tile selection event based on game state /// </summary> /// <param name="node">A selected tilenode</param> public void SelectedTile(TileNode node) { switch (state) { case State.Placement: PlacementAction(node); break; case State.Playing: PlayingAction(node); break; case State.PlayingForceWay: StartCoroutine(ForcedWayAction(node)); break; } } /// <summary> /// if placement state then this will handle the selection event /// </summary> /// <param name="node">A selected tilenode</param> private void PlacementAction(TileNode node) { // Can only place pieces on empty edge tiles if (node.type != TileNode.Type.Edge || node.tower != null || placementPiece == null) { UnhighlightPlacementTiles(); return; } // Node direction as an int int nodeDir = (node.edgeId + 3) % 6; // Invalid starting position for this piece if (nodeDir != placementPiece.Piece.direction) { UnhighlightPlacementTiles(); return; } // Validation passed, so place the piece players[turnIndex].PlacePiece(placementPiece, node); placementPiece.Placed = true; // Disable components that were used for placement purposes Destroy(placementPiece.gameObject.GetComponent<MeshCollider>()); //Destroy(placementPiece.gameObject.GetComponent<PlacementPiece>()); // Setup for the next placement placementPiece = null; UnhighlightPlacementTiles(); placementTiles.Remove(node); NextTurn(); } /// <summary> /// if playing state then this is called /// </summary> /// <param name="node">A selected tilenode</param> private void PlayingAction(TileNode node) { // no tile selected if (firstSelection == null) { #region first Selection // check if the selected tower is valid for the player's turn if (node.tower != null && node.tower.owningColour == players[turnIndex].colour) { firstSelection = node; // for a valid tower, highlight the legal moves for it. foreach (TileNode moveTile in node.tower.GetMoves().Destinations) { moveTile.highlight(); } } #endregion // player has selected a tower already (first selection) } else { #region second selection // fix attempt for mystery firstSelection not clearing TileNode cfirstSelection = this.firstSelection; this.firstSelection = null; PieceTower tower = cfirstSelection.tower; moves = tower.GetMoves().Destinations; // unhighlights the legal moves from the first selected tower foreach (TileNode moveTile in moves) { moveTile.unhighlight(); } // request move to the next selected tile. PieceMove requestedMove = new PieceMove(cfirstSelection, tower.GetMoves().GetMoveObject(node), moves); // requestMove.Execute() both validates and execute it. if (requestedMove.Execute() == true) { // add the requested move (its a legal move) to the history moveHistory.Add(requestedMove); GameObject.Find("MoveHistoryPanel").GetComponent<MoveHistoryHandler>().addMove(moveHistory[moveHistory.Count - 1]); // Tower came off of the edge tile if (cfirstSelection.type == TileNode.Type.Edge && requestedMove.dest.type != TileNode.Type.Edge) { placementTiles.Add(cfirstSelection); } StartCoroutine(HandleRequestResult(requestedMove.GetResult(), node, tower)); } // reset the selection firstSelection = null; #endregion } } /// <summary> /// Handles the result type of a piece move. /// </summary> /// <param name="result">the result type</param> /// <param name="node">the destination node</param> /// <param name="tower">the attacking tower</param> /// <returns></returns> private IEnumerator HandleRequestResult(PieceMove.ResultType result, TileNode node, PieceTower tower) { // Do something based on the result of the way move switch (result) { case PieceMove.ResultType.Normal: // Wait for overstack to finish yield return new WaitUntil(() => OverstackUI.done); NextTurn(); break; case PieceMove.ResultType.ForcedWay: // Wait for overstack to finish yield return new WaitUntil(() => OverstackUI.done); StartCoroutine(WayRoll(node, tower, node.wayLine)); break; case PieceMove.ResultType.ForcedWayCross: // Wait for overstack to finish yield return new WaitUntil(() => OverstackUI.done); StartCoroutine(WayCrossRoll(node, tower)); break; case PieceMove.ResultType.Win: SceneManager.LoadScene("EndMenu"); break; } } /// <summary> /// Logic for handling the case for way roll on a cross or intersection on the way /// </summary> /// <returns>A thing used for courtine</returns> /// <param name="node">Node.</param> /// <param name="tower">Tower.</param> private IEnumerator WayCrossRoll(TileNode node, PieceTower tower) { // create the picker for player to choose direction on the way WayCrossPicker wcp = new WayCrossPicker(node); // AI picks a random arrow if (players[turnIndex].IsAI) { // AI delay before continuing yield return new WaitForSeconds(AIPlayer.AIDelay); // Get a random arrow GameObject arrow = wcp.Arrows[new System.Random().Next(0, wcp.Arrows.Length)]; // Pick the arrow arrow.GetComponent<WayCrossArrowClick>().OnMouseUpAsButton(); } // wait until the user has picked a direction yield return new WaitUntil(() => wcp.decided == true); // if resultLine is -1 then somehow the user has not picked a direction Debug.Assert(wcp.resultLine != -1); // Start a roll along StartCoroutine(WayRoll(node, tower, wcp.resultLine)); } /// <summary> /// Logic for handling a way roll move along a way line /// </summary> /// <returns>The roll.</returns> /// <param name="node">Node.</param> /// <param name="tower">Tower.</param> /// <param name="wayLineID">Way line ID.</param> private IEnumerator WayRoll(TileNode node, PieceTower tower, int wayLineID) { //moves = tower.GetWayMove(9); // Wait for overstack to finish yield return new WaitUntil(() => OverstackUI.done); // Create a way roll dice GameObject diceObj = Instantiate(Resources.Load("Prefabs/UI/WayDice")) as GameObject; // place the way roll dice on the UICanvas diceObj.transform.SetParent(GameObject.Find("UICanvas").transform, false); // Starts the roll DiceRollScript diceScript = diceObj.GetComponent<DiceRollScript>(); StartCoroutine(diceScript.StartRoll()); // wait until roll is complete yield return new WaitUntil(() => diceScript.RollState == DiceRollScript.State.Ready); // if the result is -999, some how the diceroll did not reach a result. Debug.Assert(diceObj.GetComponent<DiceRollScript>().Result != -999); // Overstacking onto way cross, fix the reference for the tower if (tower.GetNode() == null) { // Get the new tower tower = GameObject.Find("Overstack").GetComponent<OverstackUI>().NewTower; // Clear reference from overstack interface GameObject.Find("Overstack").GetComponent<OverstackUI>().NewTower = null; } // get moves along the way line with the range from the result of the roll moves = tower.GetWayMove(diceObj.GetComponent<DiceRollScript>().Result, wayLineID).Destinations; // if no moves are avalible or rolled a zero if (moves.Count == 0) { // add move to history moveHistory.Add(new PieceMove(node, tower.GetMoves().GetMoveObject(node), moves)); GameObject.Find("MoveHistoryPanel").GetComponent<MoveHistoryHandler>().addMove(moveHistory[moveHistory.Count - 1]); // reset selection state = State.Playing; firstSelection = null; // move to next player's turn NextTurn(); } else { // highlight the way move options foreach (TileNode wayTile in moves) { wayTile.highlight (); } // set state to special way state state = State.PlayingForceWay; // set first selection to current position firstSelection = node; // If the player is an AI if (players[turnIndex].IsAI) { // AI delay before continuing yield return new WaitForSeconds(AIPlayer.AIDelay); // Forced way move for AI StartCoroutine(ForcedWayAction(((AIPlayer)players[turnIndex]).ForcedWay(tower, moves).dest)); } } // destory the dice roll ui game object Destroy(diceObj, 1f); } /// <summary> /// If forced a roll /// </summary> /// <param name="node"></param> private IEnumerator ForcedWayAction(TileNode node) { PieceMove requestedMove = new PieceMove(firstSelection, new MoveSet.Move(firstSelection, false, node), moves); if (requestedMove.Execute()) { moveHistory.Add(requestedMove); GameObject.Find("MoveHistoryPanel").GetComponent<MoveHistoryHandler>().addMove(moveHistory[moveHistory.Count - 1]); // unhighlight the way moves foreach (TileNode moveTile in moves) { moveTile.unhighlight(); } if (requestedMove.Result == PieceMove.ResultType.Win) { SceneManager.LoadScene("EndMenu"); } // Wait for overstack yield return new WaitUntil(() => OverstackUI.done); state = State.Playing; firstSelection = null; NextTurn(); } } /// <summary> /// Changes the current player's turn to the next player /// </summary> private void NextTurn() { if (turnIndex != -1) { players[turnIndex].TurnEnd(); } turnIndex = (turnIndex + 1) % players.Length; totalTurns++; // move arrow to next player's display GameObject.Find("TurnArrow").GetComponent<RectTransform>().anchoredPosition3D = new Vector3( players[turnIndex].scoreDisplay.GetComponent<RectTransform>().anchoredPosition3D.x, players[turnIndex].scoreDisplay.GetComponent<RectTransform>().anchoredPosition3D.y - 25f, players[turnIndex].scoreDisplay.GetComponent<RectTransform>().anchoredPosition3D.z); if (turnIndex == 0) { currentCycle++; } // There are placement tiles available if (placementTiles.Count > 0) { // Check if the current player must make a placement move if (ForcedPlacementCheck()) { state = State.Placement; CreatePlacementArrows(); } else { state = State.Playing; } } else { // No placement tiles available state = State.Playing; } Debug.Log("State: " + state); // check if player has any moves if (state == State.Playing && players[turnIndex].TotalNumberOfMoves() == 0) { int moves = players[turnIndex].TotalNumberOfMoves(); turnsSkipped++; // check if all but one player can make a turn; if (turnsSkipped >= players.Length - 1) { turnIndex = (turnIndex + 1) % players.Length; totalTurns++; PieceMove.winner = players[turnIndex]; PieceMove.WIN = PieceMove.WinType.ElimAll; SceneManager.LoadScene("EndMenu"); return; } players[turnIndex].TurnSkipped(); NextTurn(); // Skip turn! } // Player has move else { players[turnIndex].TurnStart(); turnsSkipped = 0; if (!players[turnIndex].IsAI) { players[turnIndex].DoTurn(); } else { StartCoroutine(AITurn()); } } } /// <summary> /// Creates arrows above the placement positions and tiles /// </summary> private void CreatePlacementArrows() { HashSet<TileNode> placementSpots = new HashSet<TileNode>(); foreach (PlacementPiece p in players[turnIndex].PlacementPieces) { // create arrow on placement piece GameObject arrow = GameObject.Instantiate(Resources.Load("Prefabs/GameObject/FloatingArrowPointer")) as GameObject; Vector3 pos = new Vector3(p.transform.position.x, p.transform.position.y, p.transform.position.z); pos.y += 90f; arrow.transform.position = pos; foreach (TileNode tn in p.GetAvailableTiles()) { placementSpots.Add(tn); } } /* // create arrows over placement spots foreach (TileNode tn in placementSpots) { GameObject arrow = GameObject.Instantiate(Resources.Load("Prefabs/GameObject/FloatingArrowPointer")) as GameObject; Vector3 pos = tn.BasePosition; pos.y += 100f; arrow.transform.position = pos; } */ } /// <summary> /// Handles turns for AI players. /// </summary> private IEnumerator AITurn() { // AI delay before continuing yield return new WaitForSeconds(AIPlayer.AIDelay); if (state == State.Placement) { // Get a placement move PlacementMove pm = ((AIPlayer)players[turnIndex]).PlacementMove(); placementPiece = pm.PlacementPiece; // Click the placement piece placementPiece.OnMouseUpAsButton(); yield return new WaitForSeconds(AIPlayer.AIDelay); // Click the placement tile SelectedTile(pm.Destination); } else { // Get a weighted move WeightedMove wm = players[turnIndex].DoTurn(); // Do the turn SelectedTile(wm.piece.GetNode()); yield return new WaitForSeconds(AIPlayer.AIDelay); SelectedTile(wm.dest); } } /// <summary> /// Randomly places pieces for the players. /// </summary> private void RandomPlacement() { turnIndex = 0; // Keep placing until done while (placementTiles.Count > 0 && players[turnIndex].PlacementPieces.Count > 0) { // Get a random piece List<PlacementPiece> placementPieces = players[turnIndex].PlacementPieces; PlacementPiece randomPiece = placementPieces[new System.Random().Next(0, placementPieces.Count)]; List<TileNode> availableTiles = randomPiece.GetAvailableTiles(); // If this piece can't be placed, get one that can if (availableTiles.Count == 0) { for (int i = 0; i < placementPieces.Count; i++) { availableTiles = placementPieces[i].GetAvailableTiles(); if (availableTiles.Count > 0) { randomPiece = placementPieces[i]; break; } } } TileNode randomTile = availableTiles[new System.Random().Next(0, availableTiles.Count)]; // Place the random piece onto a random edge tile for its direction getPlayerByColour(randomPiece.Piece.colour).PlacePiece(randomPiece, randomTile); randomPiece.Placed = true; // Cleanup, can't use PlacementAction for this because we dont want to call next turn yet Destroy(randomPiece.gameObject.GetComponent<MeshCollider>()); placementTiles.Remove(randomTile); // Increment turn index turnIndex = (turnIndex + 1) % players.Length; totalTurns++; if (turnIndex == 0) { currentCycle++; } } // Setup for next turn turnIndex--; } /// <summary> /// Gets the player by colour. /// </summary> /// <returns>The player by colour.</returns> /// <param name="colour">A playters colour enum. Does not work with hook "colour"</param> public Player getPlayerByColour(Player.PlayerColour colour) { // search each player for one with the correct colour foreach (Player p in players) { if (p.colour == colour) { return p; } } // did not find a matching player return null; } /// <summary> /// Getter for the current player. /// </summary> /// <returns>the current player</returns> public Player GetCurrentPlayer() { return players[turnIndex]; } /// <summary> /// Checks if the current player must do a placement action. /// </summary> public bool ForcedPlacementCheck() { foreach (PlacementPiece placementPiece in players[turnIndex].PlacementPieces) { if (placementPiece.GetAvailableTiles().Count > 0) { Debug.Log(players[turnIndex].colour + " must place"); return true; } } // Player doesn't have to place return false; } /// <summary> /// Unhighlights the placement tiles /// </summary> public void UnhighlightPlacementTiles() { foreach (TileNode placementTile in placementTiles) { placementTile.unhighlight(); } } /// <summary> /// Generates all twelve starting pieces for the player. /// </summary> /// <param name="player">the player to generate pieces for</param> public void GeneratePlacementPieces(Player player) { // Directions as ints int N = 0, NE = 1, SE = 2, S = 3, SW = 4, NW = 5; // List of pieces to place List<PieceData> pieces = new List<PieceData>(); PieceCreator pieceCreator = GameObject.Find("Taoex").GetComponent<PieceCreator>(); // Create the pieces for (int dir = 0; dir < 6; dir++) { pieces.Add(pieceCreator.CreatePiece(player.colour, dir, 2)); pieces.Add(pieceCreator.CreatePiece(player.colour, dir, 3)); } // Reference to the board for getting way cross coordinates TaoexBoard board = GameObject.Find("Taoex").GetComponent<TaoexBoard>(); Vector3 center = GameObject.Find("Compass").transform.position; Vector3[] crosses = new Vector3[6]; // Positions of the way crosses crosses[0] = board.GetTiles()[13, 5].BasePosition; // S crosses[1] = board.GetTiles()[7, 8].BasePosition; // SW crosses[2] = board.GetTiles()[7, 14].BasePosition; // NW crosses[3] = board.GetTiles()[13, 17].BasePosition; // N crosses[4] = board.GetTiles()[19, 14].BasePosition; // NE crosses[5] = board.GetTiles()[19, 8].BasePosition; // SE // Pieces per direction are in sets of two, so we need to offset them float offset = 0f; float angleOffset = 0f; // Counter for the piece number for the current direction int count = 0; foreach (PieceData piece in pieces) { // Setup the textures piece.SetupTextures(); // Placement piece component so that the piece can handle click events correctly player.PlacementPieces.Add(piece.getObj().AddComponent<PlacementPiece>()); piece.getObj().GetComponent<PlacementPiece>().Piece = piece; // Spawn position of the piece Vector3 spawnPosition; Transform pieceTrans = piece.getObj().transform; // Direction of the piece int direction = piece.direction; // Spawn position starts at the way cross spawnPosition = crosses[direction]; // Vector going outward from the center to the cross Vector3 centerToCross = spawnPosition - center; centerToCross.Normalize(); // Move the spawn position back and up spawnPosition += centerToCross * 500f; spawnPosition.y += 40f; // Spawn the piece texture there piece.getObj().transform.position = spawnPosition; // Make the piece look towards the center pieceTrans.LookAt(center); // Move along the side of the board using uvn coordinates pieceTrans.InverseTransformDirection(pieceTrans.position); pieceTrans.Translate(offset - 400f + playerPlacementOffset, 0, 0f); pieceTrans.TransformDirection(pieceTrans.position); // Rotate the pieces piece.getObj().transform.eulerAngles = new Vector3(0, angleOffset, 0); // Save the transform piece.getObj().GetComponent<PlacementPiece>().PlacementPosition = piece.getObj().transform.position; piece.getObj().GetComponent<PlacementPiece>().PlacementRotation = piece.getObj().transform.eulerAngles; // Increment the offset offset += 75f; count++; // If this is the second piece, reset offsets for the next set of two if (count % 2 == 0) { offset = 0f; } if (count % 2 == 0) { angleOffset += 60f; } } // Next player's offset playerPlacementOffset += 200f; } }
using DevExpress.Mvvm.DataAnnotations; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; using System.IO.Ports; namespace SimpleDemo.Model { ///// <summary> ///// 串口设置参数 ///// </summary> //public class SettingPortModelTemp //{ // /// <summary> // /// 点阵屏 // /// </summary> // public PortIndex? LatticeScreen { get; set; } // /// <summary> // /// 灯光检测 // /// </summary> // public PortIndex LightDevice { get; set; } // /// <summary> // /// 光电 // /// </summary> // public PortIndex Photoelectric { get; set; } // public string Name { get; set; } // /// <summary> // /// 自定义类型 // /// </summary> // public SettingPortType ParamType { get; set; } //} ///// <summary> ///// 串口设置参数 ///// </summary> //public class SettingPortModel //{ // public string Name { get; set; } // /// <summary> // /// 类型 // /// </summary> // public SettingPortType ParamType { get; set; } // /// <summary> // /// 值 // /// </summary> // public object Value { get; set; } //} ///// <summary> ///// 类型枚举 ///// </summary> //public enum SettingPortType //{ // /// <summary> // /// COM模式 // /// </summary> // ComType, // /// <summary> // /// 文本模式 // /// </summary> // TextType, // /// <summary> // /// 协议模式,例如显示厂家名 // /// </summary> // ProtocolType //} //public class DeviceElement //{ // /// <summary> // /// 协议类型 // /// </summary> // [Display(Name = "协议类型", Order = 99)] // public string ProtocolType { get; set; } // /// <summary> // /// 设备类型 // /// </summary> // [Display(Name = "设备类型")] // public DeviceType DeviceType { get; set; } // /// <summary> // /// 检测项目 // /// </summary> // [Display(Name = "检测项目")] // public DetectionType DetectionType { get; set; } // /// <summary> // /// 编号。用于区分同一工位或流程中出现的同款设备 // /// </summary> // [Display(Name = "编号", Description = "用于区分同一工位或流程中出现的同款设备")] // public int Index { get; set; } //} public class PortElement: SerialPort { //[Display(Name = "端口")] //public PortIndex PortName { get; set; } //[Display(Name = "波特率")] //public int BaudRate { get; set; } //[Display(Name = "数据位")] //public int DataBits { get; set; } //[Display(Name = "奇偶校验")] //public Parity Parity { get; set; } //[Display(Name = "停止位")] //public StopBits StopBits { get; set; } /// <summary> /// 协议类型 /// </summary> [Display(Name = "协议类型", Order = 99)] public string ProtocolType { get; set; } /// <summary> /// 设备类型 /// </summary> [Display(Name = "设备类型")] public DeviceType DeviceType { get; set; } /// <summary> /// 检测项目 /// </summary> [Display(Name = "检测项目")] public DetectionType DetectionType { get; set; } /// <summary> /// 编号。用于区分同一工位或流程中出现的同款设备 /// </summary> [Display(Name = "编号", Description = "用于区分同一工位或流程中出现的同款设备")] public int Index { get; set; } /// <summary> /// 设备在线情况 /// </summary> public bool IsOnline { get; set; } } //public class SettingBase //{ // public string SettingName { get; set; } // public List<PortElement> PortList { get; set; } = new List<PortElement>(); //} ///// <summary> ///// 大灯检测配置参数 ///// </summary> //[MetadataType(typeof(LightSettingLayoutMetadata))] //public class LightSetting:SettingBase //{ // const string GName = "大灯"; // /// <summary> // /// 灯屏 // /// </summary> // [Display(Name = "灯屏", GroupName = GName)] // public PortElement LatticeScreen { get; set; } = new PortElement(); // /// <summary> // /// 大灯 // /// </summary> // [Display(Name = "大灯", GroupName = GName)] // public PortElement LightDevice { get; set; } = new PortElement(); // /// <summary> // /// 光电 // /// </summary> // [Display(Name = "光电", GroupName = GName)] // public PortElement Photoelectric { get; set; } = new PortElement(); // public string XX { get; set; } // /// <summary> // /// 协议类型 // /// </summary> // //[Display(Name = "协议类型", GroupName = GName)] // //public string ProtocolType { get; set; } //} //public static class LightSettingLayoutMetadata //{ // public static void BuildMetadata(MetadataBuilder<LightSetting> builder) // { // builder.DataFormLayout() // .GroupBox("大灯参数", Orientation.Vertical) // .ContainsProperty(x => x.LatticeScreen) // .ContainsProperty(x => x.LightDevice) // .ContainsProperty(x => x.Photoelectric); // } //} }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ex7 { class Program { static void Main(string[] args) { Console.WriteLine("Enter the value of a: "); int a = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the value of b: "); int b = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the value of c: "); int c = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the value of d: "); int d = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the value of e: "); int e = int.Parse(Console.ReadLine()); int max1 = new int(); int max2 = new int(); max1 = Math.Max(a, b); max2 = Math.Max(c, d); max1 = Math.Max(max1, max2); Console.WriteLine("The largest number is \"{0}\"",Math.Max(max1,e)); Console.ReadLine(); } } }
using System.Collections.Generic; namespace MultiCommentCollectorCLI { public class CommandItem { public string Command { get; set; } public List<string> Argv { get; set; } } }
/* * Bungie.Net API * * These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. * * OpenAPI spec version: 2.1.1 * Contact: support@bungie.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter; namespace BungieNetPlatform.Model { /// <summary> /// If an item is \&quot;instanced\&quot;, this will contain information about the item&#39;s instance that doesn&#39;t fit easily into other components. One might say this is the \&quot;essential\&quot; instance data for the item. Items are instanced if they require information or state that can vary. For instance, weapons are Instanced: they are given a unique identifier, uniquely generated stats, and can have their properties altered. Non-instanced items have none of these things: for instance, Glimmer has no unique properties aside from how much of it you own. You can tell from an item&#39;s definition whether it will be instanced or not by looking at the DestinyInventoryItemDefinition&#39;s definition.inventory.isInstanceItem property. /// </summary> [DataContract] public partial class DestinyEntitiesItemsDestinyItemInstanceComponent : IEquatable<DestinyEntitiesItemsDestinyItemInstanceComponent>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="DestinyEntitiesItemsDestinyItemInstanceComponent" /> class. /// </summary> /// <param name="DamageType">If the item has a damage type, this is the item&#39;s current damage type..</param> /// <param name="DamageTypeHash">The current damage type&#39;s hash, so you can look up localized info and icons for it..</param> /// <param name="PrimaryStat">The item stat that we consider to be \&quot;primary\&quot; for the item. For instance, this would be \&quot;Attack\&quot; for Weapons or \&quot;Defense\&quot; for armor..</param> /// <param name="ItemLevel">The Item&#39;s \&quot;Level\&quot; has the most significant bearing on its stats, such as Light and Power..</param> /// <param name="Quality">The \&quot;Quality\&quot; of the item has a lesser - but still impactful - bearing on stats like Light and Power..</param> /// <param name="IsEquipped">Is the item currently equipped on the given character?.</param> /// <param name="CanEquip">If this is an equippable item, you can check it here. There are permanent as well as transitory reasons why an item might not be able to be equipped: check cannotEquipReason for details..</param> /// <param name="EquipRequiredLevel">If the item cannot be equipped until you reach a certain level, that level will be reflected here..</param> /// <param name="UnlockHashesRequiredToEquip">Sometimes, there are limitations to equipping that are represented by character-level flags called \&quot;unlocks\&quot;. This is a list of flags that they need in order to equip the item that the character has not met. Use these to look up the descriptions to show in your UI by looking up the relevant DestinyUnlockDefinitions for the hashes..</param> /// <param name="CannotEquipReason">If you cannot equip the item, this is a flags enum that enumerates all of the reasons why you couldn&#39;t equip the item. You may need to refine your UI further by using unlockHashesRequiredToEquip and equipRequiredLevel..</param> public DestinyEntitiesItemsDestinyItemInstanceComponent(DestinyDamageType DamageType = default(DestinyDamageType), uint? DamageTypeHash = default(uint?), DestinyDestinyStat PrimaryStat = default(DestinyDestinyStat), int? ItemLevel = default(int?), int? Quality = default(int?), bool? IsEquipped = default(bool?), bool? CanEquip = default(bool?), int? EquipRequiredLevel = default(int?), List<uint?> UnlockHashesRequiredToEquip = default(List<uint?>), DestinyEquipFailureReason CannotEquipReason = default(DestinyEquipFailureReason)) { this.DamageType = DamageType; this.DamageTypeHash = DamageTypeHash; this.PrimaryStat = PrimaryStat; this.ItemLevel = ItemLevel; this.Quality = Quality; this.IsEquipped = IsEquipped; this.CanEquip = CanEquip; this.EquipRequiredLevel = EquipRequiredLevel; this.UnlockHashesRequiredToEquip = UnlockHashesRequiredToEquip; this.CannotEquipReason = CannotEquipReason; } /// <summary> /// If the item has a damage type, this is the item&#39;s current damage type. /// </summary> /// <value>If the item has a damage type, this is the item&#39;s current damage type.</value> [DataMember(Name="damageType", EmitDefaultValue=false)] public DestinyDamageType DamageType { get; set; } /// <summary> /// The current damage type&#39;s hash, so you can look up localized info and icons for it. /// </summary> /// <value>The current damage type&#39;s hash, so you can look up localized info and icons for it.</value> [DataMember(Name="damageTypeHash", EmitDefaultValue=false)] public uint? DamageTypeHash { get; set; } /// <summary> /// The item stat that we consider to be \&quot;primary\&quot; for the item. For instance, this would be \&quot;Attack\&quot; for Weapons or \&quot;Defense\&quot; for armor. /// </summary> /// <value>The item stat that we consider to be \&quot;primary\&quot; for the item. For instance, this would be \&quot;Attack\&quot; for Weapons or \&quot;Defense\&quot; for armor.</value> [DataMember(Name="primaryStat", EmitDefaultValue=false)] public DestinyDestinyStat PrimaryStat { get; set; } /// <summary> /// The Item&#39;s \&quot;Level\&quot; has the most significant bearing on its stats, such as Light and Power. /// </summary> /// <value>The Item&#39;s \&quot;Level\&quot; has the most significant bearing on its stats, such as Light and Power.</value> [DataMember(Name="itemLevel", EmitDefaultValue=false)] public int? ItemLevel { get; set; } /// <summary> /// The \&quot;Quality\&quot; of the item has a lesser - but still impactful - bearing on stats like Light and Power. /// </summary> /// <value>The \&quot;Quality\&quot; of the item has a lesser - but still impactful - bearing on stats like Light and Power.</value> [DataMember(Name="quality", EmitDefaultValue=false)] public int? Quality { get; set; } /// <summary> /// Is the item currently equipped on the given character? /// </summary> /// <value>Is the item currently equipped on the given character?</value> [DataMember(Name="isEquipped", EmitDefaultValue=false)] public bool? IsEquipped { get; set; } /// <summary> /// If this is an equippable item, you can check it here. There are permanent as well as transitory reasons why an item might not be able to be equipped: check cannotEquipReason for details. /// </summary> /// <value>If this is an equippable item, you can check it here. There are permanent as well as transitory reasons why an item might not be able to be equipped: check cannotEquipReason for details.</value> [DataMember(Name="canEquip", EmitDefaultValue=false)] public bool? CanEquip { get; set; } /// <summary> /// If the item cannot be equipped until you reach a certain level, that level will be reflected here. /// </summary> /// <value>If the item cannot be equipped until you reach a certain level, that level will be reflected here.</value> [DataMember(Name="equipRequiredLevel", EmitDefaultValue=false)] public int? EquipRequiredLevel { get; set; } /// <summary> /// Sometimes, there are limitations to equipping that are represented by character-level flags called \&quot;unlocks\&quot;. This is a list of flags that they need in order to equip the item that the character has not met. Use these to look up the descriptions to show in your UI by looking up the relevant DestinyUnlockDefinitions for the hashes. /// </summary> /// <value>Sometimes, there are limitations to equipping that are represented by character-level flags called \&quot;unlocks\&quot;. This is a list of flags that they need in order to equip the item that the character has not met. Use these to look up the descriptions to show in your UI by looking up the relevant DestinyUnlockDefinitions for the hashes.</value> [DataMember(Name="unlockHashesRequiredToEquip", EmitDefaultValue=false)] public List<uint?> UnlockHashesRequiredToEquip { get; set; } /// <summary> /// If you cannot equip the item, this is a flags enum that enumerates all of the reasons why you couldn&#39;t equip the item. You may need to refine your UI further by using unlockHashesRequiredToEquip and equipRequiredLevel. /// </summary> /// <value>If you cannot equip the item, this is a flags enum that enumerates all of the reasons why you couldn&#39;t equip the item. You may need to refine your UI further by using unlockHashesRequiredToEquip and equipRequiredLevel.</value> [DataMember(Name="cannotEquipReason", EmitDefaultValue=false)] public DestinyEquipFailureReason CannotEquipReason { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DestinyEntitiesItemsDestinyItemInstanceComponent {\n"); sb.Append(" DamageType: ").Append(DamageType).Append("\n"); sb.Append(" DamageTypeHash: ").Append(DamageTypeHash).Append("\n"); sb.Append(" PrimaryStat: ").Append(PrimaryStat).Append("\n"); sb.Append(" ItemLevel: ").Append(ItemLevel).Append("\n"); sb.Append(" Quality: ").Append(Quality).Append("\n"); sb.Append(" IsEquipped: ").Append(IsEquipped).Append("\n"); sb.Append(" CanEquip: ").Append(CanEquip).Append("\n"); sb.Append(" EquipRequiredLevel: ").Append(EquipRequiredLevel).Append("\n"); sb.Append(" UnlockHashesRequiredToEquip: ").Append(UnlockHashesRequiredToEquip).Append("\n"); sb.Append(" CannotEquipReason: ").Append(CannotEquipReason).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DestinyEntitiesItemsDestinyItemInstanceComponent); } /// <summary> /// Returns true if DestinyEntitiesItemsDestinyItemInstanceComponent instances are equal /// </summary> /// <param name="input">Instance of DestinyEntitiesItemsDestinyItemInstanceComponent to be compared</param> /// <returns>Boolean</returns> public bool Equals(DestinyEntitiesItemsDestinyItemInstanceComponent input) { if (input == null) return false; return ( this.DamageType == input.DamageType || (this.DamageType != null && this.DamageType.Equals(input.DamageType)) ) && ( this.DamageTypeHash == input.DamageTypeHash || (this.DamageTypeHash != null && this.DamageTypeHash.Equals(input.DamageTypeHash)) ) && ( this.PrimaryStat == input.PrimaryStat || (this.PrimaryStat != null && this.PrimaryStat.Equals(input.PrimaryStat)) ) && ( this.ItemLevel == input.ItemLevel || (this.ItemLevel != null && this.ItemLevel.Equals(input.ItemLevel)) ) && ( this.Quality == input.Quality || (this.Quality != null && this.Quality.Equals(input.Quality)) ) && ( this.IsEquipped == input.IsEquipped || (this.IsEquipped != null && this.IsEquipped.Equals(input.IsEquipped)) ) && ( this.CanEquip == input.CanEquip || (this.CanEquip != null && this.CanEquip.Equals(input.CanEquip)) ) && ( this.EquipRequiredLevel == input.EquipRequiredLevel || (this.EquipRequiredLevel != null && this.EquipRequiredLevel.Equals(input.EquipRequiredLevel)) ) && ( this.UnlockHashesRequiredToEquip == input.UnlockHashesRequiredToEquip || this.UnlockHashesRequiredToEquip != null && this.UnlockHashesRequiredToEquip.SequenceEqual(input.UnlockHashesRequiredToEquip) ) && ( this.CannotEquipReason == input.CannotEquipReason || (this.CannotEquipReason != null && this.CannotEquipReason.Equals(input.CannotEquipReason)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.DamageType != null) hashCode = hashCode * 59 + this.DamageType.GetHashCode(); if (this.DamageTypeHash != null) hashCode = hashCode * 59 + this.DamageTypeHash.GetHashCode(); if (this.PrimaryStat != null) hashCode = hashCode * 59 + this.PrimaryStat.GetHashCode(); if (this.ItemLevel != null) hashCode = hashCode * 59 + this.ItemLevel.GetHashCode(); if (this.Quality != null) hashCode = hashCode * 59 + this.Quality.GetHashCode(); if (this.IsEquipped != null) hashCode = hashCode * 59 + this.IsEquipped.GetHashCode(); if (this.CanEquip != null) hashCode = hashCode * 59 + this.CanEquip.GetHashCode(); if (this.EquipRequiredLevel != null) hashCode = hashCode * 59 + this.EquipRequiredLevel.GetHashCode(); if (this.UnlockHashesRequiredToEquip != null) hashCode = hashCode * 59 + this.UnlockHashesRequiredToEquip.GetHashCode(); if (this.CannotEquipReason != null) hashCode = hashCode * 59 + this.CannotEquipReason.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
 using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Text; using Karkas.Core.DataUtil; using Karkas.Ornek.TypeLibrary; using Karkas.Ornek.TypeLibrary.Ornekler; namespace Karkas.Ornek.Dal.Ornekler { public partial class ButunVeriYapilari2008r2Dal : BaseDal<ButunVeriYapilari2008r2> { public override string DatabaseName { get { return "Karkas.Ornek"; } } protected override void identityKolonDegeriniSetle(ButunVeriYapilari2008r2 pTypeLibrary,long pIdentityKolonValue) { pTypeLibrary.ButunVeriYapilari2008r2key = (int )pIdentityKolonValue; } protected override string SelectCountString { get { return @"SELECT COUNT(*) FROM ORNEKLER.BUTUN_VERI_YAPILARI_2008R2"; } } protected override string SelectString { get { return @"SELECT ButunVeriYapilari2008R2Key,BigIntColumn,BinaryColumn,BitColumn,CharColumn,DateColumn,DateTimeColumn,DateTime2Column,DateTimeOffsetColumn,DecimalColumn,FloatColumn,GeopgraphyColummn,GeometryColumn,HierarchyIdColumn,ImageColumn,IntColumn,MoneyColumn,NCharColumn,NTextColumn,NumericColumn,NVarcharColumn,NVarcharMaxColumn,RealColumn,smallDateTimeColumn,smallIntColumn,SmallMoneyColumn,SqlVariantColumn,TextColumn,TimeColumn,TimestampColumn,TinyIntColumn,UniqueIdentifierColumn,VarBinaryColumn,VarBinaryMaxColumn,VarCharColumn,VarCharMaxColumn,XmlColumn FROM ORNEKLER.BUTUN_VERI_YAPILARI_2008R2"; } } protected override string DeleteString { get { return @"DELETE FROM ORNEKLER.BUTUN_VERI_YAPILARI_2008R2 WHERE ButunVeriYapilari2008R2Key = @ButunVeriYapilari2008R2Key "; } } protected override string UpdateString { get { return @"UPDATE ORNEKLER.BUTUN_VERI_YAPILARI_2008R2 SET BigIntColumn = @BigIntColumn ,BinaryColumn = @BinaryColumn ,BitColumn = @BitColumn ,CharColumn = @CharColumn ,DateColumn = @DateColumn ,DateTimeColumn = @DateTimeColumn ,DateTime2Column = @DateTime2Column ,DateTimeOffsetColumn = @DateTimeOffsetColumn ,DecimalColumn = @DecimalColumn ,FloatColumn = @FloatColumn ,GeopgraphyColummn = @GeopgraphyColummn ,GeometryColumn = @GeometryColumn ,HierarchyIdColumn = @HierarchyIdColumn ,ImageColumn = @ImageColumn ,IntColumn = @IntColumn ,MoneyColumn = @MoneyColumn ,NCharColumn = @NCharColumn ,NTextColumn = @NTextColumn ,NumericColumn = @NumericColumn ,NVarcharColumn = @NVarcharColumn ,NVarcharMaxColumn = @NVarcharMaxColumn ,RealColumn = @RealColumn ,smallDateTimeColumn = @smallDateTimeColumn ,smallIntColumn = @smallIntColumn ,SmallMoneyColumn = @SmallMoneyColumn ,SqlVariantColumn = @SqlVariantColumn ,TextColumn = @TextColumn ,TimeColumn = @TimeColumn ,TinyIntColumn = @TinyIntColumn ,UniqueIdentifierColumn = @UniqueIdentifierColumn ,VarBinaryColumn = @VarBinaryColumn ,VarBinaryMaxColumn = @VarBinaryMaxColumn ,VarCharColumn = @VarCharColumn ,VarCharMaxColumn = @VarCharMaxColumn ,XmlColumn = @XmlColumn WHERE ButunVeriYapilari2008R2Key = @ButunVeriYapilari2008R2Key "; } } protected override string InsertString { get { return @"INSERT INTO ORNEKLER.BUTUN_VERI_YAPILARI_2008R2 (BigIntColumn,BinaryColumn,BitColumn,CharColumn,DateColumn,DateTimeColumn,DateTime2Column,DateTimeOffsetColumn,DecimalColumn,FloatColumn,GeopgraphyColummn,GeometryColumn,HierarchyIdColumn,ImageColumn,IntColumn,MoneyColumn,NCharColumn,NTextColumn,NumericColumn,NVarcharColumn,NVarcharMaxColumn,RealColumn,smallDateTimeColumn,smallIntColumn,SmallMoneyColumn,SqlVariantColumn,TextColumn,TimeColumn,TinyIntColumn,UniqueIdentifierColumn,VarBinaryColumn,VarBinaryMaxColumn,VarCharColumn,VarCharMaxColumn,XmlColumn) VALUES (@BigIntColumn,@BinaryColumn,@BitColumn,@CharColumn,@DateColumn,@DateTimeColumn,@DateTime2Column,@DateTimeOffsetColumn,@DecimalColumn,@FloatColumn,@GeopgraphyColummn,@GeometryColumn,@HierarchyIdColumn,@ImageColumn,@IntColumn,@MoneyColumn,@NCharColumn,@NTextColumn,@NumericColumn,@NVarcharColumn,@NVarcharMaxColumn,@RealColumn,@smallDateTimeColumn,@smallIntColumn,@SmallMoneyColumn,@SqlVariantColumn,@TextColumn,@TimeColumn,@TinyIntColumn,@UniqueIdentifierColumn,@VarBinaryColumn,@VarBinaryMaxColumn,@VarCharColumn,@VarCharMaxColumn,@XmlColumn);SELECT scope_identity();"; } } public ButunVeriYapilari2008r2 SorgulaButunVeriYapilari2008r2keyIle(int p1) { List<ButunVeriYapilari2008r2> liste = new List<ButunVeriYapilari2008r2>(); SorguCalistir(liste,String.Format(" ButunVeriYapilari2008R2Key = '{0}'", p1)); if (liste.Count > 0) { return liste[0]; } else { return null; } } protected override bool IdentityVarMi { get { return true; } } protected override bool PkGuidMi { get { return false; } } public override string PrimaryKey { get { return "ButunVeriYapilari2008R2Key"; } } public virtual void Sil(int ButunVeriYapilari2008r2key) { ButunVeriYapilari2008r2 satir = new ButunVeriYapilari2008r2(); satir.ButunVeriYapilari2008r2key = ButunVeriYapilari2008r2key; base.Sil(satir); } protected override void ProcessRow(IDataReader dr, ButunVeriYapilari2008r2 satir) { satir.ButunVeriYapilari2008r2key = dr.GetInt32(0); if (!dr.IsDBNull(1)) { satir.BigIntColumn = dr.GetInt64(1); } if (!dr.IsDBNull(2)) { satir.BinaryColumn = (Byte[])dr.GetValue(2); } if (!dr.IsDBNull(3)) { satir.BitColumn = dr.GetBoolean(3); } if (!dr.IsDBNull(4)) { satir.CharColumn = dr.GetString(4); } if (!dr.IsDBNull(5)) { satir.DateColumn = dr.GetDateTime(5); } if (!dr.IsDBNull(6)) { satir.DateTimeColumn = dr.GetDateTime(6); } if (!dr.IsDBNull(7)) { satir.DateTime2column = dr.GetDateTime(7); } if (!dr.IsDBNull(8)) { satir.DateTimeOffsetColumn = DateTimeOffset(8); } if (!dr.IsDBNull(9)) { satir.DecimalColumn = dr.GetDecimal(9); } if (!dr.IsDBNull(10)) { satir.FloatColumn = dr.GetDouble(10); } if (!dr.IsDBNull(11)) { satir.GeopgraphyColummn = SqlGeography(11); } if (!dr.IsDBNull(12)) { satir.GeometryColumn = SqlGeometry(12); } if (!dr.IsDBNull(13)) { satir.HierarchyIdColumn = SqlHierarchyId(13); } if (!dr.IsDBNull(14)) { satir.ImageColumn = (Byte[])dr.GetValue(14); } if (!dr.IsDBNull(15)) { satir.IntColumn = dr.GetInt32(15); } if (!dr.IsDBNull(16)) { satir.MoneyColumn = dr.GetDecimal(16); } if (!dr.IsDBNull(17)) { satir.NcharColumn = dr.GetString(17); } if (!dr.IsDBNull(18)) { satir.NtextColumn = dr.GetString(18); } if (!dr.IsDBNull(19)) { satir.NumericColumn = dr.GetDecimal(19); } if (!dr.IsDBNull(20)) { satir.NvarcharColumn = dr.GetString(20); } if (!dr.IsDBNull(21)) { satir.NvarcharMaxColumn = dr.GetString(21); } if (!dr.IsDBNull(22)) { satir.RealColumn = dr.GetFloat(22); } if (!dr.IsDBNull(23)) { satir.SmallDateTimeColumn = dr.GetDateTime(23); } if (!dr.IsDBNull(24)) { satir.SmallIntColumn = dr.GetInt16(24); } if (!dr.IsDBNull(25)) { satir.SmallMoneyColumn = dr.GetDecimal(25); } if (!dr.IsDBNull(26)) { satir.SqlVariantColumn = dr.GetValue(26); } if (!dr.IsDBNull(27)) { satir.TextColumn = dr.GetString(27); } if (!dr.IsDBNull(28)) { satir.TimeColumn = TimeSpan(28); } if (!dr.IsDBNull(29)) { satir.TimestampColumn = (Byte[])dr.GetValue(29); } if (!dr.IsDBNull(30)) { satir.TinyIntColumn = dr.GetByte(30); } if (!dr.IsDBNull(31)) { satir.UniqueIdentifierColumn = dr.GetGuid(31); } if (!dr.IsDBNull(32)) { satir.VarBinaryColumn = (Byte[])dr.GetValue(32); } if (!dr.IsDBNull(33)) { satir.VarBinaryMaxColumn = (Byte[])dr.GetValue(33); } if (!dr.IsDBNull(34)) { satir.VarCharColumn = dr.GetString(34); } if (!dr.IsDBNull(35)) { satir.VarCharMaxColumn = dr.GetString(35); } if (!dr.IsDBNull(36)) { satir.XmlColumn = dr.GetString(36); } } protected override void InsertCommandParametersAdd(DbCommand cmd, ButunVeriYapilari2008r2 satir) { ParameterBuilder builder = Template.getParameterBuilder(); builder.Command = cmd; builder.parameterEkle("@BigIntColumn",SqlDbType.BigInt, satir.BigIntColumn); builder.parameterEkle("@BinaryColumn",SqlDbType.Binary, satir.BinaryColumn); builder.parameterEkle("@BitColumn",SqlDbType.Bit, satir.BitColumn); builder.parameterEkle("@CharColumn",SqlDbType.Char, satir.CharColumn,10); builder.parameterEkle("@DateColumn",SqlDbType.date, satir.DateColumn); builder.parameterEkle("@DateTimeColumn",SqlDbType.DateTime, satir.DateTimeColumn); builder.parameterEkle("@DateTime2Column",SqlDbType.datetime2, satir.DateTime2column); builder.parameterEkle("@DateTimeOffsetColumn",SqlDbType.datetimeoffset, satir.DateTimeOffsetColumn); builder.parameterEkle("@DecimalColumn",SqlDbType.Decimal, satir.DecimalColumn); builder.parameterEkle("@FloatColumn",SqlDbType.Float, satir.FloatColumn); builder.parameterEkle("@GeopgraphyColummn",SqlDbType.geography, satir.GeopgraphyColummn); builder.parameterEkle("@GeometryColumn",SqlDbType.geometry, satir.GeometryColumn); builder.parameterEkle("@HierarchyIdColumn",SqlDbType.hierarchyid, satir.HierarchyIdColumn); builder.parameterEkle("@ImageColumn",SqlDbType.Image, satir.ImageColumn); builder.parameterEkle("@IntColumn",SqlDbType.Int, satir.IntColumn); builder.parameterEkle("@MoneyColumn",SqlDbType.Money, satir.MoneyColumn); builder.parameterEkle("@NCharColumn",SqlDbType.NChar, satir.NcharColumn,10); builder.parameterEkle("@NTextColumn",SqlDbType.NText, satir.NtextColumn); builder.parameterEkle("@NumericColumn",SqlDbType.Decimal, satir.NumericColumn); builder.parameterEkle("@NVarcharColumn",SqlDbType.NVarChar, satir.NvarcharColumn,50); builder.parameterEkle("@NVarcharMaxColumn",SqlDbType.NVarChar, satir.NvarcharMaxColumn,-1); builder.parameterEkle("@RealColumn",SqlDbType.Real, satir.RealColumn); builder.parameterEkle("@smallDateTimeColumn",SqlDbType.SmallDateTime, satir.SmallDateTimeColumn); builder.parameterEkle("@smallIntColumn",SqlDbType.SmallInt, satir.SmallIntColumn); builder.parameterEkle("@SmallMoneyColumn",SqlDbType.SmallMoney, satir.SmallMoneyColumn); builder.parameterEkle("@SqlVariantColumn",SqlDbType.Variant, satir.SqlVariantColumn); builder.parameterEkle("@TextColumn",SqlDbType.Text, satir.TextColumn); builder.parameterEkle("@TimeColumn",SqlDbType.time, satir.TimeColumn); builder.parameterEkle("@TinyIntColumn",SqlDbType.TinyInt, satir.TinyIntColumn); builder.parameterEkle("@UniqueIdentifierColumn",SqlDbType.UniqueIdentifier, satir.UniqueIdentifierColumn); builder.parameterEkle("@VarBinaryColumn",SqlDbType.VarBinary, satir.VarBinaryColumn); builder.parameterEkle("@VarBinaryMaxColumn",SqlDbType.VarBinary, satir.VarBinaryMaxColumn); builder.parameterEkle("@VarCharColumn",SqlDbType.VarChar, satir.VarCharColumn,50); builder.parameterEkle("@VarCharMaxColumn",SqlDbType.VarChar, satir.VarCharMaxColumn,-1); builder.parameterEkle("@XmlColumn",SqlDbType.Xml, satir.XmlColumn); } protected override void UpdateCommandParametersAdd(DbCommand cmd, ButunVeriYapilari2008r2 satir) { ParameterBuilder builder = Template.getParameterBuilder(); builder.Command = cmd; builder.parameterEkle("@ButunVeriYapilari2008R2Key",SqlDbType.Int, satir.ButunVeriYapilari2008r2key); builder.parameterEkle("@BigIntColumn",SqlDbType.BigInt, satir.BigIntColumn); builder.parameterEkle("@BinaryColumn",SqlDbType.Binary, satir.BinaryColumn); builder.parameterEkle("@BitColumn",SqlDbType.Bit, satir.BitColumn); builder.parameterEkle("@CharColumn",SqlDbType.Char, satir.CharColumn,10); builder.parameterEkle("@DateColumn",SqlDbType.date, satir.DateColumn); builder.parameterEkle("@DateTimeColumn",SqlDbType.DateTime, satir.DateTimeColumn); builder.parameterEkle("@DateTime2Column",SqlDbType.datetime2, satir.DateTime2column); builder.parameterEkle("@DateTimeOffsetColumn",SqlDbType.datetimeoffset, satir.DateTimeOffsetColumn); builder.parameterEkle("@DecimalColumn",SqlDbType.Decimal, satir.DecimalColumn); builder.parameterEkle("@FloatColumn",SqlDbType.Float, satir.FloatColumn); builder.parameterEkle("@GeopgraphyColummn",SqlDbType.geography, satir.GeopgraphyColummn); builder.parameterEkle("@GeometryColumn",SqlDbType.geometry, satir.GeometryColumn); builder.parameterEkle("@HierarchyIdColumn",SqlDbType.hierarchyid, satir.HierarchyIdColumn); builder.parameterEkle("@ImageColumn",SqlDbType.Image, satir.ImageColumn); builder.parameterEkle("@IntColumn",SqlDbType.Int, satir.IntColumn); builder.parameterEkle("@MoneyColumn",SqlDbType.Money, satir.MoneyColumn); builder.parameterEkle("@NCharColumn",SqlDbType.NChar, satir.NcharColumn,10); builder.parameterEkle("@NTextColumn",SqlDbType.NText, satir.NtextColumn); builder.parameterEkle("@NumericColumn",SqlDbType.Decimal, satir.NumericColumn); builder.parameterEkle("@NVarcharColumn",SqlDbType.NVarChar, satir.NvarcharColumn,50); builder.parameterEkle("@NVarcharMaxColumn",SqlDbType.NVarChar, satir.NvarcharMaxColumn,-1); builder.parameterEkle("@RealColumn",SqlDbType.Real, satir.RealColumn); builder.parameterEkle("@smallDateTimeColumn",SqlDbType.SmallDateTime, satir.SmallDateTimeColumn); builder.parameterEkle("@smallIntColumn",SqlDbType.SmallInt, satir.SmallIntColumn); builder.parameterEkle("@SmallMoneyColumn",SqlDbType.SmallMoney, satir.SmallMoneyColumn); builder.parameterEkle("@SqlVariantColumn",SqlDbType.Variant, satir.SqlVariantColumn); builder.parameterEkle("@TextColumn",SqlDbType.Text, satir.TextColumn); builder.parameterEkle("@TimeColumn",SqlDbType.time, satir.TimeColumn); builder.parameterEkle("@TinyIntColumn",SqlDbType.TinyInt, satir.TinyIntColumn); builder.parameterEkle("@UniqueIdentifierColumn",SqlDbType.UniqueIdentifier, satir.UniqueIdentifierColumn); builder.parameterEkle("@VarBinaryColumn",SqlDbType.VarBinary, satir.VarBinaryColumn); builder.parameterEkle("@VarBinaryMaxColumn",SqlDbType.VarBinary, satir.VarBinaryMaxColumn); builder.parameterEkle("@VarCharColumn",SqlDbType.VarChar, satir.VarCharColumn,50); builder.parameterEkle("@VarCharMaxColumn",SqlDbType.VarChar, satir.VarCharMaxColumn,-1); builder.parameterEkle("@XmlColumn",SqlDbType.Xml, satir.XmlColumn); } protected override void DeleteCommandParametersAdd(DbCommand cmd, ButunVeriYapilari2008r2 satir) { ParameterBuilder builder = Template.getParameterBuilder(); builder.Command = cmd; builder.parameterEkle("@ButunVeriYapilari2008R2Key",SqlDbType.Int, satir.ButunVeriYapilari2008r2key); } public override string DbProviderName { get { return "System.Data.SqlClient"; } } } }
using System.Text.RegularExpressions; namespace GitHubDependentsScraper { public static class UrlUtil { private static readonly Regex _urlReplacer = new Regex(@"[:/]|https://github.com|(\?.*)", RegexOptions.Compiled); private static readonly Regex _dependentsAfterMatcher = new Regex(@"dependents_after=(.*)", RegexOptions.Compiled); public static string GetUrlPathSafe(string url) { return _urlReplacer.Replace(url, string.Empty); } public static string GetDependentsAfter(string url) { Match match = _dependentsAfterMatcher.Match(url); if (match.Success && match.Groups.Count > 1) { return match.Groups[1].Value; } return null; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Stack : MonoBehaviour { public ChangeColors changeColorsScript; public TileMovement tileMovementScript; public Material stackMaterial; public GameManager gm; private const float BOUNDS_SIZE = 3.5f; private const float STACK_MOVING_SPEED = 5f; private const float ERROR_MARGIN = 0.1f; private const float STACK_BOUNDS_GAIN = 0.25f; private const float COMBO_START_GAIN = 3f; private GameObject[] theStack; private Vector2 stackBounds = new Vector2(BOUNDS_SIZE, BOUNDS_SIZE); private int stackIndex; private int scoreCount = 0; private int combo = 0; private float secondaryPosition; private bool isMovingX = true; private bool GameOver = false; private Vector3 desiredPosition; private Vector3 lastTilePosition; // Start is called before the first frame update void Start() { gm = FindObjectOfType<GameManager>(); theStack = new GameObject[transform.childCount]; for (int i = 0; i < transform.childCount; i++) { theStack[i] = transform.GetChild(i).gameObject; changeColorsScript.ColorMesh(theStack[i].GetComponent<MeshFilter>().mesh, scoreCount); } stackIndex = transform.childCount - 1; } // Update is called once per frame void Update() { if (GameOver) { //call game manager restart gm.restartGame(); } if (Input.GetMouseButtonDown(0)) { if (PlaceTile()) { SpawnTile(); scoreCount++; } else { //endgame GameOver = true; } } tileMovementScript.MoveTile(isMovingX, theStack[stackIndex], scoreCount, secondaryPosition); //move stack transform.position = Vector3.Lerp(transform.position, desiredPosition, STACK_MOVING_SPEED * Time.deltaTime); } bool PlaceTile() { //get the current stack Transform t = theStack[stackIndex].transform; if (isMovingX) { float deltaX = lastTilePosition.x - t.position.x; if (Mathf.Abs(deltaX) > ERROR_MARGIN) { combo = 0; stackBounds.x -= Mathf.Abs(deltaX); if (stackBounds.x <= 0) { return false; } float middle = lastTilePosition.x + t.localPosition.x / 2; t.localScale = new Vector3(stackBounds.x, 1f, stackBounds.y); //create the part that is fall down CreateRubble( new Vector3( (t.position.x > 0) ? t.position.x + (t.localScale.x / 2f) : t.position.x - (t.localScale.x / 2f) , t.position.y, t.position.z), new Vector3(Mathf.Abs(deltaX), 1f, t.localScale.z)); t.localPosition = new Vector3(middle - (lastTilePosition.x / 2f), scoreCount, lastTilePosition.z); } else { if (combo > COMBO_START_GAIN) { stackBounds.x += STACK_BOUNDS_GAIN; if (stackBounds.x > BOUNDS_SIZE) { stackBounds.x = BOUNDS_SIZE; } float middle = lastTilePosition.x + t.localPosition.x / 2f; t.localScale = new Vector3(stackBounds.x, 1f, stackBounds.y); t.localPosition = new Vector3(middle - (lastTilePosition.x / 2f), scoreCount, lastTilePosition.z); } combo++; t.localPosition = new Vector3(lastTilePosition.x, scoreCount, lastTilePosition.z); } } else { float deltaZ = lastTilePosition.z - t.position.z; if (Mathf.Abs(deltaZ) > ERROR_MARGIN) { combo = 0; stackBounds.y -= Mathf.Abs(deltaZ); if (stackBounds.y <= 0) { return false; } float middle = lastTilePosition.z + t.localPosition.z / 2f; t.localScale = new Vector3(stackBounds.x, 1f, stackBounds.y); CreateRubble(new Vector3( t.position.x, t.position.y, (t.position.z > 0) ? t.position.z + (t.localScale.z / 2f) : t.position.z - (t.localScale.z / 2f)), new Vector3(t.localScale.x, 1f, Mathf.Abs(deltaZ)) ); t.localPosition = new Vector3(lastTilePosition.x, scoreCount, middle - (lastTilePosition.z / 2f)); } else { if (combo > COMBO_START_GAIN) { stackBounds.y += COMBO_START_GAIN; if (stackBounds.y > BOUNDS_SIZE) { stackBounds.y = BOUNDS_SIZE; } float middle = lastTilePosition.z + t.localPosition.z / 2f; t.localScale = new Vector3(stackBounds.x, 1f, stackBounds.y); t.localPosition = new Vector3(lastTilePosition.x / 2f, scoreCount, middle - (lastTilePosition.z / 2f)); } combo++; t.localPosition = new Vector3(lastTilePosition.x, scoreCount, lastTilePosition.z); } }//else moving on z secondaryPosition = (isMovingX) ? t.localPosition.x : t.localPosition.z; isMovingX = !isMovingX; return true; }//place tile void CreateRubble(Vector3 pos, Vector3 scale) { GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube); go.transform.localPosition = pos; go.transform.localScale = scale; go.AddComponent<Rigidbody>(); go.GetComponent<MeshRenderer>().material = stackMaterial; changeColorsScript.ColorMesh(go.GetComponent<MeshFilter>().mesh, scoreCount); }//create rubble void SpawnTile() { lastTilePosition = theStack[stackIndex].transform.localPosition; stackIndex--; if (stackIndex < 0) { stackIndex = transform.childCount - 1; } desiredPosition = Vector3.down * scoreCount; theStack[stackIndex].transform.localPosition = new Vector3(0f, scoreCount, 0f); theStack[stackIndex].transform.localScale = new Vector3(stackBounds.x, 1f, stackBounds.y); changeColorsScript.ColorMesh(theStack[stackIndex].GetComponent<MeshFilter>().mesh, scoreCount); } public int getScoreCount() { return scoreCount; } }//end of main class
 public interface GrabItemIF { bool IsGrabable(); void BeGrab(); void BeRelease(); void Selected(); void Deselected(); void GrabableHighlight(); void GrabableDehighlight(); void ChangeGrabableState(bool _grabable); void ChangeBeingGrabedState(bool _being_grabed); }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class DeathKnight : Enemy { [SerializeField] GameObject sword; protected override void Init() { base.Init(); state = EnemyState.Move; ChooseRandomDirection(); } void Update() { if (GameManager.Instance.IsInGame) { if (state == EnemyState.Move) { Move(Time.deltaTime); } else if (state == EnemyState.Attack) { sword.transform.Rotate(Vector3.forward, -90 * Time.deltaTime); } } } protected override void ChangeState() { if (state == EnemyState.Move) { state = EnemyState.Attack; Attack(); Timer secondSwipeTimer = new Timer(1); secondSwipeTimer.OnComplete.AddListener(Attack); secondSwipeTimer.Start(); } else if (state == EnemyState.Attack) { state = EnemyState.Idle; HideSword(); } else { state = EnemyState.Move; ChooseRandomDirection(); } } void Attack() { sword.SetActive(true); sword.transform.localPosition = forward; sword.transform.localRotation = Quaternion.AngleAxis(-45, Vector3.up); } void HideSword() { sword.SetActive(false); } }
using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider; using System.Windows.Controls; using System.Windows.Input; namespace WPFNotificationSimulation { public partial class MainWindow : Window { private string notificationGuid = "5A5CA7F5-5683-4021-9821-B581DA0B3F26"; public MainWindow() { InitializeComponent(); } private void InputWindow_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { var input = InputWindowTB.Text.Trim(); if (input.Length > 0) { var response = "This is the response to " + input; ImmediateWindowTB.RaiseNotificationEvent( response, notificationGuid); ImmediateWindowTB.Text += response + "\r\n"; InputWindowTB.Text = ""; } e.Handled = true; } } } public class NotificationTextBlock : TextBlock { // This control's AutomationPeer is the object that actually raises the UIA Notification event. private NotificationTextBlockAutomationPeer _peer; // Assume the UIA Notification event is available until we learn otherwise. // If we learn that the UIA Notification event is not available, no instance // of the NotificationTextBlock should attempt to raise it. static private bool _notificationEventAvailable = true; public bool NotificationEventAvailable { get { return _notificationEventAvailable; } set { _notificationEventAvailable = value; } } protected override AutomationPeer OnCreateAutomationPeer() { this._peer = new NotificationTextBlockAutomationPeer(this); return this._peer; } public void RaiseNotificationEvent(string notificationText, string notificationGuid) { // Only attempt to raise the event if we already have an AutomationPeer. if (this._peer != null) { this._peer.RaiseNotificationEvent(notificationText, notificationGuid); } } } internal class NotificationTextBlockAutomationPeer : TextBlockAutomationPeer { private NotificationTextBlock _notificationTextBlock; // The UIA Notification event requires the IRawElementProviderSimple // associated with this AutomationPeer. private IRawElementProviderSimple _reps; public NotificationTextBlockAutomationPeer(NotificationTextBlock owner) : base(owner) { this._notificationTextBlock = owner; } public void RaiseNotificationEvent(string notificationText, string notificationGuid) { // If we already know that the UIA Notification event is not available, do not // attempt to raise it. if (this._notificationTextBlock.NotificationEventAvailable) { // If no UIA clients are listening for events, don't bother raising one. if (NativeMethods.UiaClientsAreListening()) { // Get the IRawElementProviderSimple for this AutomationPeer if we don't // have it already. if (this._reps == null) { AutomationPeer peer = FrameworkElementAutomationPeer.FromElement(this._notificationTextBlock); if (peer != null) { this._reps = ProviderFromPeer(peer); } } if (this._reps != null) { try { // Todo: The NotificationKind and NotificationProcessing values shown here // are sample values for this snippet. You should use whatever values are // appropriate for your scenarios. NativeMethods.UiaRaiseNotificationEvent( this._reps, NativeMethods.AutomationNotificationKind.ActionCompleted, NativeMethods.AutomationNotificationProcessing.ImportantMostRecent, notificationText, notificationGuid); } catch (EntryPointNotFoundException) { // The UIA Notification event is not not available, so don't attempt // to raise it again. _notificationTextBlock.NotificationEventAvailable = false; } } } } } internal class NativeMethods { public enum AutomationNotificationKind { ItemAdded = 0, ItemRemoved = 1, ActionCompleted = 2, ActionAborted = 3, Other = 4 } public enum AutomationNotificationProcessing { ImportantAll = 0, ImportantMostRecent = 1, All = 2, MostRecent = 3, CurrentThenMostRecent = 4 } // Add a reference to UIAutomationProvider. [DllImport("UIAutomationCore.dll", CharSet = CharSet.Unicode)] public static extern int UiaRaiseNotificationEvent( IRawElementProviderSimple provider, AutomationNotificationKind notificationKind, AutomationNotificationProcessing notificationProcessing, string notificationText, string notificationGuid); [DllImport("UIAutomationCore.dll")] public static extern bool UiaClientsAreListening(); } } }