text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace LateOS.Models { [MetadataType(typeof(cDevolucion))] public partial class tbDevolucion { } public class cDevolucion { [Display(Name = "ID Devolución")] public Nullable<int> dev_Id { get; set; } [Display(Name = "ID Factura")] public int fact_Id { get; set; } [Display(Name = "Razón Devolución")] //[Required(AllowEmptyStrings = false, ErrorMessage = "El campo {0} de requerido.")] [MaxLength(250, ErrorMessage = "Excedió el máximo de caracteres permitidos.")] public string dev_Razon { get; set; } [Display(Name = "Fecha Devolución")] //[Required(AllowEmptyStrings = false, ErrorMessage = "El campo {0} de requerido.")] public Nullable<System.DateTime> dev_Fecha { get; set; } public int dev_UsuarioCrea { get; set; } public Nullable<System.DateTime> dev_FechaCrea { get; set; } public Nullable<int> dev_UsuarioModifica { get; set; } public Nullable<System.DateTime> dev_FechaModifica { get; set; } } }
using System; using Sandbox; namespace PermissionSystem { public class PermissionPlayer : Player { public static event Func<PlayerHasPermissionEventArgs, PlayerHasPermissionEventArgs> PlayerHasPermissionEvent; /// <summary> /// Does this player have permission to run this command? /// </summary> /// <param name="command">Command you want to test</param> /// <returns></returns> public bool HasCustomPermission(string command) { if (!this.IsValid()) { return false; } var args = new PlayerHasPermissionEventArgs(this, command); Permissions.InvokePlayerHasPermissionEvent(args); PlayerHasPermissionEvent?.Invoke(args); return args.HasPermission; } } }
using System; using System.Data; using System.Collections.Generic; using Maticsoft.Common; using PDTech.OA.Model; namespace PDTech.OA.BLL { /// <summary> /// 流程模板定义表 /// </summary> public partial class WORKFLOW_TEMPLATE { private readonly PDTech.OA.DAL.WORKFLOW_TEMPLATE dal = new PDTech.OA.DAL.WORKFLOW_TEMPLATE(); public WORKFLOW_TEMPLATE() { } #region BasicMethod /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(decimal FLOW_TEMPLATE_ID) { return dal.Exists(FLOW_TEMPLATE_ID); } /// <summary> /// 增加一条数据 /// </summary> public bool Add(PDTech.OA.Model.WORKFLOW_TEMPLATE model) { return dal.Add(model); } /// <summary> /// 更新一条数据 /// </summary> public bool Update(PDTech.OA.Model.WORKFLOW_TEMPLATE model) { return dal.Update(model); } /// <summary> /// 删除一条数据 /// </summary> public bool Delete(decimal FLOW_TEMPLATE_ID) { return dal.Delete(FLOW_TEMPLATE_ID); } #endregion BasicMethod /// <summary> /// 查询风险模块--日常办公公文 /// </summary> /// <returns>返回给下拉框</returns> public IList<Model.OA_RISK_MODULE> GetRiskModule() { return dal.GetRiskModule(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NowPlaying.XApplication.Database; namespace NowPlaying.XApplication { public static class AppInitializer { public static void Initialize() { TrackDbStore.InitializeDbStore(); } } }
using SharpShell.Attributes; using SharpShell.SharpContextMenu; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace HashProp { [ComVisible(true)] [COMServerAssociation(AssociationType.AllFiles)] public class HashContextMenu : SharpContextMenu { protected override bool CanShowMenu() { return (SelectedItemPaths.Count() == 1); } protected override ContextMenuStrip CreateMenu() { var menu = new ContextMenuStrip(); var menuItem = new ToolStripMenuItem("Hash..."); menuItem.Click += ShowHashWindow; menu.Items.Add(menuItem); return menu; } void ShowHashWindow(object sender, EventArgs e) { var win = new HashWindow(SelectedItemPaths.First()); win.Show(); } } }
// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Minor Code Smell", "S1128:Unused \"using\" should be removed", Justification = "<Ожидание>")] [assembly: SuppressMessage("Minor Code Smell", "S3626:Jump statements should not be redundant", Justification = "<Ожидание>")] [assembly: SuppressMessage("Critical Code Smell", "S3973:A conditionally executed single line should be denoted by indentation", Justification = "<Ожидание>")] [assembly: SuppressMessage("Major Code Smell", "S1066:Collapsible \"if\" statements should be merged", Justification = "<Ожидание>")] [assembly: SuppressMessage("Major Code Smell", "S125:Sections of code should not be commented out", Justification = "<Ожидание>")] [assembly: SuppressMessage("Major Code Smell", "S1117:Local variables should not shadow class fields", Justification = "<Ожидание>")] [assembly: SuppressMessage("Major Code Smell", "S125:Sections of code should not be commented out", Justification = "<Ожидание>")] [assembly: SuppressMessage("Minor Code Smell", "S3626:Jump statements should not be redundant", Justification = "<Ожидание>")] [assembly: SuppressMessage("Minor Bug", "S3887:Mutable, non-private fields should not be \"readonly\"", Justification = "<Ожидание>")]
using System.Collections; using System.Collections.Generic; using UnityEngine; using Interface2; public class csInterfaceUse : MonoBehaviour { IUserName playerState; IUserName UserName; ItemUse<int> item; // Start is called before the first frame update void Start() { playerState = new PlayerState2("WooPro"); Debug.Log(playerState.UserName); item = new ItemUse<int>(); item.Fct1(5); item.Method(5); } // Update is called once per frame void Update() { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class BulletList : MonoBehaviour { const int MAX_BULLET_COUNT = 9; public GameObject bulletUI; GameObject bulletUsingPanel, starShooterUI, obentouUI, barrierUI, kiriJetUI, zundaBombUI; Text bulletListText; Shooter shooter; int havingShooter; BulletGauge[] statShooterBulletList = new BulletGauge[MAX_BULLET_COUNT]; BulletGauge[] obentouBulletList = new BulletGauge[MAX_BULLET_COUNT]; BulletGauge[] electricBarrierBulletList = new BulletGauge[MAX_BULLET_COUNT]; BulletGauge[] kiriJetBulletList = new BulletGauge[MAX_BULLET_COUNT]; BulletGauge[] zundaBombBulletList = new BulletGauge[MAX_BULLET_COUNT]; // Start is called before the first frame update void Start() { bulletListText = GameObject.Find("BulletList").GetComponent<Text>(); shooter = GameObject.Find("HandPivot").GetComponent<Shooter>(); havingShooter = StaticValues.havingShooter; bulletUsingPanel = GameObject.Find("BulletUsingPanel"); starShooterUI = GameObject.Find("StarShooterUI"); obentouUI = GameObject.Find("ObentouUI"); barrierUI = GameObject.Find("BarrierUI"); kiriJetUI = GameObject.Find("KiriJetUI"); zundaBombUI = GameObject.Find("ZundaBombUI"); CreateBulletListUI(statShooterBulletList, new Vector2(13, -20), 0.5f, Shooter.SubWeaponType.StarShooter); CreateBulletListUI(obentouBulletList, new Vector2(45, -55), 10000.0f, Shooter.SubWeaponType.Obentou); CreateBulletListUI(electricBarrierBulletList, new Vector2(45, -90), 10000.0f, Shooter.SubWeaponType.ElectricBarrier); CreateBulletListUI(kiriJetBulletList, new Vector2(45, -125), 2.0f, Shooter.SubWeaponType.KiriJet); CreateBulletListUI(zundaBombBulletList, new Vector2(45, -160), 2.0f, Shooter.SubWeaponType.ZundaBomb); } private void CreateBulletListUI(BulletGauge[] bulletGaugeList, Vector2 firstPosition, float reloadTime, Shooter.SubWeaponType subWeaponType) { for (int i = 0; i < MAX_BULLET_COUNT; i++) { GameObject obj = Instantiate(bulletUI); obj.transform.SetParent(transform); obj.transform.localPosition = new Vector2(firstPosition.x + i * 15, firstPosition.y); obj.transform.localScale = new Vector2(1, 1); bulletGaugeList[i] = obj.GetComponent<BulletGauge>(); bulletGaugeList[i].SetReloadTime(reloadTime); bulletGaugeList[i].SetSubWeaponType(subWeaponType); } } // Update is called once per frame void Update() { bulletUsingPanel.SetActive(StaticValues.havingShooter >= 1); UpdateBulletList(statShooterBulletList, starShooterUI, StaticValues.starShooterBulletMax, StaticValues.starShooterBullet, Shooter.SubWeaponType.StarShooter); UpdateBulletList(obentouBulletList, obentouUI, StaticValues.obentouBulletMax, StaticValues.obentouBullet, Shooter.SubWeaponType.Obentou); UpdateBulletList(electricBarrierBulletList, barrierUI, StaticValues.electricBarrierBulletMax, StaticValues.electricBarrierBullet, Shooter.SubWeaponType.ElectricBarrier); UpdateBulletList(kiriJetBulletList, kiriJetUI, StaticValues.kiriJetBulletMax, StaticValues.kiriJetBullet, Shooter.SubWeaponType.KiriJet); UpdateBulletList(zundaBombBulletList, zundaBombUI, StaticValues.zundaBombBulletMax, StaticValues.zundaBombBullet, Shooter.SubWeaponType.ZundaBomb); } void UpdateBulletList(BulletGauge[] bulletGaugeList, GameObject bulletNameUI, int maxBulletCount, int nowBulletCount, Shooter.SubWeaponType subWeaponType) { float time = 0; // 画面遷移直後等でリロード中の弾が無い時はStaticValuesで持ってるリロード時間を使う switch (subWeaponType) { case Shooter.SubWeaponType.StarShooter: time = StaticValues.starShooterBulletReloadTime; break; case Shooter.SubWeaponType.Obentou: time = StaticValues.obentouBulletReloadTime; break; case Shooter.SubWeaponType.ElectricBarrier: time = StaticValues.electricBarrierBulletReloadTime; break; } for (int i = 0; i < MAX_BULLET_COUNT; i++) { bulletGaugeList[i].gameObject.SetActive(i < maxBulletCount); if ((int)subWeaponType > StaticValues.havingShooter) { bulletGaugeList[i].gameObject.SetActive(false); bulletNameUI.SetActive(false); } else { bulletNameUI.SetActive(true); } } for (int i = 0; i < maxBulletCount; i++) { switch (bulletGaugeList[i].GetState()) { case BulletGauge.State.Reloaded: shooter.ReloadShooter(subWeaponType); bulletGaugeList[i].Reload(); time = 0; break; case BulletGauge.State.Reloading: time = bulletGaugeList[i].GetTime(); break; case BulletGauge.State.NotAvailable: case BulletGauge.State.Available: break; } } for (int i = 0; i < maxBulletCount; i++) { if (i < nowBulletCount) { bulletGaugeList[i].SetState(BulletGauge.State.Available); } else if (i == nowBulletCount) { bulletGaugeList[i].SetState(BulletGauge.State.Reloading); bulletGaugeList[i].SetTime(time); } else { bulletGaugeList[i].SetState(BulletGauge.State.NotAvailable); } } switch (subWeaponType) { case Shooter.SubWeaponType.StarShooter: StaticValues.starShooterBulletReloadTime = time; break; case Shooter.SubWeaponType.Obentou: StaticValues.obentouBulletReloadTime = time; break; case Shooter.SubWeaponType.ElectricBarrier: StaticValues.electricBarrierBulletReloadTime = time; break; } } }
using LuaInterface; using RO; using SLua; using System; using UnityEngine; public class Lua_RO_UIScrollViewEx : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { UIScrollViewEx o = new UIScrollViewEx(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_BoundTarget(IntPtr l) { int result; try { UIScrollViewEx uIScrollViewEx = (UIScrollViewEx)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, uIScrollViewEx.BoundTarget); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_BoundTarget(IntPtr l) { int result; try { UIScrollViewEx uIScrollViewEx = (UIScrollViewEx)LuaObject.checkSelf(l); GameObject boundTarget; LuaObject.checkType<GameObject>(l, 2, out boundTarget); uIScrollViewEx.BoundTarget = boundTarget; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_bounds(IntPtr l) { int result; try { UIScrollViewEx uIScrollViewEx = (UIScrollViewEx)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, uIScrollViewEx.bounds); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "RO.UIScrollViewEx"); LuaObject.addMember(l, "BoundTarget", new LuaCSFunction(Lua_RO_UIScrollViewEx.get_BoundTarget), new LuaCSFunction(Lua_RO_UIScrollViewEx.set_BoundTarget), true); LuaObject.addMember(l, "bounds", new LuaCSFunction(Lua_RO_UIScrollViewEx.get_bounds), null, true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_RO_UIScrollViewEx.constructor), typeof(UIScrollViewEx), typeof(UIScrollView)); } }
namespace PlatformRacing3.Common.Extensions; internal static class StringExtensions { internal static uint CountCharsSum(this string string_) { uint sum = 0; foreach(char char_ in string_) { sum += char_; } return sum; } }
namespace ZooApi.ApiBlueprint.Tests.TestBuilder { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Http; public class AstAction { public HttpMethod Method { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using CodeGen.MetaDataProviders; using CodeGen.Models; namespace MsSqlProvider { public class MsSqlMetaDataProvider : IMetaDataProvider { private readonly MsSqlController _mssqlController = new MsSqlController(); public MetaDataProviderType Type { get { return MetaDataProviderType.MsSql; } } private EntityItem GetEntityItemFromColumn(ColumnInfo column) { return new EntityItem() { Name = column.ColumnName, IsNullable = column.IsNullable, NativeDataType = column.DataType, Length = column.Length, NumericScale = column.NumericScale, NumericPrecision = column.NumericPrecision, DateTimePrecision = column.DateTimePrecision, }; } public Entity GetEntity(string entityName, MetaDataProviderArgs args = null) { if (args == null) { throw new InvalidOperationException("MetaDataProviderArgs argument cannot be null"); } var result = new Entity() { Name = entityName }; var columns = _mssqlController.GetColumns(entityName, args.ConnectionString); foreach (var column in columns) { var item = GetEntityItemFromColumn(column); result.Items.Add(item); } return result; } public IEnumerable<Entity> GetEntities(MetaDataProviderArgs args = null) { if (args == null) { throw new InvalidOperationException("MetaDataProviderArgs argument cannot be null"); } var results = new List<Entity>(); foreach (var table in _mssqlController.GetTables(args.ConnectionString)) { var entity = GetEntity(table.TableName, args); results.Add(entity); } return results; } } }
using System.Collections; namespace SubsciptionAPI.Code { public class ReturnObject { public ReturnObject() { RecordCount = 0; ErrorMsg = ""; } public IEnumerable DataList { get; set; } public string ErrorMsg { get; set; } public int RecordCount { get; set; } } }
using Checkout.Payment.Processor.Application.Models.Enums; using System; using System.ComponentModel.DataAnnotations; namespace Checkout.Payment.Processor.Application.Validations { public class CurrencyTypeAttribute : ValidationAttribute { public override bool IsValid(object value) { return Enum.TryParse(value.ToString(), out CurrencyTypeModel result); } public override string FormatErrorMessage(string name) { if (ErrorMessage == null && ErrorMessageResourceName == null) { ErrorMessage = "Invalid Currency [currency={0}]"; } return base.FormatErrorMessage(name); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyDropItem : MonoBehaviour { // Update is called once per frame private int hp; public int chanceToSpawnAnItem = 20; public GameObject[] items; void Update() { hp = gameObject.GetComponent<Enemy>().health; if (hp <= 0) { Destroy(gameObject); int itemChanceRoll = Random.Range(0, 100); if (itemChanceRoll >= 100 - chanceToSpawnAnItem) { GetComponent<Renderer>().enabled = true; GameObject itemToSpawn = items[Random.Range(0, items.Length - 1)]; Instantiate(itemToSpawn, new Vector3(transform.position.x, transform.position.y + 1.1f), Quaternion.identity); } else { GetComponent<Renderer>().enabled = false; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CinemalyticsCSharpSDK.Model; using CinemalyticsCSharpSDK.Util; using Newtonsoft.Json; namespace CinemalyticsCSharpSDK.Repository { public class SongRepository { private static SongRepository _instance; private static String _authToken = null; private SongRepository() { } public static SongRepository Instance { get { if (_instance == null) { _instance = new SongRepository(); } return _instance; } } internal void SetAuthToken(String authToken) { if (String.IsNullOrEmpty(_authToken)) { _authToken = authToken; } } /// <summary> /// Gets song by id /// </summary> /// <param name="songId"></param> /// <returns></returns> public Song GetSongById(String songId) { String url = "http://api.cinemalytics.in/v2/song/id/" + songId + "?auth_token=" + _authToken; String jsonResponse = UrlUtil.MakeGetCall(url); return JsonConvert.DeserializeObject<Song>(jsonResponse); } /// <summary> /// Gets songs by movieId /// </summary> /// <param name="movieId"></param> /// <returns></returns> public List<Song> GetSongsByMovieId(String movieId) { String url = "http://api.cinemalytics.in/v2/movie/" + movieId + "/songs/?auth_token=" + _authToken; String jsonResponse = UrlUtil.MakeGetCall(url); return JsonConvert.DeserializeObject<List<Song>>(jsonResponse); } /// <summary> /// Gets singers for song /// </summary> /// <param name="songId"></param> /// <returns></returns> public List<Singer> GetSingersForSong(String songId) { String url = "http://api.cinemalytics.in/v2/song/" + songId + "/singers/?auth_token=" + _authToken; String jsonResponse = UrlUtil.MakeGetCall(url); return JsonConvert.DeserializeObject<List<Singer>>(jsonResponse); } /// <summary> /// Gets latest songs /// </summary> /// <returns></returns> public List<Song> GetLatestSongs() { String url = "http://api.cinemalytics.in/v2/song/latest-songs/?auth_token=" + _authToken; String jsonResponse = UrlUtil.MakeGetCall(url); return JsonConvert.DeserializeObject<List<Song>>(jsonResponse); } } }
using Android.Graphics; using Plugin.CurrentActivity; using System.IO; using System.Threading.Tasks; using Kit.Droid.Services; using Kit.Services.Interfaces; using Bitmap = Android.Graphics.Bitmap; using View = Android.Views.View; [assembly: Xamarin.Forms.Dependency(typeof(Screenshot))] namespace Kit.Droid.Services { public class Screenshot : IScreenshot { public async Task<byte[]> Capture() { await Task.Yield(); View rootView = CrossCurrentActivity.Current.Activity.Window.DecorView.RootView; using (Bitmap screenshot = Android.Graphics.Bitmap.CreateBitmap( rootView.Width, rootView.Height, Android.Graphics.Bitmap.Config.Argb8888)) { Canvas canvas = new (screenshot); rootView.Draw(canvas); using (MemoryStream stream = new ()) { screenshot.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 90, stream); return stream.ToArray(); } } } } }
using System; class ReversedString { static void Main() { Console.WriteLine("Enter a string: "); string input = Console.ReadLine(); char[] reversed = input.ToCharArray(); Array.Reverse(reversed); string output = new string(reversed); Console.WriteLine("Your reversed string: " + output); } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Text; namespace SSTypes.Tests { [TestClass] public class SmartDoubleTests { [TestMethod] public void SmartDouble_Parse_String_Test() { #region Similar to SmartInt // Leading zeros Assert.AreEqual((double)SmartDouble.Parse("0"), 0, "Parsing \"0\""); Assert.AreEqual((double)SmartDouble.Parse("01"), 1, "Parsing \"01\""); Assert.AreEqual((double)SmartDouble.Parse("001"), 1, "Parsing \"001\""); Assert.AreEqual((double)SmartDouble.Parse("0001"), 1, "Parsing \"0001\""); Assert.AreEqual((double)SmartDouble.Parse("00001"), 1, "Parsing \"00001\""); Assert.AreEqual((double)SmartDouble.Parse("000001"), 1, "Parsing \"000001\""); Assert.AreEqual((double)SmartDouble.Parse("0000001"), 1, "Parsing \"0000001\""); Assert.AreEqual((double)SmartDouble.Parse("0123"), 123, "Parsing \"0123\""); Assert.AreEqual((double)SmartDouble.Parse("00123"), 123, "Parsing \"00123\""); Assert.AreEqual((double)SmartDouble.Parse("000123"), 123, "Parsing \"000123\""); Assert.AreEqual((double)SmartDouble.Parse("0000123"), 123, "Parsing \"0000123\""); Assert.AreEqual((double)SmartDouble.Parse("00000123"), 123, "Parsing \"00000123\""); Assert.AreEqual((double)SmartDouble.Parse("000000123"), 123, "Parsing \"000000123\""); // Negative Leading zeros Assert.AreEqual((double)SmartDouble.Parse("-0"), -0, "Parsing \"-0\""); // double32.Parse("-0") throws here Assert.AreEqual((double)SmartDouble.Parse("-01"), -1, "Parsing \"-01\""); Assert.AreEqual((double)SmartDouble.Parse("-001"), -1, "Parsing \"-001\""); Assert.AreEqual((double)SmartDouble.Parse("-0001"), -1, "Parsing \"-0001\""); Assert.AreEqual((double)SmartDouble.Parse("-00001"), -1, "Parsing \"-00001\""); Assert.AreEqual((double)SmartDouble.Parse("-000001"), -1, "Parsing \"-000001\""); Assert.AreEqual((double)SmartDouble.Parse("-0000001"), -1, "Parsing \"-0000001\""); Assert.AreEqual((double)SmartDouble.Parse("-0123"), -123, "Parsing \"-0123\""); Assert.AreEqual((double)SmartDouble.Parse("-00123"), -123, "Parsing \"-00123\""); Assert.AreEqual((double)SmartDouble.Parse("-000123"), -123, "Parsing \"-000123\""); Assert.AreEqual((double)SmartDouble.Parse("-0000123"), -123, "Parsing \"-0000123\""); Assert.AreEqual((double)SmartDouble.Parse("-00000123"), -123, "Parsing \"-00000123\""); Assert.AreEqual((double)SmartDouble.Parse("-000000123"), -123, "Parsing \"-000000123\""); // Positively Sihned Leading zeros Assert.AreEqual((double)SmartDouble.Parse("+0"), 0, "Parsing \"+0\""); Assert.AreEqual((double)SmartDouble.Parse("+01"), 1, "Parsing \"+01\""); Assert.AreEqual((double)SmartDouble.Parse("+001"), 1, "Parsing \"+001\""); Assert.AreEqual((double)SmartDouble.Parse("+0001"), 1, "Parsing \"+0001\""); Assert.AreEqual((double)SmartDouble.Parse("+00001"), 1, "Parsing \"+00001\""); Assert.AreEqual((double)SmartDouble.Parse("+000001"), 1, "Parsing \"+000001\""); Assert.AreEqual((double)SmartDouble.Parse("+0000001"), 1, "Parsing \"+0000001\""); Assert.AreEqual((double)SmartDouble.Parse("+0123"), 123, "Parsing \"+0123\""); Assert.AreEqual((double)SmartDouble.Parse("+00123"), 123, "Parsing \"+00123\""); Assert.AreEqual((double)SmartDouble.Parse("+000123"), 123, "Parsing \"+000123\""); Assert.AreEqual((double)SmartDouble.Parse("+0000123"), 123, "Parsing \"+0000123\""); Assert.AreEqual((double)SmartDouble.Parse("+00000123"), 123, "Parsing \"+00000123\""); Assert.AreEqual((double)SmartDouble.Parse("+000000123"), 123, "Parsing \"+000000123\""); // Leading & Finaling Spaces Assert.AreEqual((double)SmartDouble.Parse(" 0 "), 0, "Parsing \" 0 \""); Assert.AreEqual((double)SmartDouble.Parse(" 01 "), 1, "Parsing \" 01 \""); Assert.AreEqual((double)SmartDouble.Parse(" 0123 "), 123, "Parsing \" 0123 \""); Assert.AreEqual((double)SmartDouble.Parse(" -0 "), 0, "Parsing \" -0 \""); Assert.AreEqual((double)SmartDouble.Parse(" -01 "), -1, "Parsing \" -01 \""); Assert.AreEqual((double)SmartDouble.Parse(" -0123 "), -123, "Parsing \" -0123 \""); Assert.AreEqual((double)SmartDouble.Parse(" +0 "), 0, "Parsing \" +0 \""); Assert.AreEqual((double)SmartDouble.Parse(" +01 "), 1, "Parsing \" +01 \""); Assert.AreEqual((double)SmartDouble.Parse(" +0123 "), 123, "Parsing \" +0123 \""); Assert.AreEqual((double)SmartDouble.Parse(" 0 "), 0, "Parsing \" 0 \""); Assert.AreEqual((double)SmartDouble.Parse(" 01 "), 1, "Parsing \" 01 \""); Assert.AreEqual((double)SmartDouble.Parse(" 0123 "), 123, "Parsing \" 0123 \""); Assert.AreEqual((double)SmartDouble.Parse(" -0 "), -0, "Parsing \" -0 \""); Assert.AreEqual((double)SmartDouble.Parse(" -01 "), -1, "Parsing \" -01 \""); Assert.AreEqual((double)SmartDouble.Parse(" -0123 "), -123, "Parsing \" -0123 \""); Assert.AreEqual((double)SmartDouble.Parse(" +0 "), 0, "Parsing \" +0 \""); Assert.AreEqual((double)SmartDouble.Parse(" +01 "), 1, "Parsing \" +01 \""); Assert.AreEqual((double)SmartDouble.Parse(" +0123 "), 123, "Parsing \" +0123 \""); // Leading Spaces Assert.AreEqual((double)SmartDouble.Parse(" 0"), 0, "Parsing \" 0\""); Assert.AreEqual((double)SmartDouble.Parse(" 01"), 1, "Parsing \" 01\""); Assert.AreEqual((double)SmartDouble.Parse(" 0123"), 123, "Parsing \" 0123\""); Assert.AreEqual((double)SmartDouble.Parse(" -0"), 0, "Parsing \" -0\""); Assert.AreEqual((double)SmartDouble.Parse(" -01"), -1, "Parsing \" -01\""); Assert.AreEqual((double)SmartDouble.Parse(" -0123"), -123, "Parsing \" -0123\""); Assert.AreEqual((double)SmartDouble.Parse(" +0"), 0, "Parsing \" +0\""); Assert.AreEqual((double)SmartDouble.Parse(" +01"), 1, "Parsing \" +01\""); Assert.AreEqual((double)SmartDouble.Parse(" +0123"), 123, "Parsing \" +0123\""); Assert.AreEqual((double)SmartDouble.Parse(" 0"), 0, "Parsing \" 0\""); Assert.AreEqual((double)SmartDouble.Parse(" 01"), 1, "Parsing \" 01\""); Assert.AreEqual((double)SmartDouble.Parse(" 0123"), 123, "Parsing \" 0123\""); Assert.AreEqual((double)SmartDouble.Parse(" -0"), -0, "Parsing \" -0\""); Assert.AreEqual((double)SmartDouble.Parse(" -01"), -1, "Parsing \" -01\""); Assert.AreEqual((double)SmartDouble.Parse(" -0123"), -123, "Parsing \" -0123\""); Assert.AreEqual((double)SmartDouble.Parse(" +0"), 0, "Parsing \" +0\""); Assert.AreEqual((double)SmartDouble.Parse(" +01"), 1, "Parsing \" +01\""); Assert.AreEqual((double)SmartDouble.Parse(" +0123"), 123, "Parsing \" +0123\""); // Finaling Spaces Assert.AreEqual((double)SmartDouble.Parse("0 "), 0, "Parsing \"0 \""); Assert.AreEqual((double)SmartDouble.Parse("01 "), 1, "Parsing \"01 \""); Assert.AreEqual((double)SmartDouble.Parse("0123 "), 123, "Parsing \"0123 \""); Assert.AreEqual((double)SmartDouble.Parse("-0 "), 0, "Parsing \"-0 \""); Assert.AreEqual((double)SmartDouble.Parse("-01 "), -1, "Parsing \"-01 \""); Assert.AreEqual((double)SmartDouble.Parse("-0123 "), -123, "Parsing \"-0123 \""); Assert.AreEqual((double)SmartDouble.Parse("+0 "), 0, "Parsing \"+0 \""); Assert.AreEqual((double)SmartDouble.Parse("+01 "), 1, "Parsing \"+01 \""); Assert.AreEqual((double)SmartDouble.Parse("+0123 "), 123, "Parsing \"+0123 \""); Assert.AreEqual((double)SmartDouble.Parse("0 "), 0, "Parsing \"0 \""); Assert.AreEqual((double)SmartDouble.Parse("01 "), 1, "Parsing \"01 \""); Assert.AreEqual((double)SmartDouble.Parse("0123 "), 123, "Parsing \"0123 \""); Assert.AreEqual((double)SmartDouble.Parse("-0 "), -0, "Parsing \"-0 \""); Assert.AreEqual((double)SmartDouble.Parse("-01 "), -1, "Parsing \"-01 \""); Assert.AreEqual((double)SmartDouble.Parse("-0123 "), -123, "Parsing \"-0123 \""); Assert.AreEqual((double)SmartDouble.Parse("+0 "), 0, "Parsing \"+0 \""); Assert.AreEqual((double)SmartDouble.Parse("+01 "), 1, "Parsing \"+01 \""); Assert.AreEqual((double)SmartDouble.Parse("+0123 "), 123, "Parsing \"+0123 \""); // Values that shall be parsed to SmartDouble.BadValue without throwing Assert.AreEqual(SmartDouble.Parse("").isBad(), true, "Parsing \"\""); Assert.AreEqual(SmartDouble.Parse(" ").isBad(), true, "Parsing \" \""); Assert.AreEqual(SmartDouble.Parse(" ").isBad(), true, "Parsing \" \""); Assert.AreEqual(SmartDouble.Parse(" -").isBad(), true, "Parsing \" -\""); Assert.AreEqual(SmartDouble.Parse(" +").isBad(), true, "Parsing \" +\""); Assert.AreEqual(SmartDouble.Parse("- ").isBad(), true, "Parsing \"- \""); Assert.AreEqual(SmartDouble.Parse("- ").isBad(), true, "Parsing \"+ \""); Assert.AreEqual(SmartDouble.Parse(" - ").isBad(), true, "Parsing \" - \""); Assert.AreEqual(SmartDouble.Parse(" + ").isBad(), true, "Parsing \" + \""); Assert.AreEqual(SmartDouble.Parse("-").isBad(), true, "Parsing \"-\""); Assert.AreEqual(SmartDouble.Parse("+").isBad(), true, "Parsing \"+\""); Assert.AreEqual(SmartDouble.Parse(null).isBad(), true, "Parsing null"); Assert.AreEqual(SmartDouble.Parse("abrakadabra").isBad(), true, "Parsing \"abrakadabra\""); // Assert.AreEqual(SmartDouble.Parse("1.0").isBad(), true, "Parsing \"1.0\""); Assert.AreEqual(SmartDouble.Parse("1 m.").isBad(), true, "Parsing \"1 m.\""); Assert.AreEqual(SmartDouble.Parse("x1").isBad(), true, "Parsing \"x1\""); // Extremal values that shall be parsed to SmartDouble.BadValue without throwing // Digits { int strlen = 16 * 1024; StringBuilder sb = new StringBuilder(strlen); for (int i = 0; i < strlen; i++) sb.Append((i % 10).ToString()); Assert.AreEqual(SmartDouble.Parse(sb.ToString()).isBad(), true, "Parsing \"Extremal, Digits\""); } // Letters { int strlen = 16 * 1024; StringBuilder sb = new StringBuilder(strlen); for (int i = 0; i < strlen; i++) sb.Append("A" + (i % 10)); Assert.AreEqual(SmartDouble.Parse(sb.ToString()).isBad(), true, "Parsing \"Extremal, Letters\""); } #endregion #region Doubles Assert.AreEqual((double)SmartDouble.Parse(".34"), 0.34, "Parsing \".34\""); Assert.AreEqual((double)SmartDouble.Parse("-.34"), -0.34, "Parsing \"-.34\""); Assert.AreEqual((double)SmartDouble.Parse("+.34"), 0.34, "Parsing \"+.34\""); Assert.AreEqual((double)SmartDouble.Parse(" .34 "), 0.34, "Parsing \" .34 \""); Assert.AreEqual((double)SmartDouble.Parse(" -.34 "), -0.34, "Parsing \" -.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" +.34 "), 0.34, "Parsing \" +.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" .34"), 0.34, "Parsing \" .34\""); Assert.AreEqual((double)SmartDouble.Parse(" -.34"), -0.34, "Parsing \" -.34\""); Assert.AreEqual((double)SmartDouble.Parse(" +.34"), 0.34, "Parsing \" +.34\""); Assert.AreEqual((double)SmartDouble.Parse(".34 "), 0.34, "Parsing \".34 \""); Assert.AreEqual((double)SmartDouble.Parse("-.34 "), -0.34, "Parsing \"-.34 \""); Assert.AreEqual((double)SmartDouble.Parse("+.34 "), 0.34, "Parsing \"+.34 \""); // Leading zeros Assert.AreEqual((double)SmartDouble.Parse("0.34"), 0.34, "Parsing \"0.34\""); Assert.AreEqual((double)SmartDouble.Parse("01.34"), 1.34, "Parsing \"01.34\""); Assert.AreEqual((double)SmartDouble.Parse("001.34"), 1.34, "Parsing \"001.34\""); Assert.AreEqual((double)SmartDouble.Parse("0001.34"), 1.34, "Parsing \"0001.34\""); Assert.AreEqual((double)SmartDouble.Parse("00001.34"), 1.34, "Parsing \"00001.34\""); Assert.AreEqual((double)SmartDouble.Parse("000001.34"), 1.34, "Parsing \"000001.34\""); Assert.AreEqual((double)SmartDouble.Parse("0000001.34"), 1.34, "Parsing \"0000001.34\""); Assert.AreEqual((double)SmartDouble.Parse("0123.34"), 123.34, "Parsing \"0123.34\""); Assert.AreEqual((double)SmartDouble.Parse("00123.34"), 123.34, "Parsing \"00123.34\""); Assert.AreEqual((double)SmartDouble.Parse("000123.34"), 123.34, "Parsing \"000123.34\""); Assert.AreEqual((double)SmartDouble.Parse("0000123.34"), 123.34, "Parsing \"0000123.34\""); Assert.AreEqual((double)SmartDouble.Parse("00000123.34"), 123.34, "Parsing \"00000123.34\""); Assert.AreEqual((double)SmartDouble.Parse("000000123.34"), 123.34, "Parsing \"000000123.34\""); // Negative Leading zeros Assert.AreEqual((double)SmartDouble.Parse("-0.34"), -0.34, "Parsing \"-0.34\""); // double32.Parse("-0") throws here Assert.AreEqual((double)SmartDouble.Parse("-01.34"), -1.34, "Parsing \"-01.34\""); Assert.AreEqual((double)SmartDouble.Parse("-001.34"), -1.34, "Parsing \"-001.34\""); Assert.AreEqual((double)SmartDouble.Parse("-0001.34"), -1.34, "Parsing \"-0001.34\""); Assert.AreEqual((double)SmartDouble.Parse("-00001.34"), -1.34, "Parsing \"-00001.34\""); Assert.AreEqual((double)SmartDouble.Parse("-000001.34"), -1.34, "Parsing \"-000001.34\""); Assert.AreEqual((double)SmartDouble.Parse("-0000001.34"), -1.34, "Parsing \"-0000001.34\""); Assert.AreEqual((double)SmartDouble.Parse("-0123.34"), -123.34, "Parsing \"-0123.34\""); Assert.AreEqual((double)SmartDouble.Parse("-00123.34"), -123.34, "Parsing \"-00123.34\""); Assert.AreEqual((double)SmartDouble.Parse("-000123.34"), -123.34, "Parsing \"-000123.34\""); Assert.AreEqual((double)SmartDouble.Parse("-0000123.34"), -123.34, "Parsing \"-0000123.34\""); Assert.AreEqual((double)SmartDouble.Parse("-00000123.34"), -123.34, "Parsing \"-00000123.34\""); Assert.AreEqual((double)SmartDouble.Parse("-000000123.34"), -123.34, "Parsing \"-000000123.34\""); // Positively Sihned Leading zeros Assert.AreEqual((double)SmartDouble.Parse("+0.34"), 0.34, "Parsing \"+0.34\""); Assert.AreEqual((double)SmartDouble.Parse("+01.34"), 1.34, "Parsing \"+01.34\""); Assert.AreEqual((double)SmartDouble.Parse("+001.34"), 1.34, "Parsing \"+001.34\""); Assert.AreEqual((double)SmartDouble.Parse("+0001.34"), 1.34, "Parsing \"+0001.34\""); Assert.AreEqual((double)SmartDouble.Parse("+00001.34"), 1.34, "Parsing \"+00001.34\""); Assert.AreEqual((double)SmartDouble.Parse("+000001.34"), 1.34, "Parsing \"+000001.34\""); Assert.AreEqual((double)SmartDouble.Parse("+0000001.34"), 1.34, "Parsing \"+0000001.34\""); Assert.AreEqual((double)SmartDouble.Parse("+0123.34"), 123.34, "Parsing \"+0123.34\""); Assert.AreEqual((double)SmartDouble.Parse("+00123.34"), 123.34, "Parsing \"+00123.34\""); Assert.AreEqual((double)SmartDouble.Parse("+000123.34"), 123.34, "Parsing \"+000123.34\""); Assert.AreEqual((double)SmartDouble.Parse("+0000123.34"), 123.34, "Parsing \"+0000123.34\""); Assert.AreEqual((double)SmartDouble.Parse("+00000123.34"), 123.34, "Parsing \"+00000123.34\""); Assert.AreEqual((double)SmartDouble.Parse("+000000123.34"), 123.34, "Parsing \"+000000123.34\""); // Leading & Finaling Spaces Assert.AreEqual((double)SmartDouble.Parse(" 0.34 "), 0.34, "Parsing \" 0.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" 01.34 "), 1.34, "Parsing \" 01.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" 0123.34 "), 123.34, "Parsing \" 0123.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" -0.34 "), -0.34, "Parsing \" -0.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" -01.34 "), -1.34, "Parsing \" -01.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" -0123.34 "), -123.34, "Parsing \" -0123.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" +0.34 "), 0.34, "Parsing \" +0.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" +01.34 "), 1.34, "Parsing \" +01.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" +0123.34 "), 123.34, "Parsing \" +0123.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" 0.34 "), 0.34, "Parsing \" 0 \""); Assert.AreEqual((double)SmartDouble.Parse(" 01.34 "), 1.34, "Parsing \" 01 \""); Assert.AreEqual((double)SmartDouble.Parse(" 0123.34 "), 123.34, "Parsing \" 0123 \""); Assert.AreEqual((double)SmartDouble.Parse(" -0.34 "), -0.34, "Parsing \" -0.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" -01.34 "), -1.34, "Parsing \" -01.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" -0123.34 "), -123.34, "Parsing \" -0123.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" +0.34 "), 0.34, "Parsing \" +0.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" +01.34 "), 1.34, "Parsing \" +01.34 \""); Assert.AreEqual((double)SmartDouble.Parse(" +0123.34 "), 123.34, "Parsing \" +0123.34 \""); // Leading Spaces Assert.AreEqual((double)SmartDouble.Parse(" 0.34"), 0.34, "Parsing \" 0.34\""); Assert.AreEqual((double)SmartDouble.Parse(" 01.34"), 1.34, "Parsing \" 01.34\""); Assert.AreEqual((double)SmartDouble.Parse(" 0123.34"), 123.34, "Parsing \" 0123.34\""); Assert.AreEqual((double)SmartDouble.Parse(" -0.34"), -0.34, "Parsing \" -0.34\""); Assert.AreEqual((double)SmartDouble.Parse(" -01.34"), -1.34, "Parsing \" -01.34\""); Assert.AreEqual((double)SmartDouble.Parse(" -0123.34"), -123.34, "Parsing \" -0123.34\""); Assert.AreEqual((double)SmartDouble.Parse(" +0.34"), 0.34, "Parsing \" +0.34\""); Assert.AreEqual((double)SmartDouble.Parse(" +01.34"), 1.34, "Parsing \" +01.34\""); Assert.AreEqual((double)SmartDouble.Parse(" +0123.34"), 123.34, "Parsing \" +0123.34\""); Assert.AreEqual((double)SmartDouble.Parse(" 0.34"), 0.34, "Parsing \" 0.34\""); Assert.AreEqual((double)SmartDouble.Parse(" 01.34"), 1.34, "Parsing \" 01.34\""); Assert.AreEqual((double)SmartDouble.Parse(" 0123.34"), 123.34, "Parsing \" 0123.34\""); Assert.AreEqual((double)SmartDouble.Parse(" -0.34"), -0.34, "Parsing \" -0.34\""); Assert.AreEqual((double)SmartDouble.Parse(" -01.34"), -1.34, "Parsing \" -01.34\""); Assert.AreEqual((double)SmartDouble.Parse(" -0123.34"), -123.34, "Parsing \" -0123.34\""); Assert.AreEqual((double)SmartDouble.Parse(" +0.34"), 0.34, "Parsing \" +0.34\""); Assert.AreEqual((double)SmartDouble.Parse(" +01.34"), 1.34, "Parsing \" +01.34\""); Assert.AreEqual((double)SmartDouble.Parse(" +0123.34"), 123.34, "Parsing \" +0123.34\""); // Finaling Spaces Assert.AreEqual((double)SmartDouble.Parse("0.34 "), 0.34, "Parsing \"0.34 \""); Assert.AreEqual((double)SmartDouble.Parse("01.34 "), 1.34, "Parsing \"01.34 \""); Assert.AreEqual((double)SmartDouble.Parse("0123.34 "), 123.34, "Parsing \"0123.34 \""); Assert.AreEqual((double)SmartDouble.Parse("-0.34 "), -0.34, "Parsing \"-0.34 \""); Assert.AreEqual((double)SmartDouble.Parse("-01.34 "), -1.34, "Parsing \"-01.34 \""); Assert.AreEqual((double)SmartDouble.Parse("-0123.34 "), -123.34, "Parsing \"-0123.34 \""); Assert.AreEqual((double)SmartDouble.Parse("+0.34 "), 0.34, "Parsing \"+0.34 \""); Assert.AreEqual((double)SmartDouble.Parse("+01.34 "), 1.34, "Parsing \"+01.34 \""); Assert.AreEqual((double)SmartDouble.Parse("+0123.34 "), 123.34, "Parsing \"+0123.34 \""); Assert.AreEqual((double)SmartDouble.Parse("0.34 "), 0.34, "Parsing \"0.34 \""); Assert.AreEqual((double)SmartDouble.Parse("01.34 "), 1.34, "Parsing \"01.34 \""); Assert.AreEqual((double)SmartDouble.Parse("0123.34 "), 123.34, "Parsing \"0123.34 \""); Assert.AreEqual((double)SmartDouble.Parse("-0.34 "), -0.34, "Parsing \"-0.34 \""); Assert.AreEqual((double)SmartDouble.Parse("-01.34 "), -1.34, "Parsing \"-01.34 \""); Assert.AreEqual((double)SmartDouble.Parse("-0123.34 "), -123.34, "Parsing \"-0123.34 \""); Assert.AreEqual((double)SmartDouble.Parse("+0.34 "), 0.34, "Parsing \"+0.34 \""); Assert.AreEqual((double)SmartDouble.Parse("+01.34 "), 1.34, "Parsing \"+01.34 \""); Assert.AreEqual((double)SmartDouble.Parse("+0123.34 "), 123.34, "Parsing \"+0123.34 \""); Assert.AreEqual((double)SmartDouble.Parse("0."), 0, "Parsing \"0.\""); Assert.AreEqual((double)SmartDouble.Parse("0. "), 0, "Parsing \"0. \""); Assert.AreEqual((double)SmartDouble.Parse(" 0. "), 0, "Parsing \" 0. \""); Assert.AreEqual((double)SmartDouble.Parse(" 0."), 0, "Parsing \" 0.\""); Assert.AreEqual((double)SmartDouble.Parse("-0."), 0, "Parsing \"-0.\""); Assert.AreEqual((double)SmartDouble.Parse("-0. "), 0, "Parsing \"-0. \""); Assert.AreEqual((double)SmartDouble.Parse(" -0. "), 0, "Parsing \" -0. \""); Assert.AreEqual((double)SmartDouble.Parse(" -0. "), 0, "Parsing \" -0. \""); Assert.AreEqual((double)SmartDouble.Parse("+0."), 0, "Parsing \"+0.\""); Assert.AreEqual((double)SmartDouble.Parse("+0. "), 0, "Parsing \"+0. \""); Assert.AreEqual((double)SmartDouble.Parse(" +0. "), 0, "Parsing \" +0. \""); Assert.AreEqual((double)SmartDouble.Parse(" +0."), 0, "Parsing \" +0.\""); #endregion } [TestMethod] public void SmartDouble_ToString_Test() { #region Similar to SmartInt Assert.AreEqual("1", (new SmartDouble(1)).ToString(), "ToString \"1\""); Assert.AreEqual("123", (new SmartDouble(123)).ToString(), "ToString \"123\""); Assert.AreEqual("123456789", (new SmartDouble(123456789)).ToString(), "ToString \"123456789\""); Assert.AreEqual("-1", (new SmartDouble(-1)).ToString(), "ToString \"-1\""); Assert.AreEqual("-123", (new SmartDouble(-123)).ToString(), "ToString \"-123\""); Assert.AreEqual("-123456789", (new SmartDouble(-123456789)).ToString(), "ToString \"-123456789\""); #endregion #region -1 .. 1 // -0.x Assert.AreEqual("-0.111111111111", (new SmartDouble(-0.111111111111)).ToString(), "ToString \"-0.111111111111\""); Assert.AreEqual("-0.99", (new SmartDouble(-0.99)).ToString(), "ToString \"-0.99\""); Assert.AreEqual("-0.11", (new SmartDouble(-0.11)).ToString(), "ToString \"-0.11\""); Assert.AreEqual("-0.9", (new SmartDouble(-0.9)).ToString(), "ToString \"-0.9\""); Assert.AreEqual("-0.123456789123", (new SmartDouble(-0.123456789123)).ToString(), "ToString \"-0.123456789123\""); Assert.AreEqual("-0.12345678912", (new SmartDouble(-0.12345678912)).ToString(), "ToString \"-0.12345678912\""); Assert.AreEqual("-0.1234567891", (new SmartDouble(-0.1234567891)).ToString(), "ToString \"-0.1234567891\""); Assert.AreEqual("-0.123456789", (new SmartDouble(-0.123456789)).ToString(), "ToString \"-0.123456789\""); Assert.AreEqual("-0.12345678", (new SmartDouble(-0.12345678)).ToString(), "ToString \"-0.12345678\""); Assert.AreEqual("-0.1234567", (new SmartDouble(-0.1234567)).ToString(), "ToString \"-0.1234567\""); Assert.AreEqual("-0.123456", (new SmartDouble(-0.123456)).ToString(), "ToString \"-0.123456\""); Assert.AreEqual("-0.12345", (new SmartDouble(-0.12345)).ToString(), "ToString \"-0.12345\""); Assert.AreEqual("-0.1234", (new SmartDouble(-0.1234)).ToString(), "ToString \"-0.1234\""); Assert.AreEqual("-0.123", (new SmartDouble(-0.123)).ToString(), "ToString \"-0.123\""); Assert.AreEqual("-0.12", (new SmartDouble(-0.12)).ToString(), "ToString \"-0.12\""); Assert.AreEqual("-0.1", (new SmartDouble(-0.1)).ToString(), "ToString \"-0.1\""); Assert.AreEqual("0", (new SmartDouble(-0.0)).ToString(), "ToString \"-0.0\""); Assert.AreEqual("-0.1", (new SmartDouble(-0.1)).ToString(), "ToString \"-0.1\""); Assert.AreEqual("-0.01", (new SmartDouble(-0.01)).ToString(), "ToString \"-0.01\""); Assert.AreEqual("-0.001", (new SmartDouble(-0.001)).ToString(), "ToString \"-0.001\""); Assert.AreEqual("-0.0001", (new SmartDouble(-0.0001)).ToString(), "ToString \"-0.0001\""); Assert.AreEqual("-0.00001", (new SmartDouble(-0.00001)).ToString(), "ToString \"-0.00001\""); Assert.AreEqual("-0.000001", (new SmartDouble(-0.000001)).ToString(), "ToString \"-0.000001\""); Assert.AreEqual("-0.0000001", (new SmartDouble(-0.0000001)).ToString(), "ToString \"-0.0000001\""); Assert.AreEqual("-0.00000001", (new SmartDouble(-0.00000001)).ToString(), "ToString \"-0.00000001\""); Assert.AreEqual("-0.000000001", (new SmartDouble(-0.000000001)).ToString(), "ToString \"-0.000000001\""); Assert.AreEqual("-0.0000000001", (new SmartDouble(-0.0000000001)).ToString(), "ToString \"-0.0000000001\""); Assert.AreEqual("-0.00000000001", (new SmartDouble(-0.00000000001)).ToString(), "ToString \"-0.00000000001\""); Assert.AreEqual("-0.000000000001", (new SmartDouble(-0.000000000001)).ToString(), "ToString \"-0.000000000001\""); // 0.x Assert.AreEqual("0.111111111111", (new SmartDouble(0.111111111111)).ToString(), "ToString \"0.111111111111\""); Assert.AreEqual("0.99", (new SmartDouble(0.99)).ToString(), "ToString \"0.99\""); Assert.AreEqual("0.11", (new SmartDouble(0.11)).ToString(), "ToString \"0.11\""); Assert.AreEqual("0.9", (new SmartDouble(0.9)).ToString(), "ToString \"0.9\""); Assert.AreEqual("0.1", (new SmartDouble(0.1)).ToString(), "ToString \"0.1\""); Assert.AreEqual("0.123456789123", (new SmartDouble(0.123456789123)).ToString(), "ToString \"0.123456789123\""); Assert.AreEqual("0.12345678912", (new SmartDouble(0.12345678912)).ToString(), "ToString \"0.12345678912\""); Assert.AreEqual("0.1234567891", (new SmartDouble(0.1234567891)).ToString(), "ToString \"0.1234567891\""); Assert.AreEqual("0.123456789", (new SmartDouble(0.123456789)).ToString(), "ToString \"0.123456789\""); Assert.AreEqual("0.12345678", (new SmartDouble(0.12345678)).ToString(), "ToString \"0.12345678\""); Assert.AreEqual("0.1234567", (new SmartDouble(0.1234567)).ToString(), "ToString \"0.1234567\""); Assert.AreEqual("0.123456", (new SmartDouble(0.123456)).ToString(), "ToString \"0.123456\""); Assert.AreEqual("0.12345", (new SmartDouble(0.12345)).ToString(), "ToString \"0.12345\""); Assert.AreEqual("0.1234", (new SmartDouble(0.1234)).ToString(), "ToString \"0.1234\""); Assert.AreEqual("0.123", (new SmartDouble(0.123)).ToString(), "ToString \"0.123\""); Assert.AreEqual("0.12", (new SmartDouble(0.12)).ToString(), "ToString \"0.12\""); Assert.AreEqual("0.1", (new SmartDouble(0.1)).ToString(), "ToString \"0.1\""); Assert.AreEqual("0", (new SmartDouble(0.0)).ToString(), "ToString \"0.0\""); Assert.AreEqual("0.1", (new SmartDouble(0.1)).ToString(), "ToString \"0.1\""); Assert.AreEqual("0.01", (new SmartDouble(0.01)).ToString(), "ToString \"0.01\""); Assert.AreEqual("0.001", (new SmartDouble(0.001)).ToString(), "ToString \"0.001\""); Assert.AreEqual("0.0001", (new SmartDouble(0.0001)).ToString(), "ToString \"0.0001\""); Assert.AreEqual("0.00001", (new SmartDouble(0.00001)).ToString(), "ToString \"0.00001\""); Assert.AreEqual("0.000001", (new SmartDouble(0.000001)).ToString(), "ToString \"0.000001\""); Assert.AreEqual("0.0000001", (new SmartDouble(0.0000001)).ToString(), "ToString \"0.0000001\""); Assert.AreEqual("0.00000001", (new SmartDouble(0.00000001)).ToString(), "ToString \"0.00000001\""); Assert.AreEqual("0.000000001", (new SmartDouble(0.000000001)).ToString(), "ToString \"0.000000001\""); Assert.AreEqual("0.0000000001", (new SmartDouble(0.0000000001)).ToString(), "ToString \"0.0000000001\""); Assert.AreEqual("0.00000000001", (new SmartDouble(0.00000000001)).ToString(), "ToString \"0.00000000001\""); Assert.AreEqual("0.000000000001", (new SmartDouble(0.000000000001)).ToString(), "ToString \"0.000000000001\""); // -.x Assert.AreEqual("-0.111111111111", (new SmartDouble(-.111111111111)).ToString(), "ToString \"-.111111111111\""); Assert.AreEqual("-0.99", (new SmartDouble(-.99)).ToString(), "ToString \"-.99\""); Assert.AreEqual("-0.11", (new SmartDouble(-.11)).ToString(), "ToString \"-.11\""); Assert.AreEqual("-0.9", (new SmartDouble(-.9)).ToString(), "ToString \"-.9\""); Assert.AreEqual("-0.1", (new SmartDouble(-.1)).ToString(), "ToString \"-.1\""); Assert.AreEqual("-0.123456789123", (new SmartDouble(-.123456789123)).ToString(), "ToString \"-.123456789123\""); Assert.AreEqual("-0.12345678912", (new SmartDouble(-.12345678912)).ToString(), "ToString \"-.12345678912\""); Assert.AreEqual("-0.1234567891", (new SmartDouble(-.1234567891)).ToString(), "ToString \"-.1234567891\""); Assert.AreEqual("-0.123456789", (new SmartDouble(-.123456789)).ToString(), "ToString \"-.123456789\""); Assert.AreEqual("-0.12345678", (new SmartDouble(-.12345678)).ToString(), "ToString \"-.12345678\""); Assert.AreEqual("-0.1234567", (new SmartDouble(-.1234567)).ToString(), "ToString \"-.1234567\""); Assert.AreEqual("-0.123456", (new SmartDouble(-.123456)).ToString(), "ToString \"-.123456\""); Assert.AreEqual("-0.12345", (new SmartDouble(-.12345)).ToString(), "ToString \"-.12345\""); Assert.AreEqual("-0.1234", (new SmartDouble(-.1234)).ToString(), "ToString \"-.1234\""); Assert.AreEqual("-0.123", (new SmartDouble(-.123)).ToString(), "ToString \"-.123\""); Assert.AreEqual("-0.12", (new SmartDouble(-.12)).ToString(), "ToString \"-.12\""); Assert.AreEqual("-0.1", (new SmartDouble(-.1)).ToString(), "ToString \"-.1\""); Assert.AreEqual("0", (new SmartDouble(-.0)).ToString(), "ToString \"-.0\""); Assert.AreEqual("-0.1", (new SmartDouble(-.1)).ToString(), "ToString \"-.1\""); Assert.AreEqual("-0.01", (new SmartDouble(-.01)).ToString(), "ToString \"-.01\""); Assert.AreEqual("-0.001", (new SmartDouble(-.001)).ToString(), "ToString \"-.001\""); Assert.AreEqual("-0.0001", (new SmartDouble(-.0001)).ToString(), "ToString \"-.0001\""); Assert.AreEqual("-0.00001", (new SmartDouble(-.00001)).ToString(), "ToString \"-.00001\""); Assert.AreEqual("-0.000001", (new SmartDouble(-.000001)).ToString(), "ToString \"-.000001\""); Assert.AreEqual("-0.0000001", (new SmartDouble(-.0000001)).ToString(), "ToString \"-.0000001\""); Assert.AreEqual("-0.00000001", (new SmartDouble(-.00000001)).ToString(), "ToString \"-.00000001\""); Assert.AreEqual("-0.000000001", (new SmartDouble(-.000000001)).ToString(), "ToString \"-.000000001\""); Assert.AreEqual("-0.0000000001", (new SmartDouble(-.0000000001)).ToString(), "ToString \"-.0000000001\""); Assert.AreEqual("-0.00000000001", (new SmartDouble(-.00000000001)).ToString(), "ToString \"-.00000000001\""); Assert.AreEqual("-0.000000000001", (new SmartDouble(-.000000000001)).ToString(), "ToString \"-.000000000001\""); // .x Assert.AreEqual("0.111111111111", (new SmartDouble(.111111111111)).ToString(), "ToString \"-0.111111111111\""); Assert.AreEqual("0.99", (new SmartDouble(.99)).ToString(), "ToString \".99\""); Assert.AreEqual("0.11", (new SmartDouble(.11)).ToString(), "ToString \".11\""); Assert.AreEqual("0.9", (new SmartDouble(.9)).ToString(), "ToString \".9\""); Assert.AreEqual("0.1", (new SmartDouble(.1)).ToString(), "ToString \".1\""); Assert.AreEqual("0.123456789123", (new SmartDouble(.123456789123)).ToString(), "ToString \".123456789123\""); Assert.AreEqual("0.12345678912", (new SmartDouble(.12345678912)).ToString(), "ToString \".12345678912\""); Assert.AreEqual("0.1234567891", (new SmartDouble(.1234567891)).ToString(), "ToString \".1234567891\""); Assert.AreEqual("0.123456789", (new SmartDouble(.123456789)).ToString(), "ToString \".123456789\""); Assert.AreEqual("0.12345678", (new SmartDouble(.12345678)).ToString(), "ToString \".12345678\""); Assert.AreEqual("0.1234567", (new SmartDouble(.1234567)).ToString(), "ToString \".1234567\""); Assert.AreEqual("0.123456", (new SmartDouble(.123456)).ToString(), "ToString \".123456\""); Assert.AreEqual("0.12345", (new SmartDouble(.12345)).ToString(), "ToString \".12345\""); Assert.AreEqual("0.1234", (new SmartDouble(.1234)).ToString(), "ToString \".1234\""); Assert.AreEqual("0.123", (new SmartDouble(.123)).ToString(), "ToString \".123\""); Assert.AreEqual("0.12", (new SmartDouble(.12)).ToString(), "ToString \".12\""); Assert.AreEqual("0.1", (new SmartDouble(.1)).ToString(), "ToString \".1\""); Assert.AreEqual("0", (new SmartDouble(.0)).ToString(), "ToString \".0\""); Assert.AreEqual("0.1", (new SmartDouble(.1)).ToString(), "ToString \".1\""); Assert.AreEqual("0.01", (new SmartDouble(.01)).ToString(), "ToString \".01\""); Assert.AreEqual("0.001", (new SmartDouble(.001)).ToString(), "ToString \".001\""); Assert.AreEqual("0.0001", (new SmartDouble(.0001)).ToString(), "ToString \".0001\""); Assert.AreEqual("0.00001", (new SmartDouble(.00001)).ToString(), "ToString \".00001\""); Assert.AreEqual("0.000001", (new SmartDouble(.000001)).ToString(), "ToString \".000001\""); Assert.AreEqual("0.0000001", (new SmartDouble(.0000001)).ToString(), "ToString \".0000001\""); Assert.AreEqual("0.00000001", (new SmartDouble(.00000001)).ToString(), "ToString \".00000001\""); Assert.AreEqual("0.000000001", (new SmartDouble(.000000001)).ToString(), "ToString \".000000001\""); Assert.AreEqual("0.0000000001", (new SmartDouble(.0000000001)).ToString(), "ToString \".0000000001\""); Assert.AreEqual("0.00000000001", (new SmartDouble(.00000000001)).ToString(), "ToString \".00000000001\""); Assert.AreEqual("0.000000000001", (new SmartDouble(.000000000001)).ToString(), "ToString \".000000000001\""); #endregion } [TestMethod] public void SmartDouble_ToStringN_Test() { Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(15), "49.6716517210007", "SmartDouble(49.6716517210007).ToString(15)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(14), "49.6716517210007", "SmartDouble(49.6716517210007).ToString(14)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(13), "49.6716517210007", "SmartDouble(49.6716517210007).ToString(13)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(12), "49.671651721001", "SmartDouble(49.6716517210007).ToString(12)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(11), "49.671651721", "SmartDouble(49.6716517210007).ToString(11)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(10), "49.671651721", "SmartDouble(49.6716517210007).ToString(10)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(9), "49.671651721", "SmartDouble(49.6716517210007).ToString(9)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(8), "49.67165172", "SmartDouble(49.6716517210007).ToString(8)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(7), "49.6716517", "SmartDouble(49.6716517210007).ToString(7)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(6), "49.671652", "SmartDouble(49.6716517210007).ToString(6)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(5), "49.67165", "SmartDouble(49.6716517210007).ToString(5)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(4), "49.6717", "SmartDouble(49.6716517210007).ToString(4)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(3), "49.672", "SmartDouble(49.6716517210007).ToString(3)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(2), "49.67", "SmartDouble(49.6716517210007).ToString(2)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(1), "49.7", "SmartDouble(49.6716517210007).ToString(1)"); Assert.AreEqual((new SmartDouble(49.6716517210007)).ToString(0), "50", "SmartDouble(49.6716517210007).ToString(0)"); Assert.AreEqual("99999.98324", (new SmartDouble(99999.98324)).ToString(8), "SmartDouble.ToString(8) 99999.98324"); Assert.AreEqual("2999.99971", (new SmartDouble(2999.99971)).ToString(8), "SmartDouble.ToString(8) 2999.99971"); } [TestMethod] public void SmartDouble_Parse_ToString_BruteForce_Test() { int test_count = 10000000; int parta_max = 1000000; int partb_max = 1000000; Random R = new Random(); for (int i = 0; i < test_count; i++) { string s_parta = R.Next(parta_max).ToString(); string s_partb = R.Next(partb_max).ToString(); // if (s_partb == "0") // continue; while ((s_partb.Length > 0) && (s_partb[s_partb.Length - 1] == '0')) s_partb = s_partb.Substring(0, s_partb.Length - 1); string s_sd1 = s_parta; if (!string.IsNullOrEmpty(s_partb)) s_sd1 += ("." + s_partb); //if (s_sd1.Length > 12) // s_sd1 = s_sd1.Substring(0, 12); SmartDouble sd = SmartDouble.Parse(s_sd1); string s_sd2 = sd.ToString(8); Double d = Double.Parse(s_sd1); string s_d2 = d.ToString(); Assert.AreEqual(s_sd2, s_d2, "Compare2Double " + s_sd1); } } [TestMethod] public void SmartDouble_Parse_ToString_BruteForce_Heavy_Test() { int test_count = 10000000; int parta_max = 1000000000; int partb_max = 1000000000; Random R = new Random(); for (int i = 0; i < test_count; i++) { string s_parta = R.Next(parta_max).ToString(); string s_partb = R.Next(partb_max).ToString(); while ((s_partb.Length > 0) && (s_partb[s_partb.Length - 1] == '0')) s_partb = s_partb.Substring(0, s_partb.Length - 1); string s_sd1 = s_parta; if (!string.IsNullOrEmpty(s_partb)) s_sd1 += ("." + s_partb); SmartDouble sd = SmartDouble.Parse(s_sd1); string s_sd2 = sd.ToString(); Double d = Double.Parse(s_sd1); string s_d2 = d.ToString(); // Cross d = Double.Parse(s_sd2); sd = SmartDouble.Parse(s_d2); Double error = Math.Abs((d - sd) / d); Assert.IsTrue(error < 1E-14, "Compare2DoubleHeavy " + s_sd1); } } } }
using Hayalpc.Fatura.Common.Dtos; using Hayalpc.Fatura.CoreApi.Services.Interfaces; using Hayalpc.Fatura.Data; using Hayalpc.Fatura.Data.Models; using Hayalpc.Library.Common.Extensions; using Hayalpc.Library.Common.Results; using Hayalpc.Library.Log; using Hayalpc.Library.Repository.Interfaces; using Microsoft.Extensions.Caching.Memory; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Hayalpc.Fatura.CoreApi.Services { public class InvoicePaymentService : IInvoicePaymentService { private readonly IRepository<InvoicePayment> repository; private readonly IHpUnitOfWork<HpDbContext> unitOfWork; private readonly IMemoryCache cache; private readonly IHpLogger logger; public InvoicePaymentService(IRepository<InvoicePayment> repository, IHpUnitOfWork<HpDbContext> unitOfWork, IMemoryCache cache, IHpLogger logger) { this.repository = repository; this.unitOfWork = unitOfWork; this.logger = logger; this.cache = cache; } public IDataResult<InvoicePayment> Add(InvoicePayment invoice) { try { if (invoice.Token == null) invoice.Token = Guid.NewGuid(); invoice.CreateTime = DateTime.Now; invoice.UpdateTime = DateTime.Now; invoice.CreateUserId = -1; invoice.UpdateUserId = -1; repository.Insert(invoice); unitOfWork.SaveChanges(); return new SuccessDataResult<InvoicePayment>(invoice); } catch (Exception exp) { logger.Error(exp); return new ErrorDataResult<InvoicePayment>(500, exp.Message); } } public IDataResult<InvoicePayment> Update(InvoicePayment invoice) { try { invoice.UpdateTime = DateTime.Now; repository.Update(invoice); unitOfWork.SaveChanges(); return new SuccessDataResult<InvoicePayment>(invoice); } catch (Exception exp) { logger.Error(exp); return new ErrorDataResult<InvoicePayment>(500, exp.Message); } } public IDataResult<InvoicePayment> GetByToken(Guid token) { try { var data = repository.GetQuery(x=>x.Token == token).FirstOrDefault(); if (data != null) return new SuccessDataResult<InvoicePayment>(data); else return new ErrorDataResult<InvoicePayment>(404, "NotFound"); } catch (Exception exp) { logger.Error(exp); return new ErrorDataResult<InvoicePayment>(500, exp.Message); } } public IDataResult<ReceiptDto> Receipt(long id, Guid token) { try { var data = repository.GetQuery(x => x.Token == token && x.Id == id && x.Status == Common.Enums.InvoicePaymentStatus.Success).FirstOrDefault(); if (data != null) { var receipt = new ReceiptDto { InvoicePayment = data.Convert<InvoicePaymentDto>(), Institution = repository.GetQuery<Institution>(x => x.Id == data.InstitutionId).FirstOrDefault()?.Convert<InstitutionDto>(), Category = repository.GetQuery<Category>(x => x.Id == data.CategoryId).FirstOrDefault()?.Convert<CategoryDto>(), Invoices = repository.GetQuery<Invoice>(x => x.PaymentId == data.Id).ToList()?.Convert<List<InvoiceDto>>(), }; return new SuccessDataResult<ReceiptDto>(receipt); } else return new ErrorDataResult<ReceiptDto>(404, "NotFound"); } catch (Exception exp) { logger.Error(exp); return new ErrorDataResult<ReceiptDto>(500, exp.Message); } } } }
namespace SquareRootNaturalLogSinusPerformance { using System; using System.Linq; using BasicArithmeticOperationsPerformance; public class CompareSquareRootNaturalLogSinus { public static void Main(string[] args) { double iterations = 1000000; Console.WriteLine("Iterations number: {0}", iterations); Console.WriteLine( "Square root (float), Elapsed time: {0} ms", PerformanceUtils.GetEllapsedTime(() => MathOperations.GetSquareRoot(iterations, 50f))); Console.WriteLine( "Square root (double), Elapsed time: {0} ms", PerformanceUtils.GetEllapsedTime(() => MathOperations.GetSquareRoot(iterations, 50d))); Console.WriteLine( "Square root (decimal), Elapsed time: {0} ms", PerformanceUtils.GetEllapsedTime(() => MathOperations.GetSquareRoot(iterations, 50m))); Console.WriteLine( "Natural logarithm (float), Elapsed time: {0} ms", PerformanceUtils.GetEllapsedTime(() => MathOperations.CalcNaturalLogarithm(iterations, 50f))); Console.WriteLine( "Natural logarithm (double), Elapsed time: {0} ms", PerformanceUtils.GetEllapsedTime(() => MathOperations.CalcNaturalLogarithm(iterations, 50d))); Console.WriteLine( "Natural logarithm (decimal), Elapsed time: {0} ms", PerformanceUtils.GetEllapsedTime(() => MathOperations.CalcNaturalLogarithm(iterations, 50m))); Console.WriteLine( "Sinus (float), Elapsed time: {0} ms", PerformanceUtils.GetEllapsedTime(() => MathOperations.GetSinus(iterations, 20f))); Console.WriteLine( "Sinus (double), Elapsed time: {0} ms", PerformanceUtils.GetEllapsedTime(() => MathOperations.GetSinus(iterations, 20d))); Console.WriteLine( "Sinus (decimal), Elapsed time: {0} ms", PerformanceUtils.GetEllapsedTime(() => MathOperations.GetSinus(iterations, 20m))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Exercise6 { /* 6. Write a method that returns the index of the first element in array * that is bigger than its neighbors, or -1, if there’s no such element. * Use the method from the previous exercise. */ class Program { static void Main(string[] args) { int i; int [] array = new int [10]; Console.WriteLine("Please enter numbers in array : "); for (i = 0; i < array.Length; i++) { array[i] = int.Parse(Console.ReadLine()); } for (i = 0; i < array.Length; i++) { if (Check_element(i, array)) { Console.WriteLine("First element in the array greater then its neighbors is "+ array[i]); break; } } if (i == 10) { Console.WriteLine("First element in the array greater then its neighbors is -1 "); } } static bool Check_element(int index, int[] array) { bool result = true; if (index > 0 && array[index] <= array[index - 1]) { result = false; } if (index < array.Length && array[index] <= array[index + 1]) { result = false; } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EjercicioInterfaces { public class Familiar:Auto { private int _cantidadAsientos; public Familiar(double precio,string patente,int cantidadAsientos):base(precio,patente) { this._cantidadAsientos = cantidadAsientos; } public override void MostrarPatente() { Console.WriteLine("Patente Familiar: " + this._patente); } public override void MostrarPrecio() { Console.WriteLine("Precio Familiar: "+this._precio); } } }
using App.Server.Models.Markup; using App.Server.Models.Settings; using Framework.Db; using Framework.Entity; using Framework.Entity.Filter; using Framework.Metadata; using Framework.Remote; using Framework.Remote.Mobile; using Framework.Utils; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace App.Server.Controllers { public partial class HomeController { [Authorize] public ActionResult CalculateExpressions( string entityUsageId, string currentEnt, string selectedEnts, string joins, string whereVals, string pkVals, string filters, string sorts, string parentPrimaryKeys, string parentEntityUsageId, string changedAttributeId, int startRecordIndex, int recordsAmount, string queryType, string openMode, IEnumerable<string> requiredTemplates, string[] dependentAttributesIds, string[] dependentMandatoryAttributesIds, string[] dependentStateIds ) { JsonResult json = new JsonResult(); json.JsonRequestBehavior = JsonRequestBehavior.AllowGet; //#if (!DEBUG) try { //#endif List<Dictionary<string, object>> selectedEntities; Dictionary<string, object> currentEntity; Dictionary<string, object> primaryKeysValues; Dictionary<string, object> whereValues; Dictionary<string, object> joinValues; List<CxFilterItem> filterItems; List<CxSortDescription> sortDescriptions; Dictionary<string, object> parentPks; List<string> validationErrors = new List<string>(); CxEntityUsageMetadata entityUsage = mHolder.EntityUsages[entityUsageId]; CxEntityUsageMetadata parentUsage = null; if (string.IsNullOrWhiteSpace(parentEntityUsageId) == false) parentUsage = mHolder.EntityUsages[parentEntityUsageId]; ParseQueryParams( out primaryKeysValues, out whereValues, out joinValues, out filterItems, out sortDescriptions, out parentPks, out currentEntity, out selectedEntities, pkVals, whereVals, joins, filters, sorts, parentPrimaryKeys, currentEnt, selectedEnts, entityUsage, parentUsage); CxEntityUsageMetadata meta = mHolder.EntityUsages[entityUsageId]; Dictionary<CxClientAttributeMetadata, object> entityValues = new Dictionary<CxClientAttributeMetadata, object>(); foreach (CxAttributeMetadata attribute in meta.Attributes) { CxClientAttributeMetadata clientAttributeMetadata = new CxClientAttributeMetadata(attribute, meta); entityValues.Add(clientAttributeMetadata, currentEntity[attribute.Id]); } Dictionary<string, CxClientRowSource> unfilteredRowSources = new Dictionary<string, CxClientRowSource>(); List<CxClientRowSource> filteredRowSources = new List<CxClientRowSource>(); CalculateExpressions( ref entityValues, meta, changedAttributeId, ref unfilteredRowSources, ref filteredRowSources); CxExpressionResult exprResult = new CxExpressionResult(); exprResult.Attributes = new List<CxClientAttributeMetadata>(); exprResult.Values = new Dictionary<string, object>(); CxEditController editController = new CxEditController(meta); Dictionary<string, object> calculatedValues = new Dictionary<string, object>(); foreach (KeyValuePair<CxClientAttributeMetadata, object> pair in entityValues) { calculatedValues.Add(pair.Key.Id, pair.Value); } CxBaseEntity entity = CxBaseEntity.CreateByValueProvider (meta, CxQueryParams.CreateValueProvider(calculatedValues)); foreach (CxAttributeMetadata attribute in meta.Attributes) { bool isVisible = editController.GetIsVisible(attribute, entity); bool isReadOnly = editController.GetIsReadOnly(attribute, entity); CxClientAttributeMetadata clientAttribute = new CxClientAttributeMetadata(attribute, meta) { Visible = isVisible, ReadOnly = isReadOnly }; exprResult.Attributes.Add(clientAttribute); object val = entity[attribute.Id]; if (val is DBNull) val = null; if (attribute.PrimaryKey || (currentEntity.ContainsKey(attribute.Id) && dependentAttributesIds.Contains(attribute.Id) )) { exprResult.Values[attribute.Id] = val; } } exprResult.FilteredRowSources = filteredRowSources; exprResult.UnfilteredRowSources = unfilteredRowSources; var result = new { Templates = GetTemplates(requiredTemplates), ExprResult = exprResult, EntityUsageId = entityUsageId, ValidationErrors = validationErrors }; json.Data = result; return json; } catch (Exception ex) { var result = new { Error = ex.Message }; json.Data = result; return json; } } private void CalculateExpressions( ref Dictionary<CxClientAttributeMetadata, object> entityValues, CxEntityUsageMetadata meta, string changedAttributeId, ref Dictionary<string, CxClientRowSource> unfilteredRowSources, ref List<CxClientRowSource> filteredRowSources) { Dictionary<string, object> values = new Dictionary<string, object>(); foreach (KeyValuePair<CxClientAttributeMetadata, object> pair in entityValues) { values.Add(pair.Key.Id, pair.Value); } CxBaseEntity entity = CxBaseEntity.CreateByValueProvider (meta, CxQueryParams.CreateValueProvider(values)); CxExpressionResult exprResult = new CxExpressionResult(); exprResult.ActualEntity = entity; CxEditController editController = new CxEditController(meta); editController.ProcessDependentFields( exprResult, meta.GetAttribute(changedAttributeId), values[changedAttributeId]); Dictionary<CxClientAttributeMetadata, object> changedAndDepend = new Dictionary<CxClientAttributeMetadata, object>(); Dictionary<CxClientAttributeMetadata, object> newValues = new Dictionary<CxClientAttributeMetadata, object>(); foreach (CxAttributeMetadata attrMetadata in meta.Attributes) { bool isVisible = editController.GetIsVisible(attrMetadata, exprResult.ActualEntity); bool isReadOnly = editController.GetIsReadOnly(attrMetadata, exprResult.ActualEntity); CxClientAttributeMetadata attrMeta = new CxClientAttributeMetadata(attrMetadata, meta) { Visible = isVisible, ReadOnly = isReadOnly }; if (!Equals(exprResult.ActualEntity[attrMetadata.Id], values[attrMetadata.Id]) && HasDependencies(attrMeta)) { changedAndDepend.Add(attrMeta, exprResult.ActualEntity[attrMetadata.Id]); } newValues.Add(attrMeta, exprResult.ActualEntity[attrMetadata.Id]); } entityValues = newValues; foreach (KeyValuePair<string, CxClientRowSource> pair in exprResult.UnfilteredRowSources) { if (unfilteredRowSources.ContainsKey(pair.Key)) unfilteredRowSources[pair.Key] = pair.Value; else unfilteredRowSources.Add(pair.Key, pair.Value); } foreach (KeyValuePair<string, CxClientRowSource> pair in exprResult.UnfilteredRowSources) { if (unfilteredRowSources.ContainsKey(pair.Key)) unfilteredRowSources[pair.Key] = pair.Value; else unfilteredRowSources.Add(pair.Key, pair.Value); } foreach (CxClientRowSource rs in exprResult.FilteredRowSources) { CxClientRowSource cfr = filteredRowSources.FirstOrDefault(r => r.RowSourceId == rs.RowSourceId); filteredRowSources.Add(rs); } if (changedAndDepend.Count > 0) { foreach (KeyValuePair<CxClientAttributeMetadata, object> depend in changedAndDepend) { CalculateExpressions( ref entityValues, meta, depend.Key.Id, ref unfilteredRowSources, ref filteredRowSources); } } } private bool HasDependencies(CxClientAttributeMetadata attrMetadata) { if (attrMetadata.DependentAttributesIds.Count > 0 || attrMetadata.DependentStateIds.Count > 0 || attrMetadata.DependentMandatoryAttributesIds.Count > 0) { return true; } return false; } } }
using System; using System.Collections.Generic; using UnityEngine; namespace UnityExtensions.AI.Systems.MAS.Core { [Serializable] public class Scheduler { #region Attributes //private Agent m_owner; private readonly List<Behaviour> m_enabledBehaviours = new List<Behaviour>(); private readonly List<Behaviour> m_disabledBehaviours = new List<Behaviour>(); #endregion Attributes #region Methods #region Accessors and Mutators //_____________________________________________________________________ ACCESSORS AND MUTATORS _____________________________________________________________________ public List<Behaviour> behaviours { get { var list = new List<Behaviour>(); list.AddRange(m_enabledBehaviours); list.AddRange(m_disabledBehaviours); return list; } set { m_enabledBehaviours.Clear(); m_disabledBehaviours.Clear(); foreach (var behaviour in value) { if (behaviour.enabled) { m_enabledBehaviours.Add(behaviour); } else { m_disabledBehaviours.Add(behaviour); } } } } #endregion Accessors and Mutators #region Inherited Methods //_______________________________________________________________________ INHERITED METHODS _______________________________________________________________________ /*public Scheduler(Agent owner) { m_owner = owner; }*/ #endregion Inherited Methods #region Events //_____________________________________________________________________________ EVENTS _____________________________________________________________________________ #endregion Events #region Other Methods //__________________________________________________________________________ OTHER METHODS _________________________________________________________________________ public void Add(Behaviour behaviour) { m_enabledBehaviours.Add(behaviour); } public void AddRange(List<Behaviour> behaviours) { m_enabledBehaviours.AddRange(behaviours); } public void Block(Behaviour behaviour) { if (m_enabledBehaviours.Remove(behaviour)) { m_disabledBehaviours.Add(behaviour); } } public void Remove(Behaviour behaviour) { if (!m_disabledBehaviours.Remove(behaviour)) { m_enabledBehaviours.Remove(behaviour); } } public void RemoveFromEnabled(Behaviour behaviour) { m_enabledBehaviours.Remove(behaviour); } public void RemoveFromDisabled(Behaviour behaviour) { m_disabledBehaviours.Remove(behaviour); } #endregion Other Methods #endregion Methods } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class test : MonoBehaviourWithProp { [SerializeField] private int myint; public int MonToto { get { return myint; } set { myint = value; } } [SerializeField] private float myFloat; public float MyFloat { get { return myFloat; } set { myFloat = value; } } [SerializeField] private byte myByte; public byte MyByte { get { return myByte; } set { myByte = value; } } [SerializeField] private bool mybool; public bool MyBool { get { return mybool; } set { mybool = value; } } [SerializeField] private RectTransform myRect; public RectTransform MyRect { get { return myRect; } set { myRect = value; } } [SerializeField] private char myChar; public char MyChar { get { return myChar; } set { myChar = value; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SphereMove : MonoBehaviour { float startpos, endpos, t; bool iscolor; Renderer render; Material mat, defaultMat; // Start is called before the first frame update void Start() { t = 0.0f; startpos = transform.position.x; endpos = (startpos + 3 >= 5) ? startpos - 3 : startpos + 3; iscolor = false; render = this.GetComponent<Renderer>(); mat = new Material(Shader.Find("Learning/StdColor")); mat.SetColor("_AmbientColor", new Color(.5f, 0.2f, 1f, 1f)); mat.SetColor("_Color", new Color(0.5f, 0f, 1f, 1f)); mat.SetFloat("_ColorPower", 8.4f); defaultMat = new Material(Shader.Find("Learning/StdDiffuse")); defaultMat.color = Color.white; } // Update is called once per frame void Update() { this.transform.position = new Vector3(Mathf.Lerp(startpos, endpos, t), this.transform.position.y, this.transform.position.z); t += 0.4f * Time.deltaTime; if (t > 1.0f) { float temp = startpos; startpos = endpos; endpos = temp; t = 0.0f; if (!iscolor) { render.material = mat; iscolor = true; } else { render.material = defaultMat; iscolor = false; } } } }
using UnityEngine; using System.Collections; using System; public class BasicMovement : MonoBehaviour { Animator animator; EntityInfo entityInfo; CharacterController characterController; HitPointManager hitPointManager; double deathAnimationTime; double timer; // Use this for initialization void Start () { animator = gameObject.GetComponent<Animator>(); entityInfo = gameObject.GetComponent<EntityInfo>(); characterController = gameObject.GetComponent<CharacterController>(); hitPointManager = gameObject.GetComponent<HitPointManager>(); timer = 0; deathAnimationTime = 4f; } // Update is called once per frame void Update() { animator.SetBool("IsDead", hitPointManager.isDead()); if (!hitPointManager.isDead()) { Vector3 movementVector = entityInfo.getCurrentMovementVector(); characterController.Move(movementVector * gameObject.transform.localScale.magnitude); animator.SetFloat("MovementSpeed", characterController.velocity.z * entityInfo.getFacing()); animator.SetFloat("VerticalSpeed", characterController.velocity.y); animator.SetBool("IsGrounded", characterController.isGrounded); animator.SetBool("IsCrouching", entityInfo.isCrouching()); animator.SetBool("IsJumping", entityInfo.isJumping()); animator.SetInteger("Facing", entityInfo.getFacing()); if (characterController.isGrounded) { entityInfo.landed(); } } else { // Game over if (timer < deathAnimationTime) { timer += Time.deltaTime; gameObject.GetComponent<Collider>().enabled = false; } else { Cursor.visible = true; Application.LoadLevel("GameOver"); } } } }
using Dapper; using log4net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Dynamic; using System.Linq; using System.Web; namespace ReportesCLIN2 { public class DictionaryConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { this.WriteValue(writer, value); } private void WriteValue(JsonWriter writer, object value) { var t = JToken.FromObject(value); switch (t.Type) { case JTokenType.Object: this.WriteObject(writer, value); break; case JTokenType.Array: this.WriteArray(writer, value); break; default: writer.WriteValue(value); break; } } private void WriteObject(JsonWriter writer, object value) { writer.WriteStartObject(); var obj = value as IDictionary<string, object>; foreach (var kvp in obj) { writer.WritePropertyName(kvp.Key); this.WriteValue(writer, kvp.Value); } writer.WriteEndObject(); } private void WriteArray(JsonWriter writer, object value) { writer.WriteStartArray(); var array = value as IEnumerable<object>; foreach (var o in array) { this.WriteValue(writer, o); } writer.WriteEndArray(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return ReadValue(reader); } private object ReadValue(JsonReader reader) { while (reader.TokenType == JsonToken.Comment) { if (!reader.Read()) throw new JsonSerializationException("Unexpected Token when converting IDictionary<string, object>"); } switch (reader.TokenType) { case JsonToken.StartObject: return ReadObject(reader); case JsonToken.StartArray: return this.ReadArray(reader); case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Undefined: case JsonToken.Null: case JsonToken.Date: case JsonToken.Bytes: return reader.Value; default: throw new JsonSerializationException (string.Format("Unexpected token when converting IDictionary<string, object>: {0}", reader.TokenType)); } } private object ReadArray(JsonReader reader) { IList<object> list = new List<object>(); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.Comment: break; default: var v = ReadValue(reader); list.Add(v); break; case JsonToken.EndArray: return list; } } throw new JsonSerializationException("Unexpected end when reading IDictionary<string, object>"); } private object ReadObject(JsonReader reader) { var obj = new Dictionary<string, object>(); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: var propertyName = reader.Value.ToString(); if (!reader.Read()) { throw new JsonSerializationException("Unexpected end when reading IDictionary<string, object>"); } var v = ReadValue(reader); obj[propertyName] = v; break; case JsonToken.Comment: break; case JsonToken.EndObject: return obj; } } throw new JsonSerializationException("Unexpected end when reading IDictionary<string, object>"); } public override bool CanConvert(Type objectType) { return typeof(IDictionary<string, object>).IsAssignableFrom(objectType); } } public static class Extensions { public static HashSet<T> ToHashSet<T>( this IEnumerable<T> source, IEqualityComparer<T> comparer = null) { return new HashSet<T>(source, comparer); } } public class DapperHelpers { public static dynamic ToExpandoObject(object value) { IDictionary<string, object> dapperRowProperties = value as IDictionary<string, object>; //dynamic expando = new ExpandoObject(); Dictionary<string, object> expando = new Dictionary<string, object>(); foreach (KeyValuePair<string, object> property in dapperRowProperties) ((IDictionary<string, object>)expando).Add(property.Key, property.Value); return expando; } } public class JsonObjectTypeHandler : SqlMapper.ITypeHandler { public void SetValue(IDbDataParameter parameter, object value) { parameter.Value = (value == null) ? (object)DBNull.Value : JsonConvert.SerializeObject(value); parameter.DbType = DbType.String; } public object Parse(Type destinationType, object value) { return JsonConvert.DeserializeObject(value.ToString(), destinationType); } } public class DbFactory { private static ILog log = LogManager.GetLogger(typeof(DbFactory)); public static IDbConnection Conn(string conn) { var connectionString = conn; HttpContext context = HttpContext.Current; var connection = new SqlConnection( connectionString ); return connection; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using AutoRest.Core.Logging; using System.Globalization; namespace AutoRest.Swagger { /// <summary> /// Represents a single validation violation. /// </summary> public class ComparisonMessage { public ComparisonMessage(MessageTemplate template, FileObjectPath path, Category severity, params object[] formatArguments) { Severity = severity; Message = $"Comparison: {template.Id} - {string.Format(CultureInfo.CurrentCulture, template.Message, formatArguments)}"; Path = path; Id = template.Id; } public Category Severity { get; } public string Message { get; } /// <summary> /// The JSON document path to the element being validated. /// </summary> public FileObjectPath Path { get; } /// <summary> /// The id of the validation message /// </summary> public int Id { get; private set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; #pragma warning disable 1591 // use this to disable comment warnings namespace Fall2020_CSC403_Project.code { public class BattleCharacter : Character { public float Health { get; set; } public int MaxHealth { get; private set; } public int Level { get; private set; } public float strength; public event Action<int> AttackEvent; public BattleCharacter(Vector2 initPos, Collider collider) : base(initPos, collider) { Level = 1; MaxHealth = 20; strength = 2; Health = MaxHealth; } public void OnAttack(int amount) { AttackEvent((int)(amount * strength)); } public void AlterHealth(float amount) { Health += amount; } public void LevelUp() { Level += 1; // Level = 1, Strength = 3; Level = 2, Strength = 4 AlterStrength(Level); // Level = 2, MaxHealth = 30; Level = 3, MaxHealth = 45 IncreaseMaxHealth(Level); } public void AlterStrength(int amount) { strength += amount; } public void IncreaseMaxHealth(int amount) { MaxHealth = MaxHealth + (amount * 5); } } }
using Braspag.Domain.DTO; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using System; namespace Braspag.Domain.Entities { public class Pagamento { [BsonRepresentation(BsonType.ObjectId)] public string _id { get; private set; } public string comprador { get; private set; } public string numeroCartao { get; private set; } public string dataVencimento { get; private set; } public string codSegurancaCartao { get; private set; } public decimal? valorCompra { get; private set; } public decimal? valorLojista { get; private set; } public decimal? valorAdquirente { get; private set; } public string adquirente { get; private set; } public string bandeira { get; private set; } public DateTime data { get; private set; } protected Pagamento() { } private Pagamento(PagamentoDto dto) { this._id = this._id; this.comprador = dto.comprador; this.numeroCartao = dto.numeroCartao; this.dataVencimento = dto.dataVencimento; this.codSegurancaCartao = dto.codSegurancaCartao; this.valorCompra = dto.valorCompra; this.valorLojista = dto.valorLojista; this.valorAdquirente = dto.valorAdquirente; this.adquirente = dto.adquirente; this.bandeira = dto.bandeira; this.data = DateTime.Now; } public static Pagamento RetornaPagamento(PagamentoDto dto) { return new Pagamento(dto); } } }
// -------------------------------- // <copyright file="CarMake.cs" > // © 2013 KarzPlus Inc. // </copyright> // <author>JDuverge</author> // <summary> // CarMake Entity Layer Object. // </summary> // --------------------------------- using System; using KarzPlus.Entities.Common; namespace KarzPlus.Entities { /// <summary> /// CarMake entity object. /// </summary> [Serializable] public class CarMake { public bool IsItemModified { get; set; } private int? makeId; /// <summary> /// Gets or sets MakeId. /// </summary> [SqlName("MakeId")] public int? MakeId { get { return makeId; } set { if (value != makeId) { makeId = value; IsItemModified = true; } } } private string name; /// <summary> /// Gets or sets Name. /// </summary> [SqlName("Name")] public string Name { get { return name; } set { if (value != name) { name = value; IsItemModified = true; } } } private string manufacturer; /// <summary> /// Gets or sets Manufacturer. /// </summary> [SqlName("Manufacturer")] public string Manufacturer { get { return manufacturer; } set { if (value != manufacturer) { manufacturer = value; IsItemModified = true; } } } private bool deleted; /// <summary> /// Gets or sets Deleted. /// </summary> [SqlName("Deleted")] public bool Deleted { get { return deleted; } set { if (value != deleted) { deleted = value; IsItemModified = true; } } } /// <summary> /// Initializes a new instance of the CarMake class. /// </summary> public CarMake() { MakeId = default(int?); Name = default(string); Manufacturer = default(string); Deleted = default(bool); IsItemModified = false; } public override string ToString() { return string.Format("MakeId: {0}, Name: {1}, Manufacturer: {2};", MakeId, Name, Manufacturer); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ItemEdit.Models { public class ModsConfigJson { public string name { get; set; } public string author { get; set; } public string license { get; set; } public string version { get; set; } public Dependencies dependencies { get; set; } public Res res { get; set; } public Src src { get; set; } public Dictionary<string, Dictionary<string,object>> db { get; set; } } public class Dependencies { } public class Res { } public class Src { } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; // Write a program that removes from a text file all words listed in given another // text file. Handle all possible exceptions in your methods. namespace _12RemoveListedWords { class Program { static void Main(string[] args) { } } }
using FXBLOOM.DomainLayer.CustomerAggregate; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace FXBLOOM.DataLayer.Configuration { class AccountConfiguration : IEntityTypeConfiguration<Account> { public void Configure(EntityTypeBuilder<Account> builder) { builder.HasKey(e => e.Id); builder.Property(e => e.Id).ValueGeneratedOnAdd(); } } }
using System; using System.Collections.Generic; namespace RestApiEcom.Models { public partial class TResPaiement { public int PaieId { get; set; } public int? PaieFactId { get; set; } public int? PaieFactAgId { get; set; } public float? PaieMontant { get; set; } public DateTime? PaieDate { get; set; } public int? PaieColId { get; set; } public int? PaieScValId { get; set; } public virtual TResCollecte PaieCol { get; set; } public virtual TResFacture PaieFact { get; set; } public virtual TSContValeur PaieScVal { get; set; } } }
using System.Collections; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; //Diese Klasse ist zuständig um aus einem FMOD Event die Marker und BPM zu extrahieren. //Die Marker werden von dieser Klasse aus an den MarkerManger weitergegeben der diese dann auswertet bzw zu einem Event zuordnet. [RequireComponent(typeof(FMODUnity.StudioEventEmitter))] public class FmodTimeline : MonoBehaviour { //BEATSYSTEM [StructLayout(LayoutKind.Sequential)] class TimelineInfo { public int currentMusicBeat = 0; public FMOD.StringWrapper lastMarker = new FMOD.StringWrapper(); } //Um das Event des Emitters zu holen und zuzuweisen public FMODUnity.StudioEventEmitter _emitter; FMOD.Studio.EventInstance _musicInstance; public static FmodTimeline _instance; public MarkerManager _markerManager; public int _beat; public string _marker; public bool _fullBar; public int _barCounter; bool isLoaded; TimelineInfo _timelineInfo; GCHandle _timelineHandle; FMOD.Studio.EVENT_CALLBACK _beatCallback; private void OnEnable() { if (_instance == null) { _instance = this; } else if (_instance != this) { Destroy(gameObject); } GlobalEventSystem.instance.onInit += StartLoad; } private void OnDisable() { isLoaded = false; GlobalEventSystem.instance.onInit -= StartLoad; } // Start is called before the first frame update void StartLoad() { if (!isLoaded) { isLoaded = true; _emitter.Play(); _musicInstance = _emitter.EventInstance; AssignBeatEvent(_musicInstance); _markerManager = GetComponent<MarkerManager>(); _markerManager._emitter = _emitter; _markerManager._musicInstance = _musicInstance; GetComponent<MusicLayerController>()._musicEvent = _emitter; SpectrumManager._instance.musicInstance = _musicInstance; } } //---BEATDETECTION--- void AssignBeatEvent(FMOD.Studio.EventInstance instance) { _timelineInfo = new TimelineInfo(); _timelineHandle = GCHandle.Alloc(_timelineInfo, GCHandleType.Pinned); _beatCallback = new FMOD.Studio.EVENT_CALLBACK(BeatEventCallback); instance.setUserData(GCHandle.ToIntPtr(_timelineHandle)); instance.setCallback(_beatCallback, FMOD.Studio.EVENT_CALLBACK_TYPE.TIMELINE_BEAT | FMOD.Studio.EVENT_CALLBACK_TYPE.TIMELINE_MARKER); } void StopAndClear(FMOD.Studio.EventInstance instance) { instance.setUserData(IntPtr.Zero); instance.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT); instance.release(); _timelineHandle.Free(); } [AOT.MonoPInvokeCallback(typeof(FMOD.Studio.EVENT_CALLBACK))] FMOD.RESULT BeatEventCallback(FMOD.Studio.EVENT_CALLBACK_TYPE type, FMOD.Studio.EventInstance instance, IntPtr parameterPtr) { IntPtr timelineInfoPtr; FMOD.RESULT result = instance.getUserData(out timelineInfoPtr); if (result != FMOD.RESULT.OK) { Debug.LogError("Timeline Callback error: " + result); } else if (timelineInfoPtr != IntPtr.Zero) { GCHandle timelineHandle = GCHandle.FromIntPtr(timelineInfoPtr); TimelineInfo timelineInfo = (TimelineInfo)timelineHandle.Target; switch (type) { case FMOD.Studio.EVENT_CALLBACK_TYPE.TIMELINE_BEAT: { var parameter = (FMOD.Studio.TIMELINE_BEAT_PROPERTIES)Marshal.PtrToStructure(parameterPtr, typeof(FMOD.Studio.TIMELINE_BEAT_PROPERTIES)); timelineInfo.currentMusicBeat = parameter.beat; _beat = timelineInfo.currentMusicBeat; _barCounter = parameter.bar - 1; _fullBar = false; //Debug.Log("BEAT: " + beat); if (_beat == 4) { _fullBar = true; } } break; case FMOD.Studio.EVENT_CALLBACK_TYPE.TIMELINE_MARKER: { var parameter = (FMOD.Studio.TIMELINE_MARKER_PROPERTIES)Marshal.PtrToStructure(parameterPtr, typeof(FMOD.Studio.TIMELINE_MARKER_PROPERTIES)); timelineInfo.lastMarker = parameter.name; _marker = timelineInfo.lastMarker; _markerManager.parseMarkerString(_marker); } break; } } return FMOD.RESULT.OK; } }
using UnityEngine; using System.Collections; public class ExplosionDamage : MonoBehaviour { public float Damage = 1.0f; }
using GetLabourManager.ActionFilters; using GetLabourManager.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace GetLabourManager.Controllers { [Authorize] [RBAC] public class BranchController : Controller { // GET: Branch RBACDbContext db; public BranchController() { db = new RBACDbContext(); } public ActionResult Index() { return View(new Branch()); } public JsonResult BranchList() { var records = db.Branch.AsEnumerable().Select(x => new { Id = x.Id, Name = x.Name, IsHeadBranch = x.IsHead == true ? "YES" : "NO" }).ToList(); return Json(new { data = records }, JsonRequestBehavior.AllowGet); } public PartialViewResult GetEdit(int Id) { var entity = db.Branch.FirstOrDefault(x => x.Id == Id); return PartialView("_EditBranch", entity); } public JsonResult DeleteBranch(int Id) { try { var entity = db.Branch.FirstOrDefault(x => x.Id == Id); db.Branch.Remove(entity); db.SaveChanges(); return Json(new { message = "success" }, JsonRequestBehavior.AllowGet); } catch (Exception err) { return Json(new { message = err.Message.ToUpper() }, JsonRequestBehavior.AllowGet); } } //SaveBranch public JsonResult SaveBranch(Branch model) { try { var branches = db.Branch.Select(x => x).ToList(); if (string.IsNullOrWhiteSpace(model.Name)) { return Json(new { message = "BRANCH NAME NOT SPECIFIED" }, JsonRequestBehavior.AllowGet); } if (branches.Exists(c => c.Name.ToLower().Equals(model.Name.ToLower()))) { return Json(new { message = "BRANCH NAME ALREADY EXIST" }, JsonRequestBehavior.AllowGet); } db.Branch.Add(model); db.SaveChanges(); return Json(new { message = "success" }, JsonRequestBehavior.AllowGet); } catch (Exception err) { return Json(new { message = err.Message.ToUpper() }, JsonRequestBehavior.AllowGet); } } public JsonResult EditBranch(Branch model) { try { var branches = db.Branch.FirstOrDefault(x => x.Id==model.Id); if (string.IsNullOrWhiteSpace(model.Name)) { return Json(new { message = "BRANCH NAME NOT SPECIFIED" }, JsonRequestBehavior.AllowGet); } //if (branches.Exists(c => c.Name.ToLower().Equals(model.Name.ToLower()))) //{ // return Json(new { message = "BRANCH NAME ALREADY EXIST" }, JsonRequestBehavior.AllowGet); //} branches.Name = model.Name; branches.IsHead = model.IsHead; db.Entry<Branch>(branches).State= System.Data.Entity.EntityState.Modified; db.SaveChanges(); return Json(new { message = "success" }, JsonRequestBehavior.AllowGet); } catch (Exception err) { return Json(new { message = err.Message.ToUpper() }, JsonRequestBehavior.AllowGet); } } } }
// ----------------------------------------------------------------------- // <copyright file="AlignAttribute.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root // for license information. // </copyright> // ----------------------------------------------------------------------- using System; namespace Mlos.SettingsSystem.Attributes { /// <summary> /// An attribute class to mark the alignment for a codegen structs and fields. /// </summary> [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Field, AllowMultiple = false)] public class AlignAttribute : BaseCodegenFieldAttribute { /// <summary> /// Gets the alignment size. /// </summary> public uint Size { get; } /// <summary> /// Initializes a new instance of the <see cref="AlignAttribute"/> class. /// </summary> /// <param name="size">The alignment size for the field.</param> public AlignAttribute(uint size) { Size = size; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Hayalpc.Fatura.CoreApi.Extensions; using Hayalpc.Fatura.Data; using NLog; using Hayalpc.Fatura.Common.Helpers; namespace Hayalpc.Fatura.CoreApi { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddScopes(); services.AddRepositories(); services.AddServices(); services.AddCustomCors("AllowAllOrigins"); services.AddConfigurations(); services.AddSwagger(); services.AddDbContextManager(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseCors("AllowAllOrigins"); app.AddUseSwagger("API v1.0.0"); app.Use((context, next) => { MappedDiagnosticsLogicalContext.Set("request_ip", RequestHelper.GetRealIp(context)); MappedDiagnosticsLogicalContext.Set("trace_identifier", context.TraceIdentifier); return next(); }); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
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 OtelBilgiSistemi { public partial class FormMüşteriPuanlama : Form { DBİşlemleri db = DBİşlemleri.GetInstance(); public FormMüşteriPuanlama() { InitializeComponent(); } public string oteladı; private void FormMüşteriPuanlama_Load(object sender, EventArgs e) { lblAd.Text += " " + oteladı; } private void BtnPuan_Click(object sender, EventArgs e) { int verilenPuan = Convert.ToInt16(cmbPuan.Text); db.OtelAğacı.Ara(oteladı).otel.otelPuanı = db.YeniPuanHesapla(db.OtelAğacı.Ara(oteladı).otel, verilenPuan); //dbden alınan bilgilerle puanı hesaplayıp otele koy db.PuanıGüncelle(db.OtelAğacı.Ara(oteladı).otel); //yeni puanı dbye gönder MessageBox.Show("Puanı Başarıyla gönderdiniz"); } } }
/** File Created May 11th 2017 - File name = GameManager.cs Author: Gabriel Gaudreau Project: ShootingRangeGame */ using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { public static GameManager gm; // 0 - 13 - 26 [SerializeField] GameObject npcPrefab; private float playerScore, roundTimer, scoreAccuracyPercent, totalPossibleScore, hitAccuracyPercent; private int shotCounter, shotsLeft, shotsHit; private bool firstSpawn, scoreBoardUp, gameIsPaused, gameOver; [SerializeField] Text scoreText, scorePerShotText, shotCounterText, shotsLeftText, scoreAccuracyText, hitAccuracyText, roundTimeText, canvasTitleText; [SerializeField] Canvas statsCanvas, pauseCanvas, gameOverCanvas; /// <summary> /// Initializes singleton in the event that it is null /// </summary> void Awake() { if (gm == null) gm = this; } /// <summary> /// Start method, initializes variables and locks cursor. /// </summary> void Start() { shotsLeft = PlayerPrefs.GetInt("numShots"); roundTimer = PlayerPrefs.GetFloat("roundTime"); firstSpawn = true; Cursor.lockState = CursorLockMode.Locked; scoreText.text = string.Format("Score: {0:#}", playerScore); shotCounterText.text = string.Format("Shot Counter: {0:#}", shotCounter); scorePerShotText.text = string.Format("Avg Score per Shot: {0:#0.00}", playerScore); shotsLeftText.text = string.Format("AMMO: {0:#}", shotsLeft); scoreAccuracyText.text = string.Format("Score Accuracy: {0:#0.00}%", scoreAccuracyPercent); hitAccuracyText.text = string.Format("Hit Accuracy: {0:#0.00}%", hitAccuracyPercent); roundTimeText.text = string.Format("{0:#0} s", roundTimer); statsCanvas.enabled = false; pauseCanvas.enabled = false; gameOverCanvas.enabled = false; } /// <summary> /// Public method to add score. Also adds up accuracy %. /// </summary> /// <param name="x">score to be added</param> /// <param name="max">Max possible score from that shot</param> public void AddScore(float x, float max) { shotsHit++; totalPossibleScore += max; playerScore += x; UpdateAccuracy(); scoreText.text = string.Format("Score: {0:#}", playerScore); scorePerShotText.text = string.Format("Avg Score per Shot: {0:#.00}", playerScore / shotCounter); } /// <summary> /// Returns the amount of shots left. /// </summary> /// <returns>Int</returns> public int GetShotsLeft() { return shotsLeft; } /// <summary> /// Update Accuracy every shot taken. Updates stats panel information as well. /// </summary> void UpdateAccuracy() { hitAccuracyPercent = ((float)shotsHit / (float)shotCounter) * 100; scoreAccuracyPercent = (playerScore / totalPossibleScore) * 100; scorePerShotText.text = string.Format("Avg Score per Shot: {0:#.00}", playerScore / shotCounter); scoreAccuracyText.text = string.Format("Score Accuracy: {0:#.00}%", scoreAccuracyPercent); hitAccuracyText.text = string.Format("Hit Accuracy: {0:#.00}%", hitAccuracyPercent); } /// <summary> /// public method to add to the shotcounter variable. Used with the singleton, updates text info as well. /// </summary> public void AddShotCounter() { shotCounter++; shotsLeft--; if(shotsLeft <= 0) { GameOver("Out of Bullets!"); } shotCounterText.text = string.Format("Shot Counter: {0:#}", shotCounter); shotsLeftText.text = string.Format("AMMO: {0:#}", shotsLeft); UpdateAccuracy(); } /// <summary> /// Returns the game pause status bool. /// </summary> /// <returns>returns a bool, if game is paused or not</returns> public bool IsGamePaused() { return gameIsPaused; } /// <summary> /// This method will be executed with the round timer runs out or the player has no more bullets. /// </summary> void GameOver(string s) { gameOver = true; canvasTitleText.text = s; statsCanvas.enabled = true; gameOverCanvas.enabled = true; gameIsPaused = true; Cursor.lockState = CursorLockMode.None; } /// <summary> /// Update method, on escape, the cursor is unlocked and this method will spawn the initial wave of target dummies. /// </summary> void Update() { if (!gameIsPaused) { roundTimer -= Time.deltaTime; if(roundTimer <= 0.0f) { GameOver("Out of Time!"); } roundTimeText.text = string.Format("{0:#.0} s", roundTimer); if (Input.GetKeyDown(KeyCode.Escape)) { pauseCanvas.enabled = true; gameIsPaused = true; Time.timeScale = 0.0f; if (Cursor.lockState == CursorLockMode.Locked) Cursor.lockState = CursorLockMode.None; } if (Input.GetKeyDown(KeyCode.Tab)) { if (!statsCanvas.enabled) { statsCanvas.enabled = true; } else { statsCanvas.enabled = false; } } //can this be run in start?? using a bool to only execute once in update. This is the initial spawn of enemies. if (firstSpawn) { Instantiate(npcPrefab, CircularPath.instance.Nodes[0].WorldPos, Quaternion.identity); Instantiate(npcPrefab, CircularPath.instance.Nodes[13].WorldPos, Quaternion.identity); Instantiate(npcPrefab, CircularPath.instance.Nodes[26].WorldPos, Quaternion.identity); firstSpawn = false; } } } /// <summary> /// Pause menu function to resume game. /// </summary> public void OnClickResume() { pauseCanvas.enabled = false; Time.timeScale = 1.0f; gameIsPaused = false; Cursor.lockState = CursorLockMode.Locked; } /// <summary> /// Will update all the highscores upon exiting or going to main menu once the game has ended. /// </summary> void UpdateHighScores() { if (playerScore > PlayerPrefs.GetFloat("highScore")) PlayerPrefs.SetFloat("highScore", playerScore); if (hitAccuracyPercent > PlayerPrefs.GetFloat("highestHitAccuracy")) PlayerPrefs.SetFloat("highestHitAccuracy", hitAccuracyPercent); if (scoreAccuracyPercent > PlayerPrefs.GetFloat("highestScoreAccuracy")) PlayerPrefs.SetFloat("highestScoreAccuracy", scoreAccuracyPercent); if (playerScore / shotCounter > PlayerPrefs.GetFloat("highScorePerShot")) PlayerPrefs.SetFloat("highScorePerShot", playerScore / shotCounter); } /// <summary> /// Pause menu function to return to main menu. Saves highscore. /// </summary> public void OnClickBackToMenu() { if(gameOver) UpdateHighScores(); Time.timeScale = 1.0f; SceneManager.LoadScene(0); } /// <summary> /// Pause menu button function to exit game. /// </summary> public void OnClickExit() { if(gameOver) UpdateHighScores(); Application.Quit(); } } //THINGS I WANT TO CHANGE: //crouch/sprint //custom text box or something for custom game settings //sensitivity setting?? //player position in editor //movement considers mouse orientation when calculating forward direction. //air strafing csgo style //fix cursor and aim, always goes a bit topleft of where cursor is
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Controller; namespace ControllerTest {/* [TestFixture()] class testThreadpool { private readonly = new(); [Test()] public void temps() { } } */}
using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UtilitiesNameSpace { public enum LocateBy { Id = 1, XPath = 2, TagName = 3, Name = 4, CssSelector = 5, LinkText = 6 } public class Element { public By ByElement { get; set; } public LocateBy LocatedBy { get; set; } public string LocatorString { get; set; } public Element() { } public Element(LocateBy ByMethod, string LocatorValue = "") { ByElement = ByElementLocator(ByMethod, LocatorValue); LocatorString = LocatorValue; LocatedBy = ByMethod; } /// <summary> /// Reduce the verbosity of the code used for creating locators by using this unified method /// </summary> /// <param name="LocateBy"></param> /// <param name="ByLocatorString"></param> /// <returns></returns> public By ByElementLocator(LocateBy LocatedBy, string ByLocatorString) { //Reset to a null object to remove any garbage ByElement = null; if (!string.IsNullOrEmpty(ByLocatorString)) { switch (LocatedBy) { case LocateBy.Id: ByElement = By.Id(ByLocatorString); break; case LocateBy.Name: ByElement = By.Name(ByLocatorString); break; case LocateBy.XPath: ByElement = By.XPath(ByLocatorString); break; case LocateBy.CssSelector: ByElement = By.CssSelector(ByLocatorString); break; case LocateBy.TagName: ByElement = By.TagName(ByLocatorString); break; case LocateBy.LinkText: ByElement = By.LinkText(ByLocatorString); break; default: throw new ArgumentException(); }//end switch }//endif: there's a locator value return ByElement; }//end method ByElementLocator /// <summary> /// Use Element to return selenium IWebElement /// </summary> /// <param name="driver"></param> /// <returns></returns> public IWebElement ReturnWebElement(IWebDriver driver) { IWebElement WebElement = driver.FindElement(ByElement); return WebElement; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /// <summary> /// MapStateManager is the place to keep a succession of events or "states" when building /// a multi-step AI demo. Note that this is a way to manage /// /// State changes could happen for one of two reasons: /// when the user has pressed a number key 0..9, desiring a new phase /// when something happening in the game forces a transition to the next phase /// /// One use will be for AI demos that are switched up based on keyboard input. For that, /// the number keys 0..9 will be used to dial in whichever phase the user wants to see. /// </summary> public class ForestMapManager : MonoBehaviour { // Set prefabs public GameObject PlayerPrefab; // You, the player public GameObject LittleBirdPrefab; // Agent doing chasing public GameObject BirdKingPrefab; // Agent getting chased public GameObject RedPrefab; // Red Riding Hood, or just "team red" public GameObject BluePrefab; // "team blue" public GameObject TreePrefab; // New for Assignment #2 public NPCController house; // for future use // Set up to use spawn points. Can add more here, and also add them to the // Unity project. This won't be a good idea later on when you want to spawn // a lot of agents dynamically, as with Flocking and Formation movement. public GameObject spawner1; public Text SpawnText1; public GameObject spawner2; public Text SpawnText2; public GameObject spawner3; public Text SpawnText3; public int TreeCount; private List<GameObject> spawnedNPCs; // When you need to iterate over a number of agents. //private List<GameObject> trees; //private int currentPhase = 0; // This stores where in the "phases" the game is. //private int previousPhase = 0; // The "phases" we were just in //public int Phase => currentPhase; StateController stateController; LineRenderer line; public GameObject[] Path; public Text narrator; // // Use this for initialization. Create any initial NPCs here and store them in the // spawnedNPCs list. You can always add/remove NPCs later on. public Vector3 RandomPosition(int xlb, int xub, int zlb, int zub) { bool found = false; Vector3 newPos = new Vector3(0f, 1f, 0f); while (found == false) { float x = UnityEngine.Random.Range(xlb, xub); float z = UnityEngine.Random.Range(zlb, zub); newPos = new Vector3(x, 1f, z); Collider[] hitColliders = Physics.OverlapSphere(newPos, .5f); if (hitColliders.Length == 0) { found = true; break; } } return newPos; } void Start() { narrator.text = "This is the place to mention major things going on during the demo, the \"narration.\""; stateController = GameObject.FindGameObjectWithTag("GameController").GetComponent<StateController>(); spawnedNPCs = new List<GameObject>(); GameObject[] flock = new GameObject[5]; //SPAWN FIRST LEADER BIRD. spawnedNPCs[0] spawner1.transform.position = new Vector3(5, 1, 13); GameObject BirdKing = SpawnItem(spawner1, BirdKingPrefab, null, SpawnText1, 3); BirdKing.transform.position = new Vector3(5f, 1f, 12f); BirdKing.tag = "BK3"; spawnedNPCs.Add(BirdKing); //SPAWNING FIRST GROUP OF BIRDS. spawnedNPCs[1,2,3,4,5] for (int i = 0; i < 5; i++) { //RandomPosition(-23, 23, -19, 19) will spawn across the whole map spawner1.transform.position = RandomPosition(5, 6, 10, 11); //LITTLE BIRDS FOLLOW THE LEADER GameObject bird = SpawnItem(spawner1, LittleBirdPrefab, BirdKing.GetComponent<NPCController>(), SpawnText1, 6); spawnedNPCs.Add(bird); flock[i] = spawnedNPCs[i]; } for (int j = 0; j < 6; j++) { spawnedNPCs[j].GetComponent<SteeringBehavior>().flock = flock; } ClearStage(); EnterMapStateThree(); } public void ClearStage() { foreach (GameObject NPC in spawnedNPCs) { //NPC.GetComponent<NPCController>().label.enabled = false; NPC.SetActive(false); } } private void Update() { string inputstring = Input.inputString; if (inputstring.Length > 0) { if (inputstring[0] == 'R' || inputstring[0] == 'r') { stateController.LoadThree(); } if (inputstring[0] == 'S' || inputstring[0] == 's') { foreach (GameObject NPC in spawnedNPCs) { //NPC.GetComponent<NPCController>().label.enabled = true; NPC.SetActive(true); } } } } public void EnterMapStateThree() { narrator.text = "Birds are trying their best to follow the leader"; CreatePath(); } /// <summary> /// SpawnItem placess an NPC of the desired type into the game and sets up the neighboring /// floating text items nearby (diegetic UI elements), which will follow the movement of the NPC. /// </summary> /// <param name="spawner"></param> /// <param name="spawnPrefab"></param> /// <param name="target"></param> /// <param name="spawnText"></param> /// <param name="phase"></param> /// <returns></returns> private GameObject SpawnItem(GameObject spawner, GameObject spawnPrefab, NPCController target, Text spawnText, int phase) { Vector3 size = spawner.transform.localScale; Vector3 position = spawner.transform.position + new Vector3(UnityEngine.Random.Range(-size.x / 2, size.x / 2), 0, UnityEngine.Random.Range(-size.z / 2, size.z / 2)); GameObject temp = Instantiate(spawnPrefab, position, Quaternion.identity); if (target) { temp.GetComponent<SteeringBehavior>().target = target; } temp.GetComponent<NPCController>().label = spawnText; temp.GetComponent<NPCController>().phase = phase; Camera.main.GetComponent<CameraController>().player = temp; return temp; } /* /// <summary> /// SpawnTrees will randomly place tree prefabs all over the map. The diameters /// of the trees are also varied randomly. /// /// Note that it isn't particularly smart about this (yet): notably, it doesn't /// check first to see if there is something already there. This should get fixed. /// </summary> /// <param name="numTrees">desired number of trees</param> private void SpawnTrees(int numTrees) { float MAX_X = 25; // Size of the map; ideally, these shouldn't be hard coded float MAX_Z = 20; float less_X = MAX_X - 1; float less_Z = MAX_Z - 1; float diameter; for (int i = 0; i < numTrees; i++) { //Vector3 size = spawner.transform.localScale; Vector3 position = new Vector3(UnityEngine.Random.Range(-less_X, less_X), 0, UnityEngine.Random.Range(-less_Z, less_Z)); GameObject temp = Instantiate(TreePrefab, position, Quaternion.identity); // diameter will be somewhere between .2 and .7 for both X and Z: diameter = UnityEngine.Random.Range(0.2F, 0.7F); temp.transform.localScale = new Vector3(diameter, 1.0F, diameter); trees.Add(temp); } } */ /* private void DestroyTrees() { GameObject temp; for (int i = 0; i < trees.Count; i++) { temp = trees[i]; Destroy(temp); } // Following this, write whatever methods you need that you can bolt together to // create more complex movement behaviors. } */ private void CreatePath() { line = GetComponent<LineRenderer>(); line.positionCount = Path.Length; for (int i = 0; i < Path.Length; i++) { line.SetPosition(i, Path[i].transform.position); } } void OnDrawGizmosSelected() { Gizmos.color = new Color(1, 0, 0, 0.5f); Gizmos.DrawCube(spawner1.transform.position, spawner1.transform.localScale); Gizmos.DrawCube(spawner2.transform.position, spawner2.transform.localScale); Gizmos.DrawCube(spawner3.transform.position, spawner3.transform.localScale); } }
using System.Threading.Tasks; using System.Windows.Forms; using TutteeFrame2.DataAccess; using TutteeFrame2.View; using TutteeFrame2.Model; namespace TutteeFrame2.Controller { class HomeController { HomeView view; SessionStatus currentStatus = SessionStatus.Valid; public Teacher mainTeacher; public string sessionID; public bool logined = false; public HomeController(HomeView view) { this.view = view; } public void Logout() { SessionDA.Instance.DeleteSession(mainTeacher.ID, sessionID); logined = false; LoginView loginView = new LoginView(view); view.Hide(); loginView.FormClosed += (s, ev) => { if (loginView.DialogResult == DialogResult.OK) view.Show(); else Application.Exit(); }; loginView.ShowDialog(); } public async void LoadTeacher(string teacherID) { view.SetLoad(true, "Đang tải thông tin người dùng..."); await Task.Delay(200); await Task.Run(() => { mainTeacher = TeacherDA.Instance.GetTeacher(teacherID); mainTeacher.FormClassID = TeacherDA.Instance.GetInchargeClass(mainTeacher.ID); if (!string.IsNullOrEmpty(mainTeacher.FormClassID)) { mainTeacher.Type = TeacherType.FormerTeacher; } if (mainTeacher.ID.ToUpper() == "AD999999") { mainTeacher.Type = TeacherType.SuperUser; mainTeacher.Position = "Tài khoản admin"; } }); view.ShowData(); view.SetLoad(false); currentStatus = SessionStatus.Valid; StartCheckSession(); } public async void StartCheckSession() { SessionStatus sessionStatus = currentStatus; await Task.Run(async () => { while (currentStatus == sessionStatus && logined) { await Task.Delay(550); if (!SessionDA.Instance.isChannelBusy && mainTeacher != null) { sessionStatus = SessionDA.Instance.CheckSession(mainTeacher.ID, sessionID); } } }); if (!logined) return; currentStatus = sessionStatus; view.OnCorrupt(currentStatus); switch (currentStatus) { case SessionStatus.Valid: view.OnReconnect(); break; case SessionStatus.NotValid: break; case SessionStatus.NoConnection: break; default: break; } } } }
using UnityEngine; using System.Collections; public class TextMover : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void FixedUpdate(){ //Debug.Log (transform.position.y); if (transform.position.y < 760) { transform.position = new Vector3 (transform.position.x, transform.position.y + 1f, transform.position.z); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Photon.Realtime; using Common.Utility; using Common.Dialog; using Hashtable = ExitGames.Client.Photon.Hashtable; namespace Lobby { public class LobbyUI : MonoBehaviour { [Header("Prefab")] public GameObject roomInfoPrefab; [Header("RoomInfo")] public ScrollRect scroll; [Header("PlayerInfo")] public Image profileImg; public Text textID; public Text textWinRate; public Action<RoomInfo> JoinRoomHandler; public Action<string, byte> CreateRoomHandler; private Dictionary<string, RoomInfoItem> roomInfoItemDic; private void Awake() { roomInfoItemDic = new Dictionary<string, RoomInfoItem>(); } public void SetPlayerInfo(Hashtable hashtable) { Sprite sprite = ProfileImageLoader.GetImageByFileName(hashtable["profileImgName"].ToString()); profileImg.sprite = sprite; textID.text = hashtable["id"].ToString(); int win = (int)hashtable["win"]; int lose = (int)hashtable["lose"]; if ((win + lose) == 0) { textWinRate.text = "0%"; } else { textWinRate.text = (win / (float)(win + lose) * 100).ToString("0") + "%"; } } public void OnRoomInfoUpdate(List<RoomInfo> list) { foreach (var info in list) { if (roomInfoItemDic.ContainsKey(info.Name)) { if(info.RemovedFromList) { var item = roomInfoItemDic[info.Name]; roomInfoItemDic.Remove(info.Name); Destroy(item.gameObject); } else { roomInfoItemDic[info.Name].RoomInfo = info; } } else { var item = Instantiate(roomInfoPrefab, scroll.content).GetComponent<RoomInfoItem>(); if (item.SetRoomInfo(info, JoinRoomHandler)) { //roomInfoItemList.Add(item); roomInfoItemDic.Add(info.Name, item); } else { Destroy(item.gameObject); } } } } public void OnCreateRoomClick() { //lobbyManager.CreateRoom("ABC"); InputDialog.InputDialogBuilder builder = new InputDialog.InputDialogBuilder(); builder.SetTitle("방 정보를 입력해주세요.") .SetInputField("방 이름을 입력해주세요.", "roomName", false) .SetInputField("방 인원을 입력해주세요.(최소 2 최대 5)", "maxNum", false, InputType.NUMBER) .SetBtn("방 생성", CreateRoom) .SetBtn("취소"); builder.Build().Show(); } public void Alert(string msg) { AlertDialog.AlertDialogBuilder builder = new AlertDialog.AlertDialogBuilder(); builder.SetTitle("알림") .SetMessage(msg) .SetCloseTime(2f) .Build() .Show(); } private void CreateRoom(Dictionary<string, DialogInputField> dic) { string name = dic["roomName"].GetText(); if (roomInfoItemDic.ContainsKey(name)) { Alert("이미 존재하는 방 이름입니다."); return; } int inputNum = int.Parse(dic["maxNum"].GetText()); if (inputNum < 1 || inputNum > 5) { Alert("방 인원 설정이 잘못됐습니다."); return; } //inputNum = Mathf.Clamp(inputNum,2,5); byte num = Convert.ToByte(inputNum); CreateRoomHandler?.Invoke(name, num); } } }
namespace Core.Enums { public enum Color { White = 1, Blue = 2, Yellow = 3, Red = 4, Green = 5 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Model; using UnityEngine; using UnityEngine.UI; namespace Hotfix { [ObjectEvent] public class UICowRoomComponentEvent : ObjectEvent<UICowRoomComponent>, IAwake { public void Awake() { this.Get().Awake(); } } public class UICowRoomComponent : Component { Text RoomId; public void Awake() { ReferenceCollector rc = this.GetEntity<UI>().GameObject.GetComponent<ReferenceCollector>(); RoomId = rc.Get<GameObject>("RoomId").GetComponent<Text>(); } public void DoCmd(G2C_RoomCommand cmd) { RoomId.text = "房间号:" + cmd.roomId; } } }
using System; using MessagePack; using UniRx; using UnityEngine; namespace Share { public sealed class PackedMessageSupplier : MonoBehaviour { [SerializeField] private UDPClientHolder clientHolder; private readonly Subject<PackedMessage.IdentifiedPointArray> subjectPointArray = new Subject<PackedMessage.IdentifiedPointArray>(); public IObservable<PackedMessage.IdentifiedPointArray> ObservablePointArray => subjectPointArray; private readonly Subject<PackedMessage.DevicePose> subjectDevicePose = new Subject<PackedMessage.DevicePose>(); public IObservable<PackedMessage.DevicePose> ObservableDevicePose => subjectDevicePose; private void Start() { clientHolder.ObservableReceive .TakeUntilDestroy(this) .Subscribe(OnReceive); } private void OnReceive(byte[] buffer) { var deserialized = MessagePackSerializer.Deserialize<PackedMessage.IPackedMessage>(buffer); switch (deserialized) { case PackedMessage.IdentifiedPointArray identifiedPointArray: subjectPointArray.OnNext(identifiedPointArray); break; case PackedMessage.DevicePose devicePose: subjectDevicePose.OnNext(devicePose); break; default: return; } } } }
using UnityEngine; using System.Collections; using Leap; public class ComplexFingerState : ComplexCondition { private bool[] fingerStates; public ComplexFingerState(bool[] fingerStates) { this.fingerStates = fingerStates; } public override bool isSatisfied(Hand hand) { for(int i=0; i<fingerStates.Length; i++) { if (hand.Fingers[i].IsExtended != fingerStates[i]) return false; } return true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AnnealingWPF.Common { public class SatConfiguration { public IList<bool> Valuations { get; set; } = new List<bool>(); public SatInstance Instance { get; set; } public float Score { get; set; } private List<int> unsatisfiedLiterals = new List<int>(); private int idOfMostUnsatisfiedLiteral = -1; private int optimalizationValue = -1; private int numberOfUnsatisfiedClauses; private Satisfiability configurationSatisfiability = Satisfiability.UNKNOWN; public SatConfiguration() { } public SatConfiguration(SatConfiguration other) { Valuations = new List<bool>(other.Valuations); Instance = other.Instance; } public static SatConfiguration RandomConfiguration(SatInstance instance, Random random) { var satConfiguration = new SatConfiguration(); satConfiguration.Instance = instance; for (int i = 0; i < instance.Literals.Count; i++) { satConfiguration.Valuations.Add(Convert.ToBoolean(random.Next(0, 2))); } return satConfiguration; } public void FlipValuation(int flipIndex) { Valuations[flipIndex] = !Valuations[flipIndex]; } public int GetOptimalizationValue() { if(optimalizationValue < 0) optimalizationValue = Instance.Literals.Aggregate(0, (total, current) => Valuations[current.Id-1] ? total + current.Weight : total); return optimalizationValue; } public int IndexOfRandomToImproveScore(Random random) { //Converts the valuations to a list of indexes of valuations that are negative var negativeIds = Valuations.Select((valuation, index) => valuation ? -1 : index).Where(i => i > 0); if (negativeIds.Count() == 0) return -1; return negativeIds.ElementAtOrDefault(random.Next(negativeIds.Count())) - 1; } public int IndexOfRandomToImproveSatisfiability(Random random) { if (configurationSatisfiability == Satisfiability.UNKNOWN) CalculateSatisfiability(); if (unsatisfiedLiterals.Count == 0) return -1; return unsatisfiedLiterals.ElementAt(random.Next(unsatisfiedLiterals.Count)) - 1; } public bool IsSatisfiable() { if(configurationSatisfiability == Satisfiability.UNKNOWN) CalculateSatisfiability(); if (configurationSatisfiability == Satisfiability.SATISFIABLE) return true; else if (configurationSatisfiability == Satisfiability.UNSATISFIABLE) return false; throw new Exception(); } public int NumberOfUnsatisfiedClauses() { if (configurationSatisfiability == Satisfiability.UNKNOWN) CalculateSatisfiability(); return numberOfUnsatisfiedClauses; } private void CalculateSatisfiability() { numberOfUnsatisfiedClauses = 0; foreach(var clause in Instance.Clauses) { if (!clause.IsSatisfiable(this)) IncrementUnsatisfiedLiterals(clause); } if (numberOfUnsatisfiedClauses == 0) configurationSatisfiability = Satisfiability.SATISFIABLE; else configurationSatisfiability = Satisfiability.UNSATISFIABLE; } private void IncrementUnsatisfiedLiterals(SatClause clause) { foreach(var literal in clause.RatedLiterals) { unsatisfiedLiterals.Add(literal.Literal.Id); } numberOfUnsatisfiedClauses++; } private enum Satisfiability { UNKNOWN, SATISFIABLE, UNSATISFIABLE } } }
using Accounts.Service.Contract.Commands; using Core; using CORE2.Exceptions; using System; using System.Threading.Tasks; using Xunit; namespace Accounts.Services.Tests2 { public class SuspendHandlersTests { [Fact] public async Task SuspendHandlers_ThrowsResourceNotFoundExc() { var identity = new BizflyIdentity(); string groupId = "test-group-id"; string ownerId = "test-user-id"; _mockGroupRepository .Setup(repo => repo.GetByIdAsync(groupId)) .Throws(new ResourceNotFoundException()) .Verifiable(); // _mockGroupRepository //.Setup(repo => repo.AddOrUpdateAsync(It.IsAny<Group>(), null)) //.Throws(new ResourceNotFoundException()); SuspendGroupCommand command = new SuspendGroupCommand(identity, ownerId, groupId); await _suspendGroupHandler.Handle(command); _mockGroupRepository.Verify(); } } }
using DDDSouthWest.Website.Framework; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace DDDSouthWest.Website.Features.Public.Account.Login { [Route("account/login", Name = RouteNames.AccountLogin)] public class LoginController : Controller { [Authorize] public IActionResult Login() { return RedirectToRoute(RouteNames.AccountDashboard); } } }
using System; using System.Net.Http.Headers; using System.Text; using System.Net.Http; using System.Web; using System.Threading.Tasks; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Data.Entity; using System.Collections; using System.Globalization; namespace MicrosoftUpdate { class Program { static void Main(string[] args) { Task<string> task = MakeRequest(); task.Wait(); JObject NVDdatabase = JObject.Parse(task.Result); Dictionary<string, string> ProductNameLibrary = ProductMapper((JArray)NVDdatabase["ProductTree"]["FullProductName"]); List<PatchDetail> PatchRecords = new List<PatchDetail>(); //Populated During Parse to match Patchs with there affected Products Dictionary<string, List<string>> PatchToProductMap = new Dictionary<string, List<string>>(); //Parses through each CVE JArray Vulnerabilities = (JArray)NVDdatabase["Vulnerability"]; foreach (JToken Vulnerability in Vulnerabilities) { //Parses through each PatchID JArray RemediationArray = (JArray)Vulnerability["Remediations"]; foreach (JObject Remediation in RemediationArray) { string PatchId = (string)Remediation["Description"]["Value"]; int Throw;//To be discarded Update with Regex bool result = Int32.TryParse(PatchId, out Throw); // Build Patch to Product ID match if (result) { if (PatchToProductMap.Keys.Contains(PatchId) != true) { PatchToProductMap.Add(PatchId, new List<string>()); } foreach (JToken ProductID in Remediation["ProductID"]) { if (PatchToProductMap[PatchId].Contains((string)ProductID)) { continue; } PatchToProductMap[PatchId].Add((string)ProductID); } } } foreach (JObject Remediation in RemediationArray) { string PatchId = (string)Remediation["Description"]["Value"]; if (PatchToProductMap.Keys.Contains(PatchId)) { if(PatchRecords.Where(x => x.PatchNo == PatchId).Count() == 0) { List<string> ProductIDAssociation = PatchToProductMap[PatchId]; PatchDetail PatchRecord = new PatchDetail(); // Patch PatchRecord.PatchNo = PatchId; PatchRecord.PatchVersion = null; PatchRecord.UpdateDateTime = DateTime.Now; PatchRecord.UpdatedBy = "MicrsoftUpdateAPi"; PatchRecord.AppID = 1; PatchRecord.TypeID = 1; PatchRecord.DeployedOn = null; PatchRecord.CreatedBy = "MicrsoftUpdateAPi"; PatchRecord.CreatedDateTime = DateTime.Now; PatchRecord.Link = @"https://support.microsoft.com/en-us/help/" + PatchId; PatchRecord.Title = (string)Vulnerability["Title"]["Value"]; PatchRecord.CVE = (string)Vulnerability["CVE"]; // Severity Levels JArray ThreatArray = (JArray)Vulnerability["Threats"]; List<string> SeverityList = new List<string>(); foreach (JToken Threat in ThreatArray) { if ((int)Threat["Type"] == 3)// Alternative Types avalible Look at source material { foreach (JToken ProductID in Threat["ProductID"]) { if (ProductIDAssociation.Contains((string)ProductID)) { SeverityList.Add((string)Threat["Description"]["Value"]); } } } } PatchRecord.Severity = string.Join(" : ", SeverityList.Distinct()); // Pub Date var RevisonArray = Vulnerability["RevisionHistory"]; foreach (JToken Revison in RevisonArray) { if ((string)Revison["Number"] == "1.0") { PatchRecord.Pubdate = Convert.ToDateTime((string)Revison["Date"]); } if ((string)Revison["Description"]["Value"] == "Information published.") { PatchRecord.Pubdate = Convert.ToDateTime((string)Revison["Date"]); } } //Description var NotesArray = Vulnerability["Notes"]; foreach (JToken Note in NotesArray) { if ((string)Note["Title"] == "Description") { PatchRecord.Description = (string)Note["Value"]; } } //Populat Products Affected and Description List List<string> ProductsAffected = new List<string>(); foreach (string product in ProductIDAssociation) { ProductsAffected.Add(ProductNameLibrary[product]); } PatchRecord.productsAffected = string.Join(", ", ProductsAffected); string Description = "<p> Effected versions <ul>"; foreach (string product in ProductsAffected) { Description += "<li>" + product + "</li>"; } Description += "</ul></p>"; PatchRecord.Description += Description; PatchRecords.Add(PatchRecord); } } } } Console.WriteLine("Data Population Complete"); foreach (PatchDetail PatchRecord in PatchRecords) { if (PatchRecord.Link.Count() > 999) { Console.WriteLine("char Length error at " + PatchRecord.PatchNo + ":" + PatchRecord.Link); } if (PatchRecord.PatchNo.Count() > 500) { Console.WriteLine("char Length error at " + PatchRecord.PatchNo + ":" + PatchRecord.PatchNo); } if (PatchRecord.CVE.Count() > 250) { Console.WriteLine("char Length error at " + PatchRecord.PatchNo + ":" + PatchRecord.CVE); } if (PatchRecord.Title.Count() > 500) { Console.WriteLine("char Length error at " + PatchRecord.PatchNo +":"+ PatchRecord.Title); } if (PatchRecord.Severity.Count() > 50) { Console.WriteLine("char Length error at " + PatchRecord.PatchNo + ":" + PatchRecord.Severity); } if (PatchRecord.productsAffected.Count() > 2000) { Console.WriteLine("char Length error at " + PatchRecord.PatchNo +":"+ PatchRecord.productsAffected); } } Console.WriteLine("Data to PatchDetails Start"); // using (var dbCtx = new PatchMgrDevEntities()) { int skipped = 0; foreach (PatchDetail PatchRecord in PatchRecords) { if (dbCtx.PatchDetails.Any(x => x.PatchNo == PatchRecord.PatchNo)) { skipped++;Console.WriteLine(skipped.ToString()); Console.WriteLine("skip "+PatchRecord.PatchNo); continue; } dbCtx.PatchDetails.Add(PatchRecord); } // dbCtx.SaveChanges(); Console.WriteLine("Console End"); } } static Dictionary<string,string> ProductMapper (JArray ProductTree) { Dictionary<string, string> ProductIDDict = new Dictionary<string, string>(); foreach (JObject Product in ProductTree) { ProductIDDict.Add((string)Product["ProductID"], (string)Product["Value"]); } return ProductIDDict; } static async Task<string> MakeRequest() { var client = new HttpClient(); var queryString = HttpUtility.ParseQueryString(string.Empty); queryString["api-version"] = "2016-01-01"; // Request headers client.DefaultRequestHeaders.Add("api-key", ""); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //- Test if new Cvrf is avalible var Date = DateTime.Now; string month = Date.ToString("MMM", CultureInfo.InvariantCulture);//DateTime.Now.ToString("MMM", CultureInfo.InvariantCulture); int year = Date.Year; string APIdate = "'" + year.ToString() + "-" + month + "'"; var uri = "https://api.msrc.microsoft.com/Updates(" + APIdate + ")?" + queryString; var ResponseCode = await client.GetAsync(uri); bool UpdateCheck = ResponseCode.IsSuccessStatusCode; while(UpdateCheck==false) { Date = Date.AddMonths(-1); month = Date.ToString("MMM", CultureInfo.InvariantCulture); APIdate = "'" + year.ToString() + "-" + month + "'"; uri = "https://api.msrc.microsoft.com/Updates(" + APIdate + ")?" + queryString; ResponseCode = await client.GetAsync(uri); UpdateCheck = ResponseCode.IsSuccessStatusCode; } var UpdateResponse =JObject.Parse(ResponseCode.Content.ReadAsStringAsync().Result); uri = (string)UpdateResponse["value"][0]["CvrfUrl"]; var response = await client.GetAsync(uri); Task<string> ApiResponse = response.Content.ReadAsStringAsync(); return ApiResponse.Result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.AppServices.DataContracts.Cashbag { /// <summary> /// 消费账单列表 /// </summary> public class BillDetailListDto { /// <summary> /// 消费时间 /// </summary> public DateTime CreateDate { get; set; } /// <summary> /// 账单日期 /// </summary> public DateTime BillDate { get; set; } /// <summary> /// 消费金额 /// </summary> public decimal Amount { get; set; } /// <summary> /// 交易号 /// </summary> public string PayNo { get; set; } /// <summary> /// 备注 /// </summary> public string Notes { get; set; } /// <summary> /// 订单号 /// </summary> public string OutOrderNo { get; set; } /// <summary> /// 交易号 /// </summary> public string OutTradeNo { get; set; } } }
using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TwinkleStar.Common.Excel { public static class NpoiExtend { public static List<PicturesInfo> GetAllPictureInfos(this ISheet sheet) { return sheet.GetAllPictureInfos(null, null, null, null); } public static List<PicturesInfo> GetAllPictureInfos(this ISheet sheet, int? minRow, int? maxRow, int? minCol, int? maxCol, bool onlyInternal = true) { if (sheet is HSSFSheet) { return GetAllPictureInfos((HSSFSheet)sheet, minRow, maxRow, minCol, maxCol, onlyInternal); } else if (sheet is XSSFSheet) { return GetAllPictureInfos((XSSFSheet)sheet, minRow, maxRow, minCol, maxCol, onlyInternal); } else { throw new Exception("未处理类型,没有为该类型添加:GetAllPicturesInfos()扩展方法!"); } } private static List<PicturesInfo> GetAllPictureInfos(HSSFSheet sheet, int? minRow, int? maxRow, int? minCol, int? maxCol, bool onlyInternal) { List<PicturesInfo> picturesInfoList = new List<PicturesInfo>(); var shapeContainer = sheet.DrawingPatriarch as HSSFShapeContainer; if (null != shapeContainer) { var shapeList = shapeContainer.Children; foreach (var shape in shapeList) { if (shape is HSSFPicture && shape.Anchor is HSSFClientAnchor) { var picture = (HSSFPicture)shape; var anchor = (HSSFClientAnchor)shape.Anchor; if (IsInternalOrIntersect(minRow, maxRow, minCol, maxCol, anchor.Row1, anchor.Row2, anchor.Col1, anchor.Col2, onlyInternal)) { picturesInfoList.Add(new PicturesInfo(anchor.Row1, anchor.Row2, anchor.Col1, anchor.Col2, picture.PictureData.Data)); } } } } return picturesInfoList; } private static List<PicturesInfo> GetAllPictureInfos(XSSFSheet sheet, int? minRow, int? maxRow, int? minCol, int? maxCol, bool onlyInternal) { List<PicturesInfo> picturesInfoList = new List<PicturesInfo>(); var documentPartList = sheet.GetRelations(); foreach (var documentPart in documentPartList) { if (documentPart is XSSFDrawing) { var drawing = (XSSFDrawing)documentPart; var shapeList = drawing.GetShapes(); foreach (var shape in shapeList) { if (shape is XSSFPicture) { var picture = (XSSFPicture)shape; var anchor = picture.GetPreferredSize(); if (IsInternalOrIntersect(minRow, maxRow, minCol, maxCol, anchor.Row1, anchor.Row2, anchor.Col1, anchor.Col2, onlyInternal)) { picturesInfoList.Add(new PicturesInfo(anchor.Row1, anchor.Row2, anchor.Col1, anchor.Col2, picture.PictureData.Data)); } } } } } return picturesInfoList; } private static bool IsInternalOrIntersect(int? rangeMinRow, int? rangeMaxRow, int? rangeMinCol, int? rangeMaxCol, int pictureMinRow, int pictureMaxRow, int pictureMinCol, int pictureMaxCol, bool onlyInternal) { int _rangeMinRow = rangeMinRow ?? pictureMinRow; int _rangeMaxRow = rangeMaxRow ?? pictureMaxRow; int _rangeMinCol = rangeMinCol ?? pictureMinCol; int _rangeMaxCol = rangeMaxCol ?? pictureMaxCol; if (onlyInternal) { return (_rangeMinRow <= pictureMinRow && _rangeMaxRow >= pictureMaxRow && _rangeMinCol <= pictureMinCol && _rangeMaxCol >= pictureMaxCol); } else { return ((Math.Abs(_rangeMaxRow - _rangeMinRow) + Math.Abs(pictureMaxRow - pictureMinRow) >= Math.Abs(_rangeMaxRow + _rangeMinRow - pictureMaxRow - pictureMinRow)) && (Math.Abs(_rangeMaxCol - _rangeMinCol) + Math.Abs(pictureMaxCol - pictureMinCol) >= Math.Abs(_rangeMaxCol + _rangeMinCol - pictureMaxCol - pictureMinCol))); } } } }
#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.Reflection.Emit; using Android.App; using Android.Graphics; using Android.OS; using Com.Syncfusion.Charts; using Android.Views; using Android.Content; using Android.Widget; using System.Collections.Generic; using System; namespace SampleBrowser { public class Line : SamplePage { SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.PrimaryAxis = new CategoryAxis { PlotOffset = 20 }; chart.SecondaryAxis = new NumericalAxis(); var lineSeries = new LineSeries { DataSource = MainPage.GetLineData() }; lineSeries.DataMarker.ShowLabel = true; lineSeries.StrokeWidth = 3; lineSeries.DataMarker.LabelStyle.Angle = -45; chart.Series.Add(lineSeries); return chart; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FastFood { public partial class Take_Away : UserControl { public Take_Away() { InitializeComponent(); } public static int x, count = 0; private void pictureBox5_Click(object sender, EventArgs e) { } private void button9_Click(object sender, EventArgs e) { } private void button4_Click(object sender, EventArgs e) { x = 15; count += x; } private void button1_Click(object sender, EventArgs e) { x = 19; count += x; } private void button5_Click(object sender, EventArgs e) { x = 25; count += x; } private void button6_Click(object sender, EventArgs e) { x = 27; count += x; } private void button2_Click(object sender, EventArgs e) { x = 6; count += x; } private void button3_Click(object sender, EventArgs e) { x = 8; count += x; } } }
using mTransport.Methodes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace mTransport.Models { public partial class AffectationVehicule : ICRUD { public void Delete() { //using (DB db = new DB()) //{ // var d = db.AffectationVehicules.SingleOrDefault(i => i.Id == Id); // if (d != null) // { // db.AffectationVehicules.Remove(d); // db.SaveChanges(); // } //} } public void Insert() { using (DB db = new DB()) { db.AffectationVehicules.Add(this); db.SaveChanges(); } } public void Update() { using (DB db = new DB()) { db.Entry(this).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); } } //Méthode ne necessitant pas la création d'un objet est a déclarée static public static List<AffectationVehicule> getAll() { using (DB db = new DB()) { var l = db.AffectationVehicules.Where(i => i.Supprime == false).ToList(); foreach (var item in l) { item.Chauffeur = Chauffeur.getUnChauffeur(item.IdChauffeur); item.Vehicule = Vehicule.getVehicule(item.IdVehicule); } return l; } } public static AffectationVehicule getAffectationVehicule(int Id) { using (DB db = new DB()) { AffectationVehicule c = new AffectationVehicule(); c = db.AffectationVehicules.SingleOrDefault(i => i.Id == Id); return c; } } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using CsvHelper.Configuration; namespace CloneDeploy_Entities { [Table("images")] public class ImageEntity { [Column("image_approved")] public int Approved { get; set; } [Column("image_classification_id")] public int ClassificationId { get; set; } [Column("image_description")] public string Description { get; set; } [Column("image_enabled")] public int Enabled { get; set; } [Column("image_environment")] public string Environment { get; set; } [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Column("image_id")] public int Id { get; set; } [Column("image_is_viewable_ond")] public int IsVisible { get; set; } [Column("last_upload_guid")] public string LastUploadGuid { get; set; } [Column("image_name")] public string Name { get; set; } [Column("image_os")] public string Os { get; set; } [Column("image_is_protected")] public int Protected { get; set; } [Column("image_type")] public string Type { get; set; } } [NotMapped] public class ImageWithDate : ImageEntity { public DateTime? LastUsed { get; set; } } public sealed class ImageCsvMap : ClassMap<ImageEntity> { public ImageCsvMap() { Map(m => m.Name).Name("Name"); Map(m => m.Description).Name("Description"); Map(m => m.Type).Name("Type"); Map(m => m.Environment).Name("Environment"); Map(m => m.LastUploadGuid).Name("LastUploadGuid"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterviewQuestions { public class StringManipulate { public static void Run() { var input = "asg34523asdfg 1234sg123"; var str2 = "asg34523asdfg 1234321gs"; var answ = isStringContainSameChar(input, str2); Console.WriteLine("Is the 2 strings \n{0} \n{1} have same chars:\n{2}", input,str2,answ); int[] numbs; if (ExtractNumbers(input, out numbs)) foreach (int numb in numbs) { Console.WriteLine(numb); } int[] index; if( GetSubstringIndex(input, "sg'", out index)) foreach (int i in index) { Console.WriteLine(i); } int[] index2; if(GetSubstringIndex("abc", "abc", out index2)) foreach (int i in index2) { Console.WriteLine(i); } int[] index3; if(GetSubstringIndex("abc", "bca",out index3)) foreach (int i in index2) { Console.WriteLine(i); } Console.ReadLine(); } static public bool ExtractNumbers(string input, out int[] results) { List<int> resultList = new List<int>(); char[] temp = input.ToCharArray(); List<char> number = new List<char>(); bool start = false; for (int i = 0; i < temp.Length; i++) { var iChar = temp[i]; if (!start) { if (iChar >= '0' && iChar <= '9') { start = true; number.Add(iChar); } } else { if (iChar >= '0' && iChar <= '9') { number.Add(iChar); if (i == temp.Length - 1) { var n = number.ToArray(); resultList.Add(int.Parse(new string(n))); } } else { start = false; //list<char> to char[]; var n = number.ToArray(); //char[] => string =>int resultList.Add(int.Parse(new string(n))); number.Clear(); } } } if (resultList.Count > 0) { results = resultList.ToArray(); return true; } results = new int[0]; return false; } static public bool GetSubstringIndex(string src, string sub, out int[] indexs) { List<int> results = new List<int>(); char[] cSrc = src.ToCharArray(); char[] cSub = sub.ToCharArray(); int i = 0; int j = 0; bool isSub = false; if (cSrc.Length < cSub.Length) throw new ArgumentException("asdf"); while (i < cSrc.Length) { while (cSrc[i++] == cSub[j++]) { if (j == cSub.Length -1) { isSub = true; break; } } if (isSub) results.Add(i - (cSub.Length - 1)); j = 0; isSub = false; } indexs = results.ToArray(); return isSub; } //如果两个字符串含有相同的字母,并且相同字母的个数也相同,那么就称这2个字符串是相等的 public static bool isStringContainSameChar(string aStr, string bStr) { var cStrA = aStr.ToCharArray(); var bStrB = bStr.ToCharArray(); var count = new int[256]; foreach (char c in cStrA) { count[c]++; } foreach (char c in bStrB) { count[c]--; } foreach (int i in count) { if (i > 0) return false; } return true; } } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace Danh_Trong.Objects { public class Script { string _character; int _position, _time; public int Time { get { return _time; } set { _time = value; } } public int Position { get { return _position; } set { _position = value; } } public string Character { get { return _character; } set { _character = value; } } public Script() { } public Script(string character, int position, int time) { this.Character = character; this.Position = position; this.Time = time; } } }
using AutoMapper; using PaymentApi.Dtos; using PaymentApi.Models; namespace PaymentApi.Profiles { public class PaymentProfile : Profile { public PaymentProfile() { CreateMap<Payment, PaymentShowDto>(); CreateMap<PaymentReadDto, Payment>(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO.Ports; using ZedGraph; namespace KRT_Graph { public partial class MainForm : Form { private ComPort _comPort = new ComPort(); private GraphLayer _graphLayer = null; private DataSaveLayer _dataSaveLayer = new DataSaveLayer(); private const byte GetFlowCommand = (byte)'G'; private int _intervalSec = 100; private DateTime _timeStart = new DateTime(); private Status _status = Status.Stop; private bool _isAutoSize = true; private int _maxVal = 1; private int _minVal = 0; private int _middleVal = 0; private int[] _yMidArr = new int[100]; private int _yMidCnt = 8; private int _yIndex = 0; public MainForm() { InitializeComponent(); _graphLayer = new GraphLayer(zGraph); } private void LoadPortSettings() { _comPort.DataReceived += ComPort_DataReceived; cmbPort.Items.Clear(); cmbPort.Items.AddRange(_comPort.PortNames()); cmbBaudRate.Items.Clear(); cmbBaudRate.Items.AddRange(_comPort.BaudRates()); cmbPort.SelectedItem = Properties.Settings.Default.Port; cmbBaudRate.SelectedItem = Properties.Settings.Default.BaudRate; } private void PreUpdatePortSettings() { int cpi = cmbPort.SelectedIndex; string port=""; if (cpi >= 0) { port = cmbPort.Items[cpi].ToString(); } cmbPort.Items.Clear(); cmbPort.Items.AddRange(_comPort.PortNames()); cmbPort.SelectedItem = port; } private void UpdatePortSettings() //Проверить ОК { int cpi = cmbPort.SelectedIndex; int bri = cmbBaudRate.SelectedIndex; if (cpi >= 0 && bri >= 0) { string port = cmbPort.Items[cpi].ToString(); string baudRate = cmbBaudRate.Items[bri].ToString(); if (!string.IsNullOrWhiteSpace(port) && !string.IsNullOrWhiteSpace(baudRate) && _comPort.isPortChange(port,baudRate)) { _comPort.Open(port, baudRate); } } } private void SavePortSettings() { int cpi = cmbPort.SelectedIndex; int bri = cmbBaudRate.SelectedIndex; if (_comPort.IsOpen() && cpi >= 0 && bri >= 0) { string port = cmbPort.Items[cpi].ToString(); string baudRate = cmbBaudRate.Items[bri].ToString(); if (!string.IsNullOrWhiteSpace(port) && !string.IsNullOrWhiteSpace(baudRate)) { Properties.Settings.Default.Port = port; Properties.Settings.Default.BaudRate = baudRate; } } _comPort.Close(); } private void LoadIntervalSettings() { _intervalSec = Properties.Settings.Default.Interval; switch (_intervalSec) { case 1: cmbInterval.SelectedIndex = 0; break; case 5: cmbInterval.SelectedIndex = 0+1; break; case 10: cmbInterval.SelectedIndex = 1+1; break; case 30: cmbInterval.SelectedIndex = 2+1; break; case 60: cmbInterval.SelectedIndex = 3+1; break; case 60 * 2: cmbInterval.SelectedIndex = 4+1; break; case 60 * 5: cmbInterval.SelectedIndex = 5+1; break; case 60 * 10: cmbInterval.SelectedIndex = 6+1; break; case 60 * 30: cmbInterval.SelectedIndex = 7+1; break; case 60 * 60: cmbInterval.SelectedIndex = 8+1; break; } } private void UpdateIntervalSettings() { switch (cmbInterval.SelectedIndex) { case 0: _intervalSec = 1; break; case 0+1: _intervalSec = 5; break; case 1+1: _intervalSec = 10; break; case 2+1: _intervalSec = 30; break; case 3+1: _intervalSec = 60; break; case 4+1: _intervalSec = 60 * 2; break; case 5+1: _intervalSec = 60 * 5; break; case 6+1: _intervalSec = 60 * 10; break; case 7+1: _intervalSec = 60 * 30; break; case 8+1: _intervalSec = 60 * 60; break; default: return; } DateTime dtEnd = _graphLayer.GetEndTime(); _graphLayer.UpdateAsis(dtEnd.AddSeconds(-_intervalSec), dtEnd,false); } //Дописать ОК private void ChangeBtnChecked() { switch (_status) { case Status.Start: btnStopAndClear.Checked = false; btnPause.Checked = false; btnRecAndPlay.Checked = true; break; case Status.Stop: btnStopAndClear.Checked = true; btnPause.Checked = false; btnRecAndPlay.Checked = false; break; case Status.Pause: btnStopAndClear.Checked = false; btnPause.Checked = true; btnRecAndPlay.Checked = false; break; } } #region События private void cmbInterval_SelectedIndexChanged(object sender, EventArgs e) { UpdateIntervalSettings(); } private void txtMaxValue_TextChanged(object sender, EventArgs e) { int value = 0; if (int.TryParse(txtMax.Text, out value) && value > 10) { _maxVal = value; } } private void btnHelp_Click(object sender, EventArgs e) { HelpForm hForm = new HelpForm(); hForm.ShowDialog(); } private void txtMin_TextChanged(object sender, EventArgs e) { int value = 0; if (int.TryParse(txtMin.Text, out value) && value > 0) { _minVal = value; } } private void cmbPort_SelectedIndexChanged(object sender, EventArgs e) { UpdatePortSettings(); } private void btnPortFind_DropDownOpening(object sender, EventArgs e) { PreUpdatePortSettings(); } #endregion private void MainForm_Load(object sender, EventArgs e) { LoadPortSettings(); _graphLayer.LoadGraphSettings(); LoadIntervalSettings(); _timeStart = DateTime.Now; _maxVal = Properties.Settings.Default.MaxValue; _minVal = Properties.Settings.Default.MinValue; txtMax.Text = _maxVal.ToString(); txtMin.Text = _minVal.ToString(); btnAutoSize.Checked = _isAutoSize; ChangeBtnChecked(); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { Properties.Settings.Default.Interval = _intervalSec; Properties.Settings.Default.MaxValue = _maxVal; Properties.Settings.Default.MinValue = _minVal; SavePortSettings(); Properties.Settings.Default.Save(); } private void ReadPortData(byte[] inBuf, int rxIndex) { //case GetFlowCommand : // расход // FlowTemp = 0; // FlowTemp = getchar(); // FlowTemp = (FlowTemp << 8) + getchar(); // FlowTemp = (FlowTemp << 8) + getchar(); // FlowTemp = (FlowTemp << 8) + getchar(); if (inBuf[rxIndex] == GetFlowCommand) { txtDebug.Text = string.Format("{0:X2} {1:X2} {2:X2} {3:X2} {4:X2}", inBuf[rxIndex], inBuf[rxIndex + 1], inBuf[rxIndex + 2], inBuf[rxIndex + 3], inBuf[rxIndex + 4]); //int y = BitConverter.ToInt32(inBuf, rxIndex+1); int y = (((int)inBuf[rxIndex + 1]) << 24) + (((int)inBuf[rxIndex + 2]) << 16) + (((int)inBuf[rxIndex + 3]) << 8) + ((int)inBuf[rxIndex + 4]); if (y > Math.Max(_maxVal * 10, 30 * 1000)) return; //Всплески txtValue.Text = y.ToString(); txtValueMin.Text = (y - _minVal).ToString(); y -= _minVal; _yMidArr[_yIndex] = y; _yIndex++; _yIndex %= _yMidCnt; int temp = 0; for (int i = 0; i < _yMidCnt; i++) { temp += _yMidArr[(i + _yIndex) % _yMidCnt]; } txtMidValue.Text = (temp / _yMidCnt).ToString(); if (_status == Status.Start) { txtLogValuemiMin.AppendText(y.ToString() + "\r\n"); txtLogMaxdelValue.AppendText(((double)_maxVal / (double)y).ToString() + "; " + ((double)y * 1000.0 / _maxVal).ToString() + "\r\n"); DateTime x = DateTime.Now.AddTicks(-_timeStart.Ticks); _graphLayer.UpdateData(y / 1000.0, x, (double)y / _maxVal); //Делим в литры! _dataSaveLayer.UpdateData(y / 1000.0, x); } } } private void ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { byte[] inBuf = new byte[256]; int rxCount = _comPort.Read(ref inBuf, 2); //Время чтения int rxIndex = 0; if (rxCount < 5) return; //Не наше debugTimer.Stop(); //Дебаг офф for (rxIndex = 0; rxIndex < rxCount-4; rxIndex++) { ReadPortData(inBuf, rxIndex); } } private string _programmCompileDate = File.GetLastWriteTime(Application.ExecutablePath).ToString("yyyy-MM-dd"); private void updTimer200ms_Tick(object sender, EventArgs e) { this.Text = "График Расходомера " + ((debugTimer.Enabled) ? "[debug mode on]" : _programmCompileDate); if (_status == Status.Start) { DateTime dtEnd = DateTime.Now.AddTicks(-_timeStart.Ticks); _graphLayer.UpdateAsis(dtEnd.AddSeconds(-_intervalSec), dtEnd, _isAutoSize); } } private void btnRecAndPlay_Click(object sender, EventArgs e) { if (_status == Status.Stop) { _timeStart = DateTime.Now.AddYears(-1); _dataSaveLayer.ClearData(); _graphLayer.ClearData(); txtLogMaxdelValue.Text = ""; txtLogValuemiMin.Text = ""; } _status = Status.Start; ChangeBtnChecked(); } private void btnPause_Click(object sender, EventArgs e) { _status = Status.Pause; ChangeBtnChecked(); } private void btnStopAndClear_Click(object sender, EventArgs e) { _status = Status.Stop; _graphLayer.ClearData(); ChangeBtnChecked(); _timeStart = DateTime.Now.AddYears(-1); DateTime dtEnd = DateTime.Now.AddTicks(-_timeStart.Ticks); _graphLayer.UpdateAsis(dtEnd.AddSeconds(-_intervalSec), dtEnd); } private void btnSave_Click(object sender, EventArgs e) { if (saveFileDialog1.ShowDialog() == DialogResult.OK) { _dataSaveLayer.SaveData(saveFileDialog1.FileName); } } private void btnLoad_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { _status = Status.Stop; ChangeBtnChecked(); _dataSaveLayer.LoadData(openFileDialog1.FileName); _dataSaveLayer.CopyData(_graphLayer, _intervalSec); _dataSaveLayer.TxtLog(txtLogValuemiMin,txtLogMaxdelValue,_maxVal); } } private void btnScreenshot_Click(object sender, EventArgs e) { _graphLayer.SaveAs(); } private void btnAutoSize_Click(object sender, EventArgs e) { DateTime dtEnd = _graphLayer.GetEndTime(); _graphLayer.UpdateAsis(dtEnd.AddSeconds(-_intervalSec), dtEnd); _isAutoSize = (btnAutoSize.Checked ^= true); } private void btnCropFrom_Click(object sender, EventArgs e) { MessageBox.Show("Данная функция ещё не реализована"); } private void btnCropTo_Click(object sender, EventArgs e) { MessageBox.Show("Данная функция ещё не реализована"); } Random _debugRnd = new Random(); private void debugTimer_Tick(object sender, EventArgs e) { int val = 0; val = _debugRnd.Next(1000); byte[] inBuf = {GetFlowCommand,0x00,(byte)(val>>16),(byte)(val>>8),(byte)val,0x00}; ReadPortData(inBuf,0); } } public enum Status { Start, Pause, Stop } }
using System; using System.IO; using FluentAssertions; using NUnit.Framework; using VH.Core.Configuration.AKSKeyVaultFileProvider; namespace VH.Core.Configuration.UnitTests.AKSKeyVaultFileProvider.TheAksKeyVaultSecretFileProvider._GetDirectoryContents { public class when_given_subdirectory_path_that_does_exist { private AksKeyVaultSecretFileProvider _sut; private string _subDirectoryName; [SetUp] public void SetUp() { var rootFolder = TempFolderFactory.CreateExistingTempFolder(); _sut = new AksKeyVaultSecretFileProvider(rootFolder); _subDirectoryName = Guid.NewGuid() .ToString("N") .Substring(0, 5); Directory.CreateDirectory(Path.Combine(rootFolder, _subDirectoryName)); } [Test] public void should_return_instance_of_AksKeyVaultSecretDirectoryContents() { var contents = _sut.GetDirectoryContents(_subDirectoryName); contents.Should().BeOfType<AksKeyVaultSecretDirectoryContents>(); contents.Exists.Should().BeTrue(); } } }
using System.Collections.Generic; using KRF.Core.Entities.Master; using KRF.Core.DTO.Master; namespace KRF.Core.FunctionalContracts { public interface IFleetManagement { /// <summary> /// Create new fleet record in DB /// </summary> /// <param name="fleet"></param> /// <param name="fleetServices"></param> /// <param name="fleetAssignments"></param> /// <returns></returns> int CreateFleet(Fleet fleet, List<FleetService> fleetServices, List<FleetAssignment> fleetAssignments); /// <summary> /// Edit Fleet record /// </summary> /// <param name="fleet"></param> /// <param name="fleetServices"></param> /// <param name="fleetAssignments"></param> /// <returns></returns> bool EditFleet(Fleet fleet, List<FleetService> fleetServices, List<FleetAssignment> fleetAssignments); /// <summary> /// Active/Inactive Fleet status /// </summary> /// <param name="fleetID"></param> /// <param name="tobeEnabled"></param> /// <returns></returns> bool ToggleFleetStatus(int fleetID, bool tobeEnabled); /// <summary> /// Get Fleet Detail by FleetID /// </summary> /// <param name="fleetID"></param> /// <returns></returns> FleetDTO GetFleetDetail(int fleetID); /// <summary> /// Get Fleet Details /// </summary> /// <returns></returns> FleetDTO GetFleetDetails(); } }
using SDL2; using SharpDL.Graphics; using System; namespace SharpDL { public enum MessageBoxType : uint { Error = SDL.SDL_MessageBoxFlags.SDL_MESSAGEBOX_ERROR, Information = SDL.SDL_MessageBoxFlags.SDL_MESSAGEBOX_INFORMATION, Warning = SDL.SDL_MessageBoxFlags.SDL_MESSAGEBOX_WARNING } public static class MessageBox { public static void Show(MessageBoxType messageBoxType, String title, String message, Window parentWindow = null) { IntPtr parentWindowHandle = IntPtr.Zero; if (parentWindow != null) parentWindowHandle = parentWindow.Handle; SDL.SDL_ShowSimpleMessageBox((SDL.SDL_MessageBoxFlags)messageBoxType, title, message, parentWindowHandle); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using WebRoupas.Models; namespace WebRoupas.Controllers { // Esse método de Route configura a rota da aplicação, ou seja, no postman você vai criar uma requisão do tipo get // E o endereço dela vai ficar assim http://seuLocalHost/api/Funcionarios caso seja outro você trocaria o funcionario pelo // primeiro nome do controller, ex RoupasController -> http://seuLocalHost/api/Roupas [Route("api/[controller]")] [ApiController] public class FuncionariosController : ControllerBase { private readonly BancoDeDados _context; public FuncionariosController(BancoDeDados context) { _context = context; } // GET: api/Funcionarios [HttpGet] public async Task<ActionResult<IEnumerable<Funcionario>>> GetFuncionarios() { // Aqui nesse método, repare que comentei o retorno dele, esse retorno está retornando uma lista de funcionarios cadastrados no banco. // Como não cadastrei nenhum substitui por esse retorno abaixo, onde crio uma lista com dois funcionarios e retorno os dois para efeitos de // teste var funcionarios = new List<Funcionario>() { new Funcionario() { Id = 1, CPF= "111111111111", Email = "diegol.aquino@gmail.com", Nome = "Diego Aquino", Senha = "123456"}, new Funcionario() { Id = 2, CPF= "22222222222222", Email = "gabriel@gmail.com", Nome = "Gabriel", Senha = "777777777" } }; return funcionarios; //return await _context.Funcionarios.ToListAsync(); } // GET: api/Funcionarios/5 [HttpGet("{id}")] public async Task<ActionResult<Funcionario>> GetFuncionario(int id) { var funcionario = await _context.Funcionarios.FindAsync(id); if (funcionario == null) { return NotFound(); } return funcionario; } // PUT: api/Funcionarios/5 [HttpPut("{id}")] public async Task<IActionResult> PutFuncionario(int id, Funcionario funcionario) { if (id != funcionario.Id) { return BadRequest(); } _context.Entry(funcionario).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!FuncionarioExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Funcionarios [HttpPost] public async Task<ActionResult<Funcionario>> PostFuncionario(Funcionario funcionario) { _context.Funcionarios.Add(funcionario); await _context.SaveChangesAsync(); return CreatedAtAction("GetFuncionario", new { id = funcionario.Id }, funcionario); } // DELETE: api/Funcionarios/5 [HttpDelete("{id}")] public async Task<ActionResult<Funcionario>> DeleteFuncionario(int id) { var funcionario = await _context.Funcionarios.FindAsync(id); if (funcionario == null) { return NotFound(); } _context.Funcionarios.Remove(funcionario); await _context.SaveChangesAsync(); return funcionario; } private bool FuncionarioExists(int id) { return _context.Funcionarios.Any(e => e.Id == id); } } }
using Microsoft.AspNetCore.SignalR; using System.Threading.Tasks; namespace AweCoreDemo.Hubs { public class SyncHub : Hub { public async Task Send(string key, string act, string group) { await Clients.Others.SendAsync("ReceiveMessage", key, act, group); } } }
using System; using System.Collections.Generic; using System.Text; namespace ManagementStocks.Repository.DTO { public class StockDto { public Guid Id { get; set; } public string Name { get; set; } public string Description { get; set; } public DateTime OperationTime { get; set; } public Guid ProductId { get; set; } public double Quantity { get; set; } public double Price { get; set; } public bool IsCredit { get; set; } } }
using IdentityServer4.Models; using System.Collections.Generic; using System.Security.Claims; namespace SampleOAuth { public static class Config { public static IEnumerable<IdentityResource> Ids => new IdentityResource[] { new IdentityResources.OpenId(), new IdentityResources.Profile(), }; public static IEnumerable<ApiResource> Apis => new ApiResource[] { new ApiResource("api1", "My API #1") { UserClaims = new List<string>() { "location", "userId" } } }; public static IEnumerable<Client> Clients => new Client[] { new Client { ClientId = "client", ClientName = "Client Credentials Client", AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials, ClientSecrets = {new Secret("secret".Sha256())}, AllowedScopes = {"api1", "openid"} } }; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.InputSystem.EnhancedTouch; public class InputManager : MonoBehaviour { [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] static void Init() { if (Application.isEditor && Application.isPlaying) { DeleteInputActionAssetFile(GetInputActionAssetFilePath()); } inputActionAsset = null; pathToInputAction.Clear(); AdditionalInputActionInfos.Clear(); } private static InputManager instance; public static InputManager Instance { get { if (instance == null) { instance = GameObjectUtils.FindComponentWithTag<InputManager>("InputManager"); } return instance; } } private static readonly Dictionary<string, ObservableCancelablePriorityInputAction> pathToInputAction = new Dictionary<string, ObservableCancelablePriorityInputAction>(); public static List<InputActionInfo> AdditionalInputActionInfos { get; private set; }= new List<InputActionInfo>(); /** * Default InputActionAsset is copied to streamingAssetsPath such that users can edit it to their preferences. * Use loaded InputActions-object instead. The loaded InputActions-object is also available via Injection. */ public InputActionAsset defaultInputActionAsset; // Static reference to be persisted across scenes. private static InputActionAsset inputActionAsset; /** * Loaded InputActionAsset. This will be loaded from streamingAssets if possible. * If loading it from file failed, then defaultInputActionMap is used instead. */ private InputActionAsset InputActionAsset { get { if (inputActionAsset == null) { string absoluteFilePath = GetInputActionAssetFilePath(); if (!File.Exists(absoluteFilePath)) { SaveInputActionAssetToFile(defaultInputActionAsset, absoluteFilePath); } inputActionAsset = LoadInputActionAssetFromFile(absoluteFilePath); inputActionAsset.Enable(); } return inputActionAsset; } } private void Start() { if (Touchscreen.current != null && !EnhancedTouchSupport.enabled) { // Enable EnhancedTouchSupport to make use of EnhancedTouch.Touch struct etc. EnhancedTouchSupport.Enable(); } ContextMenu.OpenContextMenus.Clear(); } private void SaveInputActionAssetToFile(InputActionAsset theInputActionAsset, string absoluteFilePath) { Debug.Log($"Saving InputActionAsset to '{absoluteFilePath}'"); try { File.WriteAllText(absoluteFilePath, theInputActionAsset.ToJson(), Encoding.UTF8); } catch (Exception ex) { Log.Logger.Error(ex, $"Error saving default InputActionAsset to '{absoluteFilePath}'"); } } private InputActionAsset LoadInputActionAssetFromFile(string absoluteFilePath) { Debug.Log($"Loading InputActionAsset from '{absoluteFilePath}'"); try { string inputActionMapJson = File.ReadAllText(absoluteFilePath, Encoding.UTF8); return InputActionAsset.FromJson(inputActionMapJson); } catch (Exception ex) { Log.Logger.Error(ex, $"Error loading InputActionAsset from '{absoluteFilePath}'. Using default InputActionAsset instead."); return defaultInputActionAsset; } } private static void DeleteInputActionAssetFile(string absoluteFilePath) { try { File.Delete(absoluteFilePath); } catch (Exception ex) { Log.Logger.Error(ex, $"Error deleting InputActionAsset '{absoluteFilePath}'"); } } private static string GetInputActionAssetFilePath() { return ApplicationUtils.GetStreamingAssetsPath("Input/UltraStarPlayInputActions.inputactions"); } public static ObservableCancelablePriorityInputAction GetInputAction(string path) { if (pathToInputAction.TryGetValue(path, out ObservableCancelablePriorityInputAction observableInputAction)) { return observableInputAction; } InputAction inputAction = Instance.InputActionAsset.FindAction(path, true); observableInputAction = new ObservableCancelablePriorityInputAction(inputAction, Instance.gameObject); pathToInputAction[path] = observableInputAction; return observableInputAction; } public static List<ObservableCancelablePriorityInputAction> GetBoundInputActions() { return pathToInputAction.Values.Where(it => it.HasAnySubscribers()).ToList(); } private void OnDestroy() { pathToInputAction.Clear(); AdditionalInputActionInfos.Clear(); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CharacterSelect : MonoBehaviour { public Transform[] Characters; public Transform activeCharacter; public GameObject selectscreen; private void OnEnable() { GameTriggers.OnWaveEnd += DisplaySelectScreen; } private void OnDisable() { GameTriggers.OnWaveEnd -= DisplaySelectScreen; } //DEBUG private void Update() { if (Input.GetKeyDown(KeyCode.P)) { DisplaySelectScreen(); } } // Start is called before the first frame update void Start() { selectscreen.SetActive(false); DisablePlayerScripts(); DisplaySelectScreen(); } private void DisplaySelectScreen() { GameTriggers.OnCharSelect(); Cursor.visible = true; Cursor.lockState = CursorLockMode.None; selectscreen.SetActive(true); DisablePlayerScripts(); Time.timeScale = 0; } public void SelectPlayer(Transform character) { var scripts = character.GetComponents<MonoBehaviour>(); foreach (var s in scripts) { s.enabled = true; } activeCharacter = character; character.tag = "Player"; character.gameObject.layer = 12; GameTriggers.OnPlayerAssigned(); selectscreen.SetActive(false); Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; Time.timeScale = 1; } void DisablePlayerScripts() { foreach (var c in Characters) { var scripts = c.GetComponents<MonoBehaviour>(); foreach (var s in scripts) { s.enabled = false; } c.tag = "Untagged"; c.gameObject.layer = 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Serializer { /// <summary> /// This class helps serialize objects. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="U"></typeparam> public class Entry<T,U> { public T Key { get; set; } public U Value { get; set; } public Entry() { } public Entry(T key, U value) { Key = key; Value = value; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using TLF.Framework.Config; using TLF.Business.WSBiz; namespace TLF.Framework.ExceptionHelper { /// <summary> /// System에서 발생하는 예외를 담당하는 Form입니다. /// </summary> /// <remarks> /// 2008-12-23 최초생성 : 황준혁 /// 변경내역 /// /// </remarks> internal partial class frmException : DevExpress.XtraEditors.XtraForm { /////////////////////////////////////////////////////////////////////////////////////////////// // Constructor & Global Instance /////////////////////////////////////////////////////////////////////////////////////////////// #region :: 생성자 :: /// <summary> /// Exception Form 생성합니다. /// </summary> public frmException() { InitializeComponent(); } #endregion #region :: 전역변수 :: private const int _stdFormWidth = 540; private const int _stdFormHeight = 400; private const int _stdDetailWidth = 510; private const int _stdDetailHeight = 192; private Exception _exception; private DateTime _exceptionTime; private bool _enlarged = false; private bool _detailVisible = false; #endregion /////////////////////////////////////////////////////////////////////////////////////////////// // Properties /////////////////////////////////////////////////////////////////////////////////////////////// #region :: Exception :: 예외를 설정합니다. /// <summary> /// 예외를 설정합니다. /// </summary> [Category(AppConfig.CONTROLCATEGORY)] [Description("예외를 설정합니다."), Browsable(false)] public Exception Exception { set { _exception = value; } } #endregion /////////////////////////////////////////////////////////////////////////////////////////////// // Method(Private) /////////////////////////////////////////////////////////////////////////////////////////////// #region :: HideDetail :: Detail 구간을 숨김니다. /// <summary> /// Detail 구간을 숨김니다. /// </summary> private void HideDetail() { _detailVisible = false; txtDetail.Visible = false; btnReport.Visible = false; btnCopy.Visible = false; btnCopy.Enabled = false; btnResize.Visible = false; btnResize.Enabled = false; btnExit.Visible = false; btnExit.Enabled = false; btnDetail.Text = "자세히 >>"; Height = Height - txtDetail.Height - btnCopy.Height - 16; } #endregion #region :: ShowDetail :: Detail 구간을 보입니다. /// <summary> /// Detail 구간을 보입니다. /// </summary> private void ShowDetail() { _detailVisible = true; txtDetail.Visible = true; btnReport.Visible = true; btnCopy.Visible = true; btnCopy.Enabled = true; btnResize.Visible = true; btnResize.Enabled = true; btnExit.Visible = false; btnExit.Enabled = false; btnDetail.Text = "자세히 <<"; Height = Height + txtDetail.Height + btnCopy.Height + 16; } #endregion #region :: GetCallStack :: Exception의 Call Stack을 가져옵니다. /// <summary> /// Exception의 Call Stack을 가져옵니다. /// </summary> /// <param name="_exception"></param> /// <param name="callStack"></param> private void GetCallStack(Exception _exception, ref StringBuilder callStack) { if (_exception == null) return; callStack.AppendLine(_exception.Message); callStack.AppendLine(_exception.StackTrace); GetCallStack(_exception.InnerException, ref callStack); } #endregion private void ExceptionLogSave() { using (WsBiz wb = new WsBiz(AppConfig.DEFAULTDB)) { string query = "dbo.ExceptionLog_Save"; string[] paramList = new string[] { "@Message", "@Trace", "@Location", "@Source" }; object[] valueList = new object[] { _exception.Message, _exception.StackTrace, _exception.TargetSite.ToString(), _exception.Source }; wb.Tx_ExecuteNonQuery(AppConfig.DEFAULTDB, query, AppConfig.COMMANDSP, paramList, valueList); } } /////////////////////////////////////////// // Event Handler /////////////////////////////////////////////////////////////////////////////////////////////// #region :: Load Event :: private void frmException_Load(object sender, EventArgs e) { if (_exception == null) _exception = new Exception("표시할 예외 정보가 없습니다."); _exceptionTime = DateTime.Now; txtDesc.Text = _exception.Message.Replace("\n", Environment.NewLine); StringBuilder callStack = new StringBuilder(); GetCallStack(_exception, ref callStack); txtDetail.Text = callStack.ToString(); HideDetail(); ExceptionLogSave(); } #endregion #region : Ok Button Click Event : private void btnOK_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; } #endregion #region : Detail Button Click Event : private void btnDetail_Click(object sender, EventArgs e) { if (_detailVisible) HideDetail(); else ShowDetail(); } #endregion #region : Clipboard Button Click Event : private void btnCopy_Click(object sender, EventArgs e) { txtDetail.SelectAll(); txtDetail.Copy(); } #endregion #region : Report Button Click Event : private void btnReport_Click(object sender, EventArgs e) { //TODO: 서버에 오류를 전송할 수 있는 로직 만들기!(긴급도 100) } #endregion #region : Resize Button Click Event : private void btnResize_Click(object sender, EventArgs e) { if (_enlarged) { Width = _stdFormWidth; Height = _stdFormHeight; txtDetail.Width = _stdDetailWidth; txtDetail.Height = _stdDetailHeight; btnResize.Text = "크게"; _enlarged = false; } else { Width = _stdFormWidth + _stdFormWidth / 2; Height = _stdFormHeight + _stdFormHeight / 2; txtDetail.Width = _stdDetailWidth + _stdFormWidth / 2; txtDetail.Height = _stdDetailHeight + _stdFormHeight / 2; btnResize.Text = "작게"; _enlarged = true; } } #endregion #region : Exit Button Click Event : private void btnExit_Click(object sender, EventArgs e) { DialogResult = DialogResult.Abort; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace menghuanshuju { public partial class Form1 : Form { //set variables //hero private int hero_class = 1; private int hero_lv = 60; private double hero_basic_status = 551.0; private double weapon_num = 118.0; private double cuirass_num = 0.0; private double helmet_num = 0.0; private double trinket_num = 75.0; private double weapon_ratio = 10.0; private double cuirass_ratio = 0.0; private double helmet_ratio = 0.0; private double trinket_ratio = 5.0; private double enchantment_wp_num = 30.0; private double enchantment_cr_num = 10.0; private double enchantment_hm_num = 10.0; private double enchantment_tk_num = 20.0; private double enchantment_wp_ratio = 15.0; private double enchantment_cr_ratio = 5.0; private double enchantment_hm_ratio = 5.0; private double enchantment_tk_ratio = 10.0; private double[] gear_num_list; private double[] gear_ratio_list; private double[] enchantment_num_list; private double[] enchantment_ratio_list; private double twoset_bonus = 5.0; private double fourset_bonus = 10.0; private double fourset_bonus_ratio=0.1; private double skill_inc_num = 0.0; private double skill_inc_ratio = 0.0; private double talent_inc_num = 0.0; private double talent_inc_ratio = 0.0; private double buff_inc_num = 0.0; private double buff_inc_ratio = 0.0; private double other_inc_num = 0.0; private double other_inc_ratio = 0.0; private double status_inc_num = 0.0; private double status_num_pe = 0.0; private double status_num_nobuff = 0.0; private double status_num_buff = 0.0; //soldier private int soldier_lv = 60; private double soldier_lv1_status = 43; private double soldier_hero_correction = 20; private int soldier_basic_train_lv = 5; private int soldier_syn_train_lv = 10; private int soldier_enhance_train_lv = 15; private int soldier_core_train_lv = 20; private double soldier_basic_train_num = 10; private double soldier_syn_train_ratio = 10; private double soldier_enhance_train_num = 45; private double soldier_core_train_ratio = 40; private int soldier_tech_lv = 10; private double soldier_tech_inc_ratio = 30; private double soldier_spec_inc_num = 0; private double soldier_spec_inc_ratio = 20; private double soldier_other_inc_num = 0; private double soldier_other_inc_ratio = 20; double soldier_other_inc_num_implicit = 0.0; double soldier_other_inc_ratio_implicit = 0.0; private double SH_skill_inc_num = 0.0; private double SH_skill_inc_ratio = 10; private double SH_talent_inc_num = 0.0; private double SH_talent_inc_ratio = 0.0; private double SH_buff_inc_num = 0.0; private double SH_buff_inc_ratio = 20; private double SH_other_inc_num = 0.0; private double SH_other_inc_ratio = 0.0; private double soldier_basic_status = 0.0; private double soldier_basic_correction = 0.0; private double soldier_basic_total_status = 0.0; private double soldier_pe_status = 0.0; private double soldier_pe_correction = 0.0; private double soldier_pe_total_status = 0.0; private double soldier_total_status = 0.0; private double soldier_total_correction = 0.0; private double soldier_total_sum_status = 0.0; private double soldier_eq_inc_num = 0.0; private double soldier_eq_inc_ratio = 0.0; public Form1() { InitializeComponent(); } private void tabPage1_Click(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { } private void label26_Click(object sender, EventArgs e) { } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void label27_Click(object sender, EventArgs e) { } private void textBox4_TextChanged(object sender, EventArgs e) { } private void label31_Click(object sender, EventArgs e) { } private void label10_Click(object sender, EventArgs e) { } private double Equiment_Hdata(out double equiment_AT_data, double base_AT_data, double[] equiment_status_Num_list, double[] enchantment_status_Num_list, double[] enchantment_status_Ratio_list) { double weapon_AT = equiment_status_Num_list[0]; double chest_AT = equiment_status_Num_list[1]; double helmet_AT = equiment_status_Num_list[2]; double trinket_AT = equiment_status_Num_list[3]; double weapon_EnAT = enchantment_status_Num_list[0]; double chest_EnAT = enchantment_status_Num_list[1]; double helmet_EnAT = enchantment_status_Num_list[2]; double trinket_EnAT = enchantment_status_Num_list[3]; double weapon_FnAT = enchantment_status_Ratio_list[0]; double chest_FnAT = enchantment_status_Ratio_list[1]; double helmet_FnAT = enchantment_status_Ratio_list[2]; double trinket_FnAT = enchantment_status_Ratio_list[3]; double suit_FnAT = enchantment_status_Ratio_list[4]; double totol_equiment_AT_num = weapon_AT+chest_AT+helmet_AT+trinket_AT; double totol_enchantment_EnAT_num = weapon_EnAT + chest_EnAT + helmet_EnAT + trinket_EnAT; double totol_enchantment_FnAT_factor = weapon_FnAT + chest_FnAT + helmet_FnAT + trinket_FnAT+ suit_FnAT; double totol_enchantment_FnAT_num = base_AT_data * (totol_enchantment_FnAT_factor/100); equiment_AT_data = totol_equiment_AT_num + totol_enchantment_EnAT_num + totol_enchantment_FnAT_num; double total_base_AT = equiment_AT_data + base_AT_data; return total_base_AT; } private double Battle_Hdata(double base_AT_data, double equiment_AT_data, double[] equiment_AT_Ifactor_list,double enchantmentset_AT_Ifactor) { double total_base_AT = base_AT_data + equiment_AT_data; double weapon_AT_Ifactor = equiment_AT_Ifactor_list[0]; double chest_AT_Ifactor = equiment_AT_Ifactor_list[1]; double helmet_AT_Ifactor = equiment_AT_Ifactor_list[2]; double trinket_AT_Ifactor = equiment_AT_Ifactor_list[3]; double equiment_AT_Ifactor_num = total_base_AT * (weapon_AT_Ifactor + chest_AT_Ifactor + helmet_AT_Ifactor + trinket_AT_Ifactor)/100; double enchantment_AT_Ifactor_num = total_base_AT * (enchantmentset_AT_Ifactor)/100; double battle_AT_data = (total_base_AT + equiment_AT_Ifactor_num + enchantment_AT_Ifactor_num); return battle_AT_data; } private double Total_Hdata(double base_AT_data,double equiment_AT_data, double battle_AT_data, double talent_AT_num, double talent_AT_Ifactor, double skill_AT_num, double skill_AT_Ifactor, double buff_AT_num, double buff_AT_Ifactor, double other_buff_num, double other_buff_ratio, int hero_class) { double total_AT_data = 0.0; double total_base_AT2 = base_AT_data + equiment_AT_data; if (hero_class == 1) total_AT_data = battle_AT_data + total_base_AT2 * (skill_AT_Ifactor + buff_AT_Ifactor + talent_AT_Ifactor + other_buff_ratio)/100 + talent_AT_num + skill_AT_num + buff_AT_num + other_buff_num; return total_AT_data; } private double Battle_Sdata(double base_Soldier_AT, double command_modification, double equiment_SAT_num, double equiment_SAT_Ifactor, double soldier_Spec_num, double soldier_Spec_Ifactor, double talent_SAT_num, double talent_SAT_Ifactor, double skill_SAT_num, double skill_SAT_Ifactor) { double Battle_base_SAT = base_Soldier_AT*(100+command_modification)/100; double Battle_SAT = base_Soldier_AT + equiment_SAT_num + soldier_Spec_num + talent_SAT_num + skill_SAT_num + base_Soldier_AT * (equiment_SAT_Ifactor + soldier_Spec_Ifactor + talent_SAT_Ifactor + skill_SAT_Ifactor) / 100; return Battle_SAT; } private double Total_Sdata(double base_Soldier_AT, double command_modification, double total_static_Snum, double total_static_SIfactor, double talent_SAT_num, double talent_SAT_Ifactor, double skill_SAT_num, double skill_SAT_Ifactor, double buff_SAT_num, double buff_SAT_Ifactor, double other_SAT_num, double other_SAT_Ifactor, int hero_class) { if (hero_class == 1) { double Battle_base_SAT = base_Soldier_AT * (100 + command_modification) / 100; double total_SAT_num = base_Soldier_AT + total_static_Snum + talent_SAT_num + skill_SAT_num + buff_SAT_num + other_SAT_num + base_Soldier_AT * (total_static_SIfactor + talent_SAT_Ifactor + skill_SAT_Ifactor + buff_SAT_Ifactor + other_SAT_Ifactor) / 100; return total_SAT_num; } else return -1; } private double Soldier_Data_Formula(int soldier_hero_lv, double soldier_ini_data, double total_Ifactor_tech, double total_Inum_tech, double total_soldier_Ifactor, double total_soldier_inc_num) { double soldier_final_data = Math.Round((soldier_ini_data + (soldier_hero_lv - 1) * soldier_ini_data * 0.1) * (100 + total_soldier_Ifactor + total_Ifactor_tech) / 100 + total_soldier_inc_num + total_Inum_tech); return soldier_final_data; } private double Uniform_Num_Train(double inc_num,int train_lv) { double base_train_inc_num = inc_num * train_lv; return base_train_inc_num; } private double Uniform_Ratio_Train(double inc_ratio, int train_lv) { double base_train_inc_num = inc_ratio * train_lv; return base_train_inc_num; } private double Core_Ratio_Train(int train_lv) { int ii=0; double train_ratio = 0; double final_total_train_ratio =0; for (ii=1;ii<=train_lv;ii++) { if(ii<=4) train_ratio = 1; else if(ii>4&&ii<=17) train_ratio = 2; else if (ii>17&&ii<=19) train_ratio = 3; else train_ratio = 4; final_total_train_ratio = final_total_train_ratio + train_ratio; } return final_total_train_ratio; } private double Tech_Ratio_Train(int train_lv) { int ii = 0; double train_ratio = 0; double final_total_train_ratio = 0; for (ii = 1; ii <= train_lv; ii++) { if (ii <= 3) train_ratio = 2; else if (ii > 3 && ii <= 7) train_ratio = 3; else train_ratio = 4; final_total_train_ratio = final_total_train_ratio + train_ratio; } return final_total_train_ratio; } private void button1_Click(object sender, EventArgs e) { //input the value hero_class = System.Convert.ToInt32(HeroClass.SelectedIndex.ToString())+1; hero_lv = System.Convert.ToInt32(HeroLv.Text); hero_basic_status = System.Convert.ToDouble(HeroBasicStatus.Text); weapon_num = System.Convert.ToDouble(WeaponNum.Text); cuirass_num = System.Convert.ToDouble(CuirassNum.Text); helmet_num =System.Convert.ToDouble(HelmetNum.Text); trinket_num = System.Convert.ToDouble(TrinketNum.Text); weapon_ratio = System.Convert.ToDouble(WeaponRatio.Text); cuirass_ratio = System.Convert.ToDouble(CuirassRatio.Text); helmet_ratio =System.Convert.ToDouble(HelmetRatio.Text); trinket_ratio = System.Convert.ToDouble(TrinketRatio.Text); enchantment_wp_num = System.Convert.ToDouble(EnchantmentWpNum.Text); enchantment_cr_num = System.Convert.ToDouble(EnchantmentCrNum.Text); enchantment_hm_num = System.Convert.ToDouble(EnchantmentHmNum.Text); enchantment_tk_num = System.Convert.ToDouble(EnchantmentTkNum.Text); enchantment_wp_ratio = System.Convert.ToDouble(EnchantmentWpRatio.Text); enchantment_cr_ratio = System.Convert.ToDouble(EnchantmentCrRatio.Text); enchantment_hm_ratio = System.Convert.ToDouble(EnchantmentHmRatio.Text); enchantment_tk_ratio = System.Convert.ToDouble(EnchantmentTkRatio.Text); twoset_bonus = System.Convert.ToDouble(TwosetBonus.Text); fourset_bonus = System.Convert.ToDouble(FoursetBonus.Text); fourset_bonus_ratio = fourset_bonus / 100; skill_inc_num = System.Convert.ToDouble(SkillIncNum.Text); talent_inc_num = System.Convert.ToDouble(TalentIncNum.Text); buff_inc_num = System.Convert.ToDouble(BuffIncNum.Text); other_inc_num = System.Convert.ToDouble(OtherIncNum.Text); skill_inc_ratio = System.Convert.ToDouble(SkillIncRatio.Text); talent_inc_ratio = System.Convert.ToDouble(TalentIncRatio.Text); buff_inc_ratio = System.Convert.ToDouble(BuffIncRatio.Text); other_inc_ratio = System.Convert.ToDouble(OtherIncRatio.Text); gear_num_list = new double[4]{weapon_num,cuirass_num,helmet_num,trinket_num}; gear_ratio_list = new double[4] { weapon_ratio, cuirass_ratio, helmet_ratio, trinket_ratio}; enchantment_num_list = new double[4] { enchantment_wp_num, enchantment_cr_num, enchantment_hm_num, enchantment_tk_num }; enchantment_ratio_list = new double[5] { enchantment_wp_ratio, enchantment_cr_ratio, enchantment_hm_ratio, enchantment_tk_ratio, twoset_bonus}; } private void button2_Click(object sender, EventArgs e) { status_num_pe = Equiment_Hdata(out status_inc_num, hero_basic_status, gear_num_list, enchantment_num_list, enchantment_ratio_list); status_num_nobuff = Battle_Hdata(hero_basic_status, status_inc_num, gear_ratio_list, fourset_bonus); status_num_buff = Total_Hdata(hero_basic_status, status_inc_num, status_num_nobuff, talent_inc_num, talent_inc_ratio, skill_inc_num, skill_inc_ratio, buff_inc_num, buff_inc_ratio, other_inc_num, other_inc_ratio, hero_class); HeroStatusIncNum.Text = status_inc_num.ToString(); HeroStatusIncNumPe.Text = status_num_pe.ToString(); HeroStatusNumNobuff.Text = status_num_nobuff.ToString(); HeroStatusNumBuff.Text = status_num_buff.ToString(); } private void label33_Click(object sender, EventArgs e) { } private void Save1_Click(object sender, EventArgs e) { HeroStatusIncNum11.Text = HeroStatusIncNum.Text; HeroStatusIncNumPe1.Text = HeroStatusIncNumPe.Text; HeroStatusNumNobuff1.Text = HeroStatusNumNobuff.Text; HeroStatusNumBuff1.Text = HeroStatusNumBuff.Text; HeroName1.Text = HeroName.Text; } private void Save2_Click(object sender, EventArgs e) { HeroStatusIncNum2.Text = HeroStatusIncNum.Text; HeroStatusIncNumPe2.Text = HeroStatusIncNumPe.Text; HeroStatusNumNobuff2.Text = HeroStatusNumNobuff.Text; HeroStatusNumBuff2.Text = HeroStatusNumBuff.Text; HeroName2.Text = HeroName.Text; } private void Save3_Click(object sender, EventArgs e) { HeroStatusIncNum3.Text = HeroStatusIncNum.Text; HeroStatusIncNumPe3.Text = HeroStatusIncNumPe.Text; HeroStatusNumNobuff3.Text = HeroStatusNumNobuff.Text; HeroStatusNumBuff3.Text = HeroStatusNumBuff.Text; HeroName3.Text = HeroName.Text; } private void label53_Click(object sender, EventArgs e) { } private void textBox3_TextChanged(object sender, EventArgs e) { } private void textBox24_TextChanged(object sender, EventArgs e) { } private void label54_Click(object sender, EventArgs e) { } private void label83_Click(object sender, EventArgs e) { } private void SoldireConfirm_Click(object sender, EventArgs e) { if (InheritHeroStatus.Checked == true) { SH_buff_inc_num = buff_inc_num; SH_buff_inc_ratio = buff_inc_ratio; SH_other_inc_num = other_inc_num; SH_other_inc_ratio = other_inc_ratio; SH_skill_inc_num = skill_inc_num; SH_skill_inc_ratio = skill_inc_ratio; SH_talent_inc_num = talent_inc_num; SH_talent_inc_ratio = talent_inc_ratio; soldier_lv = hero_lv; SoldierHeroSkillIncNum.Text = SH_skill_inc_num.ToString(); SoldierHeroSkillIncRatio.Text = SH_skill_inc_ratio.ToString(); SoldierHeroTalentIncNum.Text = SH_talent_inc_num.ToString(); SoldierHeroTalentIncRatio.Text = SH_talent_inc_ratio.ToString(); SoldierHeroBuffIncNum.Text = SH_buff_inc_num.ToString(); SoldierHeroBuffIncRatio.Text = SH_buff_inc_ratio.ToString(); SoldierHeroOtherIncNum.Text = SH_other_inc_num.ToString(); SoldierHeroOtherIncRatio.Text = SH_other_inc_ratio.ToString(); SoldierLv.Text = soldier_lv.ToString(); } else { SH_buff_inc_num = System.Convert.ToDouble(SoldierHeroBuffIncNum.Text); SH_buff_inc_ratio = System.Convert.ToDouble(SoldierHeroBuffIncRatio.Text); SH_other_inc_num = System.Convert.ToDouble(SoldierHeroOtherIncNum.Text); SH_other_inc_ratio = System.Convert.ToDouble(SoldierHeroOtherIncRatio.Text); SH_skill_inc_num = System.Convert.ToDouble(SoldierHeroSkillIncNum.Text); SH_skill_inc_ratio = System.Convert.ToDouble(SoldierHeroSkillIncRatio.Text); SH_talent_inc_num = System.Convert.ToDouble(SoldierHeroTalentIncNum.Text); SH_talent_inc_ratio = System.Convert.ToDouble(SoldierHeroTalentIncRatio.Text); soldier_lv = System.Convert.ToInt32(SoldierLv.Text); } soldier_lv1_status = System.Convert.ToDouble(Lv1SoldierStatus.Text); soldier_hero_correction = System.Convert.ToDouble(SoldierHeroCorrection.Text); if (UseTrainLv.Checked == true) { soldier_basic_train_lv = System.Convert.ToInt32(SoldierBasicTrainLv.Text); soldier_syn_train_lv = System.Convert.ToInt32(SoldierSynTrainLv.Text); soldier_enhance_train_lv = System.Convert.ToInt32(SoldierEnhanceTrainLv.Text); soldier_core_train_lv = System.Convert.ToInt32(SoldierCoreTrainLv.Text); soldier_tech_lv = System.Convert.ToInt32(SoldierTechLv.Text); soldier_basic_train_num = Uniform_Num_Train(2, soldier_basic_train_lv); soldier_syn_train_ratio = Uniform_Ratio_Train(1, soldier_syn_train_lv); soldier_enhance_train_num = Uniform_Num_Train(3, soldier_enhance_train_lv); soldier_core_train_ratio = Core_Ratio_Train(soldier_core_train_lv); soldier_tech_inc_ratio = Tech_Ratio_Train(soldier_tech_lv); SoldierBasicTrainNum.Text = soldier_basic_train_num.ToString(); SoldierSynTrainRatio.Text = soldier_syn_train_ratio.ToString(); SoldierEnhanceTrainNum.Text = soldier_enhance_train_num.ToString(); SoldierCoreTrainRatio.Text = soldier_core_train_ratio.ToString(); SoldierTechIncRatio.Text = soldier_tech_inc_ratio.ToString(); } else { soldier_basic_train_num = System.Convert.ToDouble(SoldierBasicTrainNum.Text); soldier_syn_train_ratio = System.Convert.ToDouble(SoldierSynTrainRatio.Text); soldier_enhance_train_num = System.Convert.ToDouble(SoldierEnhanceTrainNum.Text); soldier_core_train_ratio = System.Convert.ToDouble(SoldierCoreTrainRatio.Text); soldier_tech_inc_ratio = System.Convert.ToDouble(SoldierTechIncRatio.Text); } soldier_spec_inc_ratio = System.Convert.ToDouble(SoldierSpecIncRatio.Text); soldier_other_inc_ratio = System.Convert.ToDouble(SoldierOtherIncRatio.Text); soldier_other_inc_ratio_implicit = System.Convert.ToDouble(SoldierOtherIncRatioImplicit.Text); ; soldier_spec_inc_num = System.Convert.ToDouble(SoldierSpecIncNum.Text); soldier_other_inc_num = System.Convert.ToDouble(SoldierOtherIncNum.Text); soldier_other_inc_num_implicit = System.Convert.ToDouble(SoldierOtherIncNumImplicit.Text); } private void InheritHeroStatus_CheckedChanged(object sender, EventArgs e) { if (InheritHeroStatus.Checked == true) { groupBox5.Enabled = false; } else { groupBox5.Enabled = true; } } private void UseTrainLv_CheckedChanged(object sender, EventArgs e) { if (UseTrainLv.Checked == true) { SoldierBasicTrainNum.Enabled = false; SoldierSynTrainRatio.Enabled = false; SoldierEnhanceTrainNum.Enabled = false; SoldierCoreTrainRatio.Enabled = false; SoldierBasicTrainNum.Enabled = false; SoldierTechIncRatio.Enabled = false; SoldierBasicTrainLv.Enabled = true; SoldierSynTrainLv.Enabled = true; SoldierEnhanceTrainLv.Enabled = true; SoldierCoreTrainLv.Enabled = true; SoldierBasicTrainLv.Enabled = true; SoldierTechLv.Enabled = true; } else { SoldierBasicTrainNum.Enabled = true; SoldierSynTrainRatio.Enabled = true; SoldierEnhanceTrainNum.Enabled = true; SoldierCoreTrainRatio.Enabled = true; SoldierBasicTrainNum.Enabled = true; SoldierTechIncRatio.Enabled = true; SoldierBasicTrainLv.Enabled = false; SoldierSynTrainLv.Enabled = false; SoldierEnhanceTrainLv.Enabled = false; SoldierCoreTrainLv.Enabled = false; SoldierBasicTrainLv.Enabled = false; SoldierTechLv.Enabled = false; } } private void SoldierCalculation_Click(object sender, EventArgs e) { double total_inc_ratio_train=0.0;double total_inc_num_train=0.0; double total_inc_ratio_soldiertech=0.0;double total_inc_num_soldiertech=0.0; double total_inc_num_soldier =0.0; double total_inc_ratio_soldier = 0.0;double total_soldier_total_status = 0.0; double soldier_explicit_inc_num = 0.0; double soldier_explicit_inc_ratio = 0.0; total_inc_ratio_train = soldier_syn_train_ratio+soldier_core_train_ratio; total_inc_num_train = soldier_basic_train_num + soldier_enhance_train_num; total_inc_ratio_soldiertech = soldier_tech_inc_ratio; soldier_explicit_inc_num = soldier_spec_inc_num + soldier_eq_inc_num + soldier_other_inc_num; soldier_explicit_inc_ratio = soldier_spec_inc_ratio + soldier_eq_inc_ratio + soldier_other_inc_ratio; total_inc_num_soldier = soldier_spec_inc_num + soldier_eq_inc_num + soldier_other_inc_num + soldier_other_inc_num_implicit; total_inc_ratio_soldier = soldier_spec_inc_ratio + soldier_eq_inc_ratio + soldier_other_inc_ratio + soldier_other_inc_ratio_implicit; soldier_basic_status = Soldier_Data_Formula(soldier_lv, soldier_lv1_status, total_inc_ratio_train, total_inc_num_train, total_inc_ratio_soldiertech, total_inc_num_soldiertech); soldier_basic_correction = soldier_basic_status * soldier_hero_correction / 100; soldier_basic_total_status = soldier_basic_status + soldier_basic_correction; SoldierBasicStatus.Text = soldier_basic_status.ToString(); SoldierBasicCorrection.Text = soldier_basic_correction.ToString(); SoldierBasicTotalStatus.Text = soldier_basic_total_status.ToString(); soldier_pe_status = Battle_Sdata(soldier_basic_status, soldier_hero_correction, soldier_eq_inc_num, soldier_eq_inc_ratio, soldier_explicit_inc_num, soldier_explicit_inc_ratio, SH_talent_inc_num, SH_talent_inc_ratio, SH_skill_inc_num, SH_skill_inc_ratio); soldier_pe_correction = soldier_pe_status * soldier_hero_correction / 100; soldier_pe_total_status = soldier_pe_status + soldier_pe_correction; SoldierPeStatus.Text = soldier_pe_status.ToString(); SoldierPeCorrection.Text = soldier_pe_correction.ToString(); SoldierPeTotalStatus.Text = soldier_pe_total_status.ToString(); soldier_total_status = Total_Sdata(soldier_basic_status, soldier_hero_correction, total_inc_num_soldier, total_inc_ratio_soldier, SH_talent_inc_num, SH_talent_inc_ratio, SH_skill_inc_num, SH_skill_inc_ratio, SH_buff_inc_num, SH_buff_inc_ratio, SH_other_inc_num, SH_other_inc_ratio, hero_class); soldier_total_correction = soldier_total_status * soldier_hero_correction / 100; total_soldier_total_status = soldier_total_status + soldier_total_correction; SoldierBattleStatus.Text = soldier_total_status.ToString(); SoldierBattleCorrection.Text = soldier_total_correction.ToString(); SoldierBattleTotalStatus.Text = total_soldier_total_status.ToString(); //private double soldier_basic_status = 0.0; private double soldier_basic_correction = 0.0; private double soldier_basic_total_status = 0.0; // private double soldier_pe_status = 0.0; private double soldier_pe_correction = 0.0; private double soldier_pe_total_status = 0.0; // private double soldier_total_status = 0.0; private double soldier_total_correction = 0.0; private double soldier_total_sum_status = 0.0; } private void label118_Click(object sender, EventArgs e) { } private void SoldierSave1_Click(object sender, EventArgs e) { SoldierBasicStatus1.Text = SoldierBasicStatus.Text; SoldierBasicCorrection1.Text = SoldierBasicCorrection.Text; SoldierBasicTotalStatus1.Text = SoldierBasicTotalStatus.Text; SoldierPeStatus1.Text = SoldierPeStatus.Text; SoldierPeCorrection1.Text = SoldierPeCorrection.Text; SoldierPeTotalStatus1.Text = SoldierPeTotalStatus.Text; SoldierBattleStatus1.Text = SoldierBattleStatus.Text; SoldierBattleCorrection1.Text = SoldierBattleCorrection.Text; SoldierBattleTotalStatus1.Text = SoldierBattleTotalStatus.Text; SoldierName1.Text = SoldierName.Text; SoldierHeroName1.Text = HeroName.Text; SoldierLv1.Text = SoldierLv.Text; } private void SoldierSave2_Click(object sender, EventArgs e) { SoldierBasicStatus2.Text = SoldierBasicStatus.Text; SoldierBasicCorrection2.Text = SoldierBasicCorrection.Text; SoldierBasicTotalStatus2.Text = SoldierBasicTotalStatus.Text; SoldierPeStatus2.Text = SoldierPeStatus.Text; SoldierPeCorrection2.Text = SoldierPeCorrection.Text; SoldierPeTotalStatus2.Text = SoldierPeTotalStatus.Text; SoldierBattleStatus2.Text = SoldierBattleStatus.Text; SoldierBattleCorrection2.Text = SoldierBattleCorrection.Text; SoldierBattleTotalStatus2.Text = SoldierBattleTotalStatus.Text; SoldierName2.Text = SoldierName.Text; SoldierHeroName2.Text = HeroName.Text; SoldierLv2.Text = SoldierLv.Text; } private void SoldierSave3_Click(object sender, EventArgs e) { SoldierBasicStatus3.Text = SoldierBasicStatus.Text; SoldierBasicCorrection3.Text = SoldierBasicCorrection.Text; SoldierBasicTotalStatus3.Text = SoldierBasicTotalStatus.Text; SoldierPeStatus3.Text = SoldierPeStatus.Text; SoldierPeCorrection3.Text = SoldierPeCorrection.Text; SoldierPeTotalStatus3.Text = SoldierPeTotalStatus.Text; SoldierBattleStatus3.Text = SoldierBattleStatus.Text; SoldierBattleCorrection3.Text = SoldierBattleCorrection.Text; SoldierBattleTotalStatus3.Text = SoldierBattleTotalStatus.Text; SoldierName3.Text = SoldierName.Text; SoldierHeroName3.Text = HeroName.Text; SoldierLv3.Text = SoldierLv.Text; } } }
using System; using System.Collections.Generic; using System.Text; using Soko.Domain; using Soko.Report; namespace Bilten.Dao { /// <summary> /// Business DAO operations related to the <see cref="Domain.DolazakNaTrening"/> entity. /// </summary> public interface DolazakNaTreningDAO : GenericDAO<DolazakNaTrening, int> { IList<DolazakNaTrening> getDolazakNaTrening(DateTime from, DateTime to); IList<DolazakNaTrening> getDolazakNaTrening(Clan c, DateTime from, DateTime to); List<object[]> getEvidencijaTreningaReportItems(DateTime from, DateTime to, List<Grupa> grupe); List<ReportGrupa> getEvidencijaTreningaReportGrupe(DateTime from, DateTime to, List<Grupa> grupe); List<object[]> getEvidencijaTreningaReportItems(int clanId, DateTime from, DateTime to, List<Grupa> grupe); List<object[]> getDolazakNaTreningMesecniReportItems(DateTime from, DateTime to, bool samoNedostajuceUplate); List<object[]> getNeplacenDolazakNaTrening(DateTime from, DateTime to); void deleteDolasci(DateTime from, DateTime to); void insertDolazak(DateTime datum_vreme_dolaska, int clan_id, int grupa_id); } }
using CryptoInvestor.Core.Domain; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace CryptoInvestor.Core.Repositories { public interface ICoinRepository : IRepository { Task AddAsync(Coin coin); Task<Coin> GetAsync(Guid id); Task<Coin> GetAsync(string symbol); Task<IEnumerable<Coin>> BrowseAsync(); Task UpdateAsync(Coin coin); Task DeleteAsync(Guid id); } }
using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; namespace Swiddler.Security { /// <summary> /// The SSL extension information. /// </summary> public class SslExtension { /// <summary> /// Extension type /// </summary> [XmlAttribute] public int Type { get; set; } /// <summary> /// Gets the name. /// </summary> /// <value> /// The name. /// </value> [XmlAttribute] public string Name { get; set; } /// <summary> /// Gets the data. /// </summary> /// <value> /// The data. /// </value> [XmlIgnore] public byte[] RawData { get; set; } [XmlElement(nameof(RawData))] public string RawDataEncoded { get => Convert.ToBase64String(RawData); set => RawData = Convert.FromBase64String(value); } /// <summary> /// Gets the position. /// </summary> /// <value> /// The position. /// </value> [XmlAttribute] public int Position { get; } /// <summary> /// Initializes a new instance of the <see cref="SslExtension"/> class. /// </summary> /// <param name="type">The value.</param> /// <param name="name">The name.</param> /// <param name="data">The data.</param> /// <param name="position">The position.</param> public SslExtension(int type, byte[] data, int position) { Name = GetExtensionName(type); Type = type; RawData = data; Position = position; } public SslExtension() {} public object GetExtensionData() { // https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml var data = RawData; switch (Type) { case 0: return ParseServerName(data); case 5: if (data.Length == 5 && data[0] == 1 && data[1] == 0 && data[2] == 0 && data[3] == 0 && data[4] == 0) return "OCSP - Implicit Responder"; return data; case 10: return ParseSupportedGroup(data); case 11: return ParseEcPointFormats(data); case 13: return ParseSignatureAlgorithms(data); case 16: return ParseApplicationLayerProtocolNegotiation(data); } return data; } private static string GetExtensionName(int type) { //https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml switch (type) { case 0: return "server_name"; case 1: return "max_fragment_length"; case 2: return "client_certificate_url"; case 3: return "trusted_ca_keys"; case 4: return "truncated_hmac"; case 5: return "status_request"; case 6: return "user_mapping"; case 7: return "client_authz"; case 8: return "server_authz"; case 9: return "cert_type"; case 10: return "supported_groups"; // renamed from "elliptic_curves" (RFC 7919 / TLS 1.3) case 11: return "ec_point_formats"; case 12: return "srp"; case 13: return "signature_algorithms"; case 14: return "use_srtp"; case 15: return "heartbeat"; case 16: return "ALPN"; // application_layer_protocol_negotiation case 17: return "status_request_v2"; case 18: return "signed_certificate_timestamp"; case 19: return "client_certificate_type"; case 20: return "server_certificate_type"; case 21: return "padding"; case 22: return "encrypt_then_mac"; case 23: return "extended_master_secret"; case 24: return "token_binding"; // TEMPORARY - registered 2016-02-04, extension registered 2017-01-12, expires 2018-02-04 case 25: return "cached_info"; case 26: return "quic_transports_parameters"; // Not yet assigned by IANA (QUIC-TLS Draft04) case 27: return "compress_certificate"; case 28: return "record_size_limit"; case 29: return "pwd_protect"; case 30: return "pwd_clear"; case 31: return "password_salt"; case 32: return "ticket_pinning"; case 33: return "tls_cert_with_extern_psk"; case 34: return "delegated_credentials"; case 35: return "session_ticket"; // TLS 1.3 draft: https://tools.ietf.org/html/draft-ietf-tls-tls13 case 41: return "pre_shared_key"; case 42: return "early_data"; case 43: return "supported_versions"; case 44: return "cookie"; case 45: return "psk_key_exchange_modes"; case 46: return "ticket_early_data_info"; case 47: return "certificate_authorities"; case 48: return "oid_filters"; case 49: return "post_handshake_auth"; case 51: return "key_share"; case 52: return "transparency_info"; case 55: return "external_id_hash"; case 56: return "external_session_id"; case 2570: // 0a0a case 6682: // 1a1a case 10794: // 2a2a case 14906: // 3a3a case 19018: // 4a4a case 23130: // 5a5a case 27242: // 6a6a case 31354: // 7a7a case 35466: // 8a8a case 39578: // 9a9a case 43690: // aaaa case 47802: // baba case 51914: // caca case 56026: // dada case 60138: // eaea case 64250: // fafa return "Reserved (GREASE)"; case 13172: return "next_protocol_negotiation"; case 30031: return "channel_id_old"; // Google case 30032: return "channel_id"; // Google case 35655: return "draft-agl-tls-padding"; case 65281: return "renegotiation_info"; case 65282: return "Draft version of TLS 1.3"; // for experimentation only https://www.ietf.org/mail-archive/web/tls/current/msg20853.html default: return $"unknown_{type:x2}"; } } private static string[] ParseServerName(byte[] data) { int index = 2; List<string> list = new List<string>(); while (index < data.Length) { int nameType = data[index]; int count = (data[index + 1] << 8) + data[index + 2]; if (nameType == 0) list.Add(Encoding.ASCII.GetString(data, index + 3, count)); index += 3 + count; } return list.ToArray(); } private static string[] ParseSupportedGroup(byte[] data) { //https://datatracker.ietf.org/doc/draft-ietf-tls-rfc4492bis/?include_text=1 List<string> list = new List<string>(); if (data.Length < 2) return null; int i = 2; while (i < data.Length - 1) { int namedCurve = (data[i] << 8) + data[i + 1]; switch (namedCurve) { case 1: list.Add("sect163k1 [0x1]"); //deprecated break; case 2: list.Add("sect163r1 [0x2]"); //deprecated break; case 3: list.Add("sect163r2 [0x3]"); //deprecated break; case 4: list.Add("sect193r1 [0x4]"); //deprecated break; case 5: list.Add("sect193r2 [0x5]"); //deprecated break; case 6: list.Add("sect233k1 [0x6]"); //deprecated break; case 7: list.Add("sect233r1 [0x7]"); //deprecated break; case 8: list.Add("sect239k1 [0x8]"); //deprecated break; case 9: list.Add("sect283k1 [0x9]"); //deprecated break; case 10: list.Add("sect283r1 [0xA]"); //deprecated break; case 11: list.Add("sect409k1 [0xB]"); //deprecated break; case 12: list.Add("sect409r1 [0xC]"); //deprecated break; case 13: list.Add("sect571k1 [0xD]"); //deprecated break; case 14: list.Add("sect571r1 [0xE]"); //deprecated break; case 15: list.Add("secp160k1 [0xF]"); //deprecated break; case 16: list.Add("secp160r1 [0x10]"); //deprecated break; case 17: list.Add("secp160r2 [0x11]"); //deprecated break; case 18: list.Add("secp192k1 [0x12]"); //deprecated break; case 19: list.Add("secp192r1 [0x13]"); //deprecated break; case 20: list.Add("secp224k1 [0x14]"); //deprecated break; case 21: list.Add("secp224r1 [0x15]"); //deprecated break; case 22: list.Add("secp256k1 [0x16]"); //deprecated break; case 23: list.Add("secp256r1 [0x17]"); break; case 24: list.Add("secp384r1 [0x18]"); break; case 25: list.Add("secp521r1 [0x19]"); break; case 26: list.Add("brainpoolP256r1 [0x1A]"); break; case 27: list.Add("brainpoolP384r1 [0x1B]"); break; case 28: list.Add("brainpoolP512r1 [0x1C]"); break; case 29: list.Add("x25519 [0x1D]"); break; case 30: list.Add("x448 [0x1E]"); break; case 256: list.Add("ffdhe2048 [0x0100]"); break; case 257: list.Add("ffdhe3072 [0x0101]"); break; case 258: list.Add("ffdhe4096 [0x0102]"); break; case 259: list.Add("ffdhe6144 [0x0103]"); break; case 260: list.Add("ffdhe8192 [0x0104]"); break; case 65281: list.Add("arbitrary_explicit_prime_curves [0xFF01]"); //deprecated break; case 65282: list.Add("arbitrary_explicit_char2_curves [0xFF02]"); //deprecated break; default: list.Add($"unknown [0x{namedCurve:X4}]"); break; } i += 2; } return list.ToArray(); } private static string[] ParseEcPointFormats(byte[] data) { List<string> list = new List<string>(); if (data.Length < 1) return null; int i = 1; while (i < data.Length) { switch (data[i]) { case 0: list.Add("uncompressed [0x0]"); break; case 1: list.Add("ansiX962_compressed_prime [0x1]"); break; case 2: list.Add("ansiX962_compressed_char2 [0x2]"); break; default: list.Add($"unknown [0x{data[i]:X2}]"); break; } i += 2; } return list.ToArray(); } private static string[] ParseSignatureAlgorithms(byte[] data) { // https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml int num = (data[0] << 8) + data[1]; List<string> list = new List<string>(); int index = 2; while (index < num + 2) { string s1, s2; switch (data[index]) { case 0: s1 = "none"; break; case 1: s1 = "md5"; break; case 2: s1 = "sha1"; break; case 3: s1 = "sha224"; break; case 4: s1 = "sha256"; break; case 5: s1 = "sha384"; break; case 6: s1 = "sha512"; break; case 8: s1 = "Intrinsic"; break; default: s1 = string.Format("Unknown[0x{0:X2}]", data[index]); break; } switch (data[index + 1]) { case 0: s2 = "anonymous"; break; case 1: s2 = "rsa"; break; case 2: s2 = "dsa"; break; case 3: s2 = "ecdsa"; break; case 7: s2 = "ed25519"; break; case 8: s2 = "ed448"; break; default: s2 = string.Format("Unknown[0x{0:X2}]", data[index + 1]); break; } list.Add($"{s1}_{s2}"); index += 2; } return list.ToArray(); } private static string[] ParseApplicationLayerProtocolNegotiation(byte[] data) { List<string> stringList = new List<string>(); int index = 2; while (index < data.Length) { int count = data[index]; stringList.Add(Encoding.ASCII.GetString(data, index + 1, count)); index += 1 + count; } return stringList.ToArray(); } public override string ToString() { var obj = GetExtensionData(); if (obj is string[] strArr) return string.Join(", ", strArr); else return obj?.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoreComponents { public interface IResult<T> { T Result { get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class ResultScene : MonoBehaviour { public class Options { public List<ResultData> Results { get; private set; } public Options(List<ResultData> results) { Results = results; } } Options options = null; List<ResultData> resultDatas = null; [SerializeField] ResultRankListView resultRankListView; private void Awake() { if(SceneLoader.CurrentOptions == null) SceneLoader.CurrentOptions = new Options(ResultData.CreateTestModels()); } // Use this for initialization void Start() { options = SceneLoader.CurrentOptions as Options; if (options == null) { Debug.LogError("Score result is null"); } Debug.Log(options.Results.Count); resultDatas = options.Results.OrderBy(value => value.Rank).ToList(); ; resultRankListView.SetResultRankItem(resultDatas); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Return)) { AudioPlayer.PlaySE(SEType.Attack1); SceneLoader.LoadSceneAsync("Title"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace BackPropagation { class MedialLayer { /// <summary> /// Gets or sets the weights between the inputs of the layer and the neurons. /// </summary> public double[,] Weights { get { return weights; } set { weights = value; } } private double[,] weights; /// <summary> /// Calculates the output of the layer with the given inputs. /// </summary> /// <param name="inputs">The inputs to the layer</param> /// <returns>The outputs of the neurons</returns> public double[] GetOutput(double[] inputs) { Debug.Assert(inputs.Length == weights.GetLength(0), "Input length does not match weight lengths."); double[] outputs = new double[weights.GetLength(1)]; for (int neuron = 0; neuron < outputs.Length; neuron++) { double sum = 0; for (int input = 0; input < inputs.Length; input++) { sum += inputs[input] * weights[input, neuron]; } outputs[neuron] = logistic(sum); } return outputs; } /// <summary> /// Returns the value of a sigmoid function, specifically the logistic function /// with the given input x. /// </summary> /// <param name="x">The value for x</param> /// <returns>The value of logistic(x)</returns> private double logistic(double x) { return 1.0 / (1 + Math.Exp(-x)); } } /// <summary> /// Simulates a simple feed forward network with one hidden (medial) layer /// containing a variable number of neurons, as well as a variable number /// of input and output neurons. The network can also calculate the output /// given its inputs. /// </summary> class Network { /// <summary> /// Gets the medial layers in the network. /// </summary> public MedialLayer[] Layers { get { return layers; } } private MedialLayer[] layers; /// <summary> /// Gets the output of each medial neuron. /// </summary> public double[][] Medout { get { return medout; } } private double[][] medout; /// <summary> /// Gets or sets the weights leading to the output layer. /// </summary> public double[,] SynOut { get { return synOut; } set { synOut = value; } } private double[,] synOut; /// <summary> /// Gets the number of neurons in the medial layer. /// </summary> public int MedialNeurons { get { return neuronCount; } } private readonly int neuronCount; /// <summary> /// Gets the number of inputs to the network. /// </summary> public int Inputs { get { return inputCount; } } private readonly int inputCount; /// <summary> /// Gets the number of outputs of the network. /// </summary> public int Outputs { get { return outputCount; } } private readonly int outputCount; /// <summary> /// Creates a new feed forward network with the given number of inputs, /// outputs and medial neurons in the network. /// </summary> /// <param name="inputs">The number of inputs</param> /// <param name="outputs">The number of outputs</param> /// <param name="neurons">The number of medial neurons</param> public Network(int inputs, int outputs, int neurons, int layers) { Random random = new Random(); this.medout = new double[layers][]; this.neuronCount = neurons; this.inputCount = inputs; this.outputCount = outputs; this.synOut = InitialiseSynArray(neurons, outputs, random); this.layers = new MedialLayer[layers]; for (int i = 0; i < layers; i++) { int layerInputs = neurons; if (i == 0) { layerInputs = inputs; } this.layers[i] = new MedialLayer(); this.layers[i].Weights = InitialiseSynArray(layerInputs, neurons, random); } } /// <summary> /// Calculates the output of the network with the given inputs. /// Pre: The length of the input array matches the number of /// input neurons. /// </summary> /// <param name="inputs">The inputs to the network</param> /// <returns>The outputs of the network</returns> public double[] GetOutput(double[] inputs) { Debug.Assert(inputs.Length == inputCount, "Incorrect number of inputs."); // Calculate the values of the medial neurons. for (int layer = 0; layer < layers.Length; layer++) { medout[layer] = layers[layer].GetOutput(inputs); inputs = medout[layer]; } // Calculate the values of the output neurons. double[] outputs = new double[outputCount]; for (int output = 0; output < outputCount; output++) { outputs[output] = 0; for (int neuron = 0; neuron < neuronCount; neuron++) { outputs[output] += inputs[neuron] * synOut[neuron, output]; } } return outputs; } /// <summary> /// Helper method to set the synaptic weights between two neurons to a small /// random value: [0, 0.1). /// </summary> /// <param name="a">The first dimension of the weights array to return</param> /// <param name="b">The second dimension of the weights array to return</param> /// <param name="random">The random number generator to use</param> /// <returns>A table of synaptic weights</returns> private double[,] InitialiseSynArray(int a, int b, Random random) { double[,] result = new double[a, b]; for (int y = 0; y < b; y++) { for (int x = 0; x < a; x++) { result[x, y] = random.NextDouble() - 0.5; } } return result; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SFXManager : MonoBehaviour { public AudioSource hit, beeDead, chickenDead, musicWin, musicDead, playerHitted, jump, steps, takeItem, _throw; public enum SFXType { HIT, BEEDEAD, CHICKENDEAD, MUSICWIN, MUSICDEAD, PLAYERHITTED, JUMP, STEPS, TAKEITEM, THROW}; private static SFXManager sharedInstance = null; public static SFXManager SharedInstance { get{ return sharedInstance; } } private void Awake() { if (sharedInstance != null && sharedInstance != this) { Destroy(gameObject); } else { sharedInstance = this; DontDestroyOnLoad(this.gameObject); } } //Los siguientes 2 métodos no los hago genéricos para agilizar la prueba. /// <summary> /// Devuelve true o false en funicón de si se están reproduciendo o no los pasos. /// </summary> /// <returns></returns> public bool IsPlayingSteps() { return steps.isPlaying; } /// <summary> /// Se para el sonido de los pasos /// </summary> public void StopSteps() { if (steps.isPlaying) { steps.Stop(); } } /// <summary> /// Según el type seleccionado se reproduce un sonido u otro /// </summary> /// <param name="type">Elemento del enumerado</param> public void PlaySFX(SFXType type) { switch (type) { case SFXType.BEEDEAD: beeDead.Play(); break; case SFXType.CHICKENDEAD: chickenDead.Play(); break; case SFXType.HIT: hit.Play(); break; case SFXType.MUSICWIN: musicWin.Play(); break; case SFXType.MUSICDEAD: musicDead.Play(); break; case SFXType.PLAYERHITTED: playerHitted.Play(); break; case SFXType.JUMP: jump.Play(); break; case SFXType.STEPS: steps.Play(); break; case SFXType.TAKEITEM: takeItem.Play(); break; case SFXType.THROW: _throw.Play(); break; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GiftAidCalculator.Tests { public class LotsOfDecimalPlacesStub : ITaxStore { public void Update(decimal taxRateArg) { throw new NotImplementedException(); } public decimal Read() { return 30; } } }
namespace OC.Security.Bruteforce { public class Throttler { const LOGIN_ACTION = 'login'; /** @var IDBConnection */ private $db; /** @var ITimeFactory */ private $timeFactory; /** @var ILogger */ private $logger; /** @var IConfig */ private $config; /** * @param IDBConnection $db * @param ITimeFactory $timeFactory * @param ILogger $logger * @param IConfig $config */ public function __construct(IDBConnection $db, ITimeFactory $timeFactory, ILogger $logger, IConfig $config) { $this->db = $db; $this->timeFactory = $timeFactory; $this->logger = $logger; $this->config = $config; } /** * Convert a number of seconds into the appropriate DateInterval * * @param int $expire * @return \DateInterval */ private function getCutoff($expire) { $d1 = new \DateTime(); $d2 = clone $d1; $d2->sub(new \DateInterval('PT' . $expire . 'S')); return $d2->diff($d1); } /** * Register a failed attempt to bruteforce a security control * * @param string $action * @param string $ip * @param array $metadata Optional metadata logged to the database * @suppress SqlInjectionChecker */ public function registerAttempt($action, $ip, array $metadata = []) { // No need to log if the bruteforce protection is disabled if($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) { return; } $ipAddress = new IpAddress($ip); $values = [ 'action' => $action, 'occurred' => $this->timeFactory->getTime(), 'ip' => (string)$ipAddress, 'subnet' => $ipAddress->getSubnet(), 'metadata' => json_encode($metadata), ]; $this->logger->notice( sprintf( 'Bruteforce attempt from "%s" detected for action "%s".', $ip, $action ), [ 'app' => 'core', ] ); $qb = $this->db->getQueryBuilder(); $qb->insert('bruteforce_attempts'); foreach($values as $column => $value) { $qb->setValue($column, $qb->createNamedParameter($value)); } $qb->execute(); } /** * Check if the IP is whitelisted * * @param string $ip * @return bool */ private function isIPWhitelisted($ip) { if($this->config->getSystemValue('auth.bruteforce.protection.enabled', true) === false) { return true; } $keys = $this->config->getAppKeys('bruteForce'); $keys = array_filter($keys, function($key) { $regex = '/^whitelist_/S'; return preg_match($regex, $key) === 1; }); if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { $type = 4; } else if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $type = 6; } else { return false; } $ip = inet_pton($ip); foreach ($keys as $key) { $cidr = $this->config->getAppValue('bruteForce', $key, null); $cx = explode('/', $cidr); $addr = $cx[0]; $mask = (int)$cx[1]; // Do not compare ipv4 to ipv6 if (($type === 4 && !filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) || ($type === 6 && !filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))) { continue; } $addr = inet_pton($addr); $valid = true; for($i = 0; $i < $mask; $i++) { $part = ord($addr[(int)($i/8)]); $orig = ord($ip[(int)($i/8)]); $bitmask = 1 << (7 - ($i % 8)); $part = $part & $bitmask; $orig = $orig & $bitmask; if ($part !== $orig) { $valid = false; break; } } if ($valid === true) { return true; } } return false; } /** * Get the throttling delay (in milliseconds) * * @param string $ip * @param string $action optionally filter by action * @return int */ public int getDelay(string ip, string action = "") { $ipAddress = new IpAddress($ip); if ($this->isIPWhitelisted((string)$ipAddress)) { return 0; } $cutoffTime = (new \DateTime()) ->sub($this->getCutoff(43200)) ->getTimestamp(); $qb = $this->db->getQueryBuilder(); $qb->select('*') ->from('bruteforce_attempts') ->where($qb->expr()->gt('occurred', $qb->createNamedParameter($cutoffTime))) ->andWhere($qb->expr()->eq('subnet', $qb->createNamedParameter($ipAddress->getSubnet()))); if ($action !== '') { $qb->andWhere($qb->expr()->eq('action', $qb->createNamedParameter($action))); } $attempts = count($qb->execute()->fetchAll()); if ($attempts === 0) { return 0; } $maxDelay = 25; $firstDelay = 0.1; if ($attempts > (8 * PHP_INT_SIZE - 1)) { // Don't ever overflow. Just assume the maxDelay time:s $firstDelay = $maxDelay; } else { $firstDelay *= pow(2, $attempts); if ($firstDelay > $maxDelay) { $firstDelay = $maxDelay; } } return (int) \ceil($firstDelay * 1000); } /** * Reset the throttling delay for an IP address, action and metadata * * @param string $ip * @param string $action * @param string $metadata */ public function resetDelay($ip, $action, $metadata) { $ipAddress = new IpAddress($ip); if ($this->isIPWhitelisted((string)$ipAddress)) { return; } $cutoffTime = (new \DateTime()) ->sub($this->getCutoff(43200)) ->getTimestamp(); $qb = $this->db->getQueryBuilder(); $qb->delete('bruteforce_attempts') ->where($qb->expr()->gt('occurred', $qb->createNamedParameter($cutoffTime))) ->andWhere($qb->expr()->eq('subnet', $qb->createNamedParameter($ipAddress->getSubnet()))) ->andWhere($qb->expr()->eq('action', $qb->createNamedParameter($action))) ->andWhere($qb->expr()->eq('metadata', $qb->createNamedParameter(json_encode($metadata)))); $qb->execute(); } /** * Will sleep for the defined amount of time * * @param string $ip * @param string $action optionally filter by action * @return int the time spent sleeping */ public function sleepDelay($ip, $action = '') { $delay = $this->getDelay($ip, $action); usleep($delay * 1000); return $delay; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Projectile : MonoBehaviour { // --------------------------- PROTECTED CONFIG ATTRIBUTES --------------------------- // protected PlayerInputCtlr.ePlayer origin; protected float m_rotationSpeed; [Header("Dimensions")] protected float m_width = 0.2f; protected float m_height = 0.2f; public GameObject PistolPref; public GameObject SaberPref; private void Awake() { m_rotationSpeed = 0f; } private void Update() { transform.Rotate(new Vector3(0, 0, m_rotationSpeed)); } void OnCollisionEnter2D(Collision2D collision) { GameObject other = collision.gameObject; if (other.GetComponentInChildren<DamageBehaviour>()!=null) { if (tag == "Lethal") { other.GetComponentInChildren<DamageBehaviour>().TakeDamage(origin); Destroy(gameObject); } else { other.GetComponentInChildren<DamageBehaviour>().CallStun(); GameObject obj; switch (name) { case "ThrowablePistol(Clone)": obj = Instantiate(PistolPref, transform.position, Quaternion.identity); break; case "ThrowableSaber(Clone)": obj = Instantiate(SaberPref, transform.position, Quaternion.identity); break; default: obj = Instantiate(SaberPref, transform.position, Quaternion.identity); break; } obj.GetComponent<Rigidbody2D>().velocity = new Vector3((-0.2f)*this.GetComponent<Rigidbody2D>().velocity.x, 5f, 0); obj.GetComponent<Rigidbody2D>().gravityScale = 1; Destroy(obj, 5f); Destroy(gameObject); } } else { if (tag == "Lethal") Destroy(gameObject); else { GameObject obj; switch (name) { case "ThrowablePistol(Clone)": obj = Instantiate(PistolPref, transform.position, Quaternion.identity); break; case "ThrowableSaber(Clone)": obj = Instantiate(SaberPref, transform.position, Quaternion.identity); break; default: obj = Instantiate(SaberPref, transform.position, Quaternion.identity); break; } obj.GetComponent<Rigidbody2D>().velocity = new Vector3((-0.2f) * this.GetComponent<Rigidbody2D>().velocity.x, 5f, 0); obj.GetComponent<Rigidbody2D>().gravityScale = 1; Destroy(obj, 5f); Destroy(gameObject); } } } public void SetOrigin(PlayerInputCtlr.ePlayer player) { origin = player; } public void SetRotationSpeed(float rotationSpeed) { m_rotationSpeed = rotationSpeed; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace YourProject_winForms { public partial class EditService : Form { #region Variable Declarations private long _lngPKID = 0; private DataTable _dtbService = null; private bool _blnNew = false; private string fileName; string pdfFile; #endregion #region Constructors /// <summary> /// Constructor to create new record /// </summary> public EditService() { _blnNew = true; InitializeComponent(); InitializeDataTable(); } /// <summary> /// Constructor to open and update existing record /// </summary> /// <param name="PKID"></param> public EditService(long PKID) { InitializeComponent(); _lngPKID = PKID; InitializeDataTable(); } #endregion #region Control Events private void EditService_Load(object sender, EventArgs e) { BindControls(); // Upon loading the form, loads the saved image from file stream LoadImageFromFileStream(); // pdf should open when this form loads LoadPDFFromFilePath(); CollectGarbage(); //calls for garbage collection } private void EditService_Paint(object sender, PaintEventArgs e) { // read the new Property settings of the ColorTheme this.BackColor = Properties.Settings.Default.ColorTheme; } #endregion #region Accessors /// <summary> /// This method will initialize the data table by getting the record of an existing tool or, /// create a new row when adding a new tool. /// </summary> private void InitializeDataTable() { // Get an existing Tool for Update _dtbService = ProjectModel.DLL.ProjectContext.GetDataTable( $"SELECT * FROM Service WHERE ServiceId = {_lngPKID}", "Service"); // Create an empty row of Tools so users can fill it with Tool title. if (_blnNew) { DataRow row = _dtbService.NewRow(); _dtbService.Rows.Add(row); } } #endregion #region Button Events /// <summary> /// Will allow user to view the maximized receipt image. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void pictureBoxReceipt_Click(object sender, EventArgs e) { // load file from storage location. string filePathName = textBoxReceiptIMG.Text; ReceiptView frm = new ReceiptView(filePathName); frm.Show(); } /// <summary> /// updates receipt image on click. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnUpdateImg_Click(object sender, EventArgs e) { RemovePBImage(); //removes current image from picture box UpdateReceiptImage(sender); //opens dialogue box for image selection & updates path UpdateImageSavePath(); //saves image to file path CollectGarbage(); //calls for garbage collection } /// <summary> /// deletes receipt image on click. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnDeleteImage_Click(object sender, EventArgs e) { RemovePBImage(); //removes current image from picture box } /// <summary> /// Will update the new details to the exsiting record. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnUpdate_Click(object sender, EventArgs e) { // Establish connection String string connectionString = ProjectModel.DLL.ProjectContext.ConnectionString = Properties.Settings.Default.ConnectionString; // if these two requirements are not met text length needs to be at least 5 characters if (textBoxProductName.Text == "" || textBoxBusinessName.Text == "") //Text == "" { // Display a message to the user about missing details MessageBox.Show("Please Enter Business Name & Product Name.", MessageBoxIcon.Warning.ToString(), MessageBoxButtons.OK); return; } try { // display message to user to verify Insert Success MessageBox.Show(textBoxBusinessName.Text + " record updated. : " + DateTime.Now); // always do the EndEdit, otherwise the data will not persist. _dtbService.Rows[0].EndEdit(); // calls the method in our Data Access Layer to save the changes to the data table ProjectModel.DLL.ProjectContext.SaveDatabaseTable(_dtbService); // save image to folder. //SaveImageToLocalFolder(); } catch (Exception serviceExists) // Catch our exceptions { // display our warning message MessageBox.Show(serviceExists.Message, "Product Record Not Updated...", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } /// <summary> /// Will close this window and return to the previous screen. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnClose_Click(object sender, EventArgs e) { CollectGarbage(); //calls for garbage collection Close(); // close this window } /// <summary> /// Will close this window and return to the previous screen. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BackButton_Click_1(object sender, EventArgs e) { CollectGarbage(); //calls for garbage collection Close(); // close this window } #endregion #region Helper Methods /// <summary> /// This method will bind the controls to each field in the data table. /// </summary> private void BindControls() { // Binding the text box txtUpdateToolId with the data table '_dtbTool' and // map it to the database field called 'ToolId' and use the // 'Text' property of the control for binding. txtServiceId.DataBindings.Add("Text", _dtbService, "ServiceId"); textBoxBusinessName.DataBindings.Add("Text", _dtbService, "BusinessName"); textLocation.DataBindings.Add("Text", _dtbService, "Location"); txtBoxContactName.DataBindings.Add("Text", _dtbService, "ContactName"); txtContactEmail.DataBindings.Add("Text", _dtbService, "ContactEmail"); textContactPhone.DataBindings.Add("Text", _dtbService, "ContactPhone"); textBoxProductName.DataBindings.Add("Text", _dtbService, "ProductName"); textBoxAmount.DataBindings.Add("Text", _dtbService, "Amount"); richTextBoxComments.DataBindings.Add("Text", _dtbService, "Comments"); textBoxReceiptIMG.DataBindings.Add("Text", _dtbService, "ReceiptIMG"); txtPDFFile.DataBindings.Add("Text", _dtbService, "PDFFile"); // display date in day-month-year format. dtpDateServiceDate.Format = DateTimePickerFormat.Custom; dtpDateServiceDate.CustomFormat = "dd-MMM-yyyy"; // display date in day-month-year format. dtpDateExpired.Format = DateTimePickerFormat.Custom; dtpDateExpired.CustomFormat = "dd-MMM-yyyy"; // bind the dates to the date time picker. dtpDateServiceDate.DataBindings.Add("Text", _dtbService, "ServiceDate"); dtpDateExpired.DataBindings.Add("Text", _dtbService, "WarrantyExpired"); } #endregion #region File Handling /// <summary> /// Removes current image from picture box /// </summary> private void RemovePBImage() { try { if (pictureBoxReceipt.Image != null) { pictureBoxReceipt.Image = null; File.Delete(textBoxReceiptIMG.Text); } } catch (Exception e) { // display error message to user MessageBox.Show("Error Removing Image @ " + textBoxReceiptIMG.Text); } } /// <summary> /// select new image for updating receipt /// </summary> /// <param name="sender"></param> private void UpdateReceiptImage(object sender) { Button SelBtn = sender as Button; // sets directory path for image file and folder. string dirPath = "C:\\Receipt Book\\MyServices\\"; string folder = textBoxBusinessName.Text; string productName = textBoxProductName.Text + ".jpg"; //checks if directory exists else creates directory if (!Directory.Exists(dirPath + folder)) Directory.CreateDirectory(dirPath + folder); //path for folder directory and file string filePathName = dirPath + folder + "\\" + productName; try { // if a picture has been uploaded to the screen. Do This --> if (pictureBoxReceipt == null || pictureBoxReceipt != null) { using (OpenFileDialog open = new OpenFileDialog() { Filter = "All Files (*.*;) | *.*; | JPG Files (*.jpg;)| *.jpg; | JPEG Files (*.jpeg;) | *.jpeg; | BMP Files (*.bmp;) | *.bmp; | PNG files (*.png;) | *.png;", ValidateNames = true, Multiselect = false }) // if the dialog contains any of the file types and is successful.. if (open.ShowDialog() == DialogResult.OK) { // select the image from file and display to the picture box on screen. pictureBoxReceipt.Image = Image.FromFile(open.FileName); // select the image from file and display to the picture box on screen. textBoxReceiptIMG.Text = filePathName; textBoxReceiptIMG.Focus(); } } } catch (FileNotFoundException fne) { // display error message to user to verify Insert Success // MessageBox.Show("File Not Found @ " + textBoxReceiptIMG.Text); } catch (Exception e) { // display error message to user to verify Insert Success // MessageBox.Show("Error Updating Image @ " + textBoxReceiptIMG.Text); } } private void UpdateImageSavePath() { if (pictureBoxReceipt.Image != null) { try { // sets directory path for image file and folder. string productName = textBoxProductName.Text; string folder = "C:\\Receipt Book\\MyServices\\" + textBoxBusinessName.Text; string fileName = productName + ".jpg"; //checks if directory exists else creates directory if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); //path for folder directory and file string filePathName = folder + "\\"; string filePath = Path.Combine(filePathName, fileName); Image receiptFile = pictureBoxReceipt.Image; receiptFile.Save(filePath); } catch (FileNotFoundException fne) { // display error message to user to verify Insert Success // MessageBox.Show("File Not Found @ " + textBoxReceiptIMG.Text); } catch (Exception e) { // display error message to user to verify Insert Success // MessageBox.Show("Error Saving File @ " + textBoxReceiptIMG.Text); } } } /// <summary> /// Loads the image from file to stream as read only. /// </summary> private void LoadImageFromFileStream() { try { if (textBoxReceiptIMG.Text != null) { // load file from storage location. string fileDirPath = textBoxReceiptIMG.Text; FileStream fs = File.OpenRead(fileDirPath); pictureBoxReceipt.Image = Image.FromStream(fs); fs.Close(); } } catch (FileNotFoundException fne) { // display error message to user to verify Insert Success // MessageBox.Show("File Not Found @ " + textBoxReceiptIMG.Text); } catch (Exception e) { // display error message to user to verify Insert Success // MessageBox.Show("Error Loading File @ " + textBoxReceiptIMG.Text); } } #endregion #region Memory Management Method /// <summary> /// This method will call for garbage collection. /// </summary> private void CollectGarbage() { GC.Collect(); GC.WaitForPendingFinalizers(); } #endregion #region PDF File Handling private void btnUpdatePDF_Click(object sender, EventArgs e) { // RemovePDFImage(); //removes current image from pdf viewer UpdatePDFFile(sender); //opens dialogue box for pdf selection & updates path UpdatePDFSavePath(); //saves pdf to file path CollectGarbage(); //calls for garbage collection } /// <summary> /// Removes current image from picture box /// </summary> private void RemovePDFImage() { try { if (axAcroPDF_viewer.src != null) { axAcroPDF_viewer.src = null; File.Delete(txtPDFFile.Text); } } catch (Exception e) { // display error message to user // MessageBox.Show("Error Removing Image @ " + txtPDFFile.Text + " " + e.Message); } } /// <summary> /// select new image for updating receipt /// </summary> /// <param name="sender"></param> private void UpdatePDFFile(object sender) { Button SelectButton = sender as Button; // sets directory path for image file and folder. string dirPath = "C:\\Receipt Book\\MyReceipts\\"; string folder = textBoxBusinessName.Text; string productName = textBoxProductName.Text + ".pdf"; //checks if directory exists else creates directory if (!Directory.Exists(dirPath + folder)) Directory.CreateDirectory(dirPath + folder); //path for folder directory and file string filePathName = dirPath + folder + "\\" + productName; try { // if a picture has been uploaded to the screen. Do This --> if (axAcroPDF_viewer.src == null || axAcroPDF_viewer.src != null) { using (OpenFileDialog ofd = new OpenFileDialog() { ValidateNames = true, Multiselect = false, Filter = "PDF files|*.pdf" }) { // if the dialog box result is not cancel if (ofd.ShowDialog() != DialogResult.Cancel) { try { // set the pdf viewer source to the file name opened. axAcroPDF_viewer.src = ofd.FileName; // select the pdf from file and display to the pdf viewer box on screen. txtPDFFile.Text = filePathName; txtPDFFile.Focus(); pdfFile = ofd.FileName; } catch (Exception pdf_Read_Exception) { MessageBox.Show(pdf_Read_Exception.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } //the dialog box result is cancel else { //DO Nothing stooge } } } } catch (FileNotFoundException fne) { // display error message to user // MessageBox.Show("File Not Found @ " + txtPDFFile.Text); } catch (Exception e) { // display error message to user // MessageBox.Show("Error Selecting Product File @ " + txtPDFFile.Text); } } private void UpdatePDFSavePath() { if (axAcroPDF_viewer.src != null) { try { // sets directory path for image file and folder. string dirPath = "C:\\Receipt Book\\MyReceipts\\"; string folder = textBoxBusinessName.Text; string productName = textBoxProductName.Text + ".pdf"; //checks if directory exists else creates directory if (!Directory.Exists(dirPath + folder)) Directory.CreateDirectory(dirPath + folder); //path for folder directory and file string filePathName = dirPath + folder + "\\"; string filePath = Path.Combine(filePathName, productName); //TODO - fix!! this deletes the file even if user presses cancel????? File.Delete(filePath); File.Copy(pdfFile, filePath); } catch (FileNotFoundException fne) { // display error message to user MessageBox.Show("File Not Found @ " + txtPDFFile.Text); } catch (Exception e) { // display error message to user MessageBox.Show("Error Setting File Path @ " + txtPDFFile.Text); } } } /// <summary> /// Will allow user to view the maximized receipt PDF. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnBigPDF_Click(object sender, EventArgs e) { // load file from storage location. string filePathName = txtPDFFile.Text; PDF_Reader_View frm = new PDF_Reader_View(filePathName); frm.Show(); } private void DeletePdf_Click(object sender, EventArgs e) { try { string filePath = txtPDFFile.Text; File.Delete(filePath); axAcroPDF_viewer.src = null; //"E:\\Assessments\\Larissa_DB_Project\\YourProject_winForms\\Resources\\NO_PDF.pdf"; txtPDFFile.Text = ""; txtPDFFile.Focus(); } catch (FileNotFoundException fne) { // display error message to user //MessageBox.Show("File Not Found @ " + txtPDFFile.Text); } catch (Exception ex) { // display error message to user MessageBox.Show("PDF File has already been deleted." + txtPDFFile.Text); } } /// <summary> /// Loads the image from file to stream as read only. /// </summary> private void LoadPDFFromFilePath() { try { if (txtPDFFile.Text != null) { // load file from storage location. string pdfFileDirPath = txtPDFFile.Text; axAcroPDF_viewer.src = pdfFileDirPath; axAcroPDF_viewer.Refresh(); CollectGarbage(); } } // catch exceptions blanked to hide user message when no image is saved, // better for reading pdf and image files catch (FileNotFoundException fne) { // display error message to user // MessageBox.Show("File Not Found @ " + textBoxReceiptIMG.Text); } catch (Exception e) { // display error message to user // MessageBox.Show("Error loading File @ " + textBoxReceiptIMG.Text); } } #endregion } }
using LowLevelNetworking.Shared; using System; using System.Collections.Generic; using System.IO; using WUIShared.Packets; namespace WUIServer { public class ServerAssetManager { private Dictionary<string, byte[]> assets; public ServerAssetManager() { assets = new Dictionary<string, byte[]>(); } public void AddAsset(string name, byte[] asset) { lock (assets) { if (assets.ContainsKey(name)) return; Console.WriteLine("Broadcasting asset " + name + " to clients, the asset is of size: " + asset.Length + "."); assets[name] = asset; Program.broadcaster.Broadcast(new WUIShared.Packets.AssetSend() { assetName = name, asset = asset }); } } public void SendAllAssetsTo(ClientBase clientBase) { lock (assets) foreach (var item in assets) { Console.WriteLine("Sending asset " + item.Key + " to client id " + clientBase.Id + "."); clientBase.Send(new AssetSend() { assetName = item.Key, asset = item.Value }); } } public void Handle(ClientBase clientHandler) { clientHandler.On<AssetSend>(OnAssetSend); clientHandler.OnStart += ClientHandler_OnStart; } private void ClientHandler_OnStart(ClientBase client) { SendAllAssetsTo(client); } //TODO: ADD SECURITY MEASURES TO SERVER RECEIVING ASSETS. private void OnAssetSend(ClientBase sender, AssetSend packet) { Console.WriteLine("Recieved asset " + packet.assetName + " from client."); AddAsset(packet.assetName, packet.asset); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace ProyectoFinalMantenimiento { /// <summary> /// Lógica de interacción para MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void BotonAgregar(object sender, RoutedEventArgs e) { gridFormulario.Visibility = Visibility.Visible; gridBuscar.Visibility = Visibility.Hidden; gridEliminar.Visibility = Visibility.Hidden; gridActualizar.Visibility = Visibility.Hidden; imgLogo.Visibility = Visibility.Hidden; imgIntegrantes.Visibility = Visibility.Hidden; } private void BotonEliminar(object sender, RoutedEventArgs e) { gridFormulario.Visibility = Visibility.Hidden; gridBuscar.Visibility = Visibility.Hidden; gridEliminar.Visibility = Visibility.Visible; gridActualizar.Visibility = Visibility.Hidden; imgLogo.Visibility = Visibility.Visible; imgIntegrantes.Visibility = Visibility.Visible; } private void BotonActualizar(object sender, RoutedEventArgs e) { gridFormulario.Visibility = Visibility.Hidden; gridBuscar.Visibility = Visibility.Hidden; gridEliminar.Visibility = Visibility.Hidden; gridActualizar.Visibility = Visibility.Visible; imgLogo.Visibility = Visibility.Visible; imgIntegrantes.Visibility = Visibility.Visible; } private void BotonBuscar(object sender, RoutedEventArgs e) { gridFormulario.Visibility = Visibility.Hidden; gridBuscar.Visibility = Visibility.Visible; gridEliminar.Visibility = Visibility.Hidden; gridActualizar.Visibility = Visibility.Hidden; imgLogo.Visibility = Visibility.Visible; imgIntegrantes.Visibility = Visibility.Visible; } private void BotonSalir(object sender, RoutedEventArgs e) { System.Environment.Exit(0); } private void BuscarFormulario(object sender, RoutedEventArgs e) { } private void EliminarOrden(object sender, RoutedEventArgs e) { } private void BotonCancelar(object sender, RoutedEventArgs e) { dpOrderDate.Text = ""; dpRequiredDate.Text = ""; txtShippedDate.Text = ""; txtShipName.Text = ""; txtShipAddress.Text = ""; txtShipCity.Text = ""; txtShipRegion.Text = ""; txtShipCountry.Text = ""; txtShipPostalCode.Text = ""; txtShipVia.Text = ""; txtFreight.Text = ""; gridFormulario.Visibility = Visibility.Hidden; gridBuscar.Visibility = Visibility.Visible; gridEliminar.Visibility = Visibility.Hidden; gridActualizar.Visibility = Visibility.Hidden; imgLogo.Visibility = Visibility.Visible; imgIntegrantes.Visibility = Visibility.Visible; } } }
using Crt.Data.Database; using Crt.Data.Repositories; using Crt.Domain.Services.Base; using Crt.Model; using Crt.Model.Dtos; using Crt.Model.Dtos.Element; using Crt.Model.Utils; using System.Collections.Generic; using System.Threading.Tasks; namespace Crt.Domain.Services { public interface IElementService { Task<IEnumerable<ElementDto>> GetElementsAsync(); Task<PagedDto<ElementListDto>> SearchElementsAsync(string searchText, bool? isActive, int pageSize, int pageNumber, string orderBy, string direction); Task<ElementDto> GetElementByIdAsync(decimal elementId); Task<(decimal elementId, Dictionary<string, List<string>> errors)> CreateElementAsync(ElementCreateDto element); Task<(bool notFound, Dictionary<string, List<string>> errors)> UpdateElementAsync(ElementUpdateDto element); Task<(bool notFound, Dictionary<string, List<string>> errors)> DeleteElementAsync(decimal elementId); } public class ElementService : CrtServiceBase, IElementService { private IElementRepository _elementRepo; public ElementService(CrtCurrentUser currentUser, IFieldValidatorService validator, IUnitOfWork unitOfWork, IElementRepository elementRepo) : base(currentUser, validator, unitOfWork) { _elementRepo = elementRepo; } public async Task<IEnumerable<ElementDto>> GetElementsAsync() { return await _elementRepo.GetElementsAsync(); } public async Task<PagedDto<ElementListDto>> SearchElementsAsync(string searchText, bool? isActive, int pageSize, int pageNumber, string orderBy, string direction) { return await _elementRepo.SearchElementsAsync(searchText, isActive, pageSize, pageNumber, orderBy, direction); } public async Task<ElementDto> GetElementByIdAsync(decimal elementId) { return await _elementRepo.GetElementByIdAsync(elementId); } public async Task<(decimal elementId, Dictionary<string, List<string>> errors)> CreateElementAsync(ElementCreateDto element) { element.TrimStringFields(); var errors = new Dictionary<string, List<string>>(); errors = _validator.Validate(Entities.Element, element, errors); await ValidateElement(element, errors); if (errors.Count > 0) { return (0, errors); } var crtElement = await _elementRepo.CreateElementAsync(element); _unitOfWork.Commit(); await _elementRepo.UpdateDisplayOrderAsync(); _unitOfWork.Commit(); return (crtElement.ElementId, errors); } public async Task<(bool notFound, Dictionary<string, List<string>> errors)> UpdateElementAsync(ElementUpdateDto element) { element.TrimStringFields(); var crtElement = await _elementRepo.GetElementByIdAsync(element.ElementId); if (crtElement == null) { return (true, null); } var errors = new Dictionary<string, List<string>>(); errors = _validator.Validate(Entities.Element, element, errors); await ValidateElement(element, errors); if (errors.Count > 0) { return (false, errors); } await _elementRepo.UpdateElementAsync(element); _unitOfWork.Commit(); await _elementRepo.UpdateDisplayOrderAsync(); _unitOfWork.Commit(); return (false, errors); } public async Task<(bool notFound, Dictionary<string, List<string>> errors)> DeleteElementAsync(decimal elementId) { var crtElement = await _elementRepo.GetElementByIdAsync(elementId); if (crtElement == null) { return (true, null); } var errors = new Dictionary<string, List<string>>(); if (await _elementRepo.IsElementInUseAsync(elementId)) { errors.AddItem(Fields.Code, $"Element ID: [{elementId}], Code: [{crtElement.Code}] is in use and cannot be deleted."); } await _elementRepo.DeleteElementAsync(elementId); _unitOfWork.Commit(); await _elementRepo.UpdateDisplayOrderAsync(); _unitOfWork.Commit(); return (false, errors); } private async Task ValidateElement(ElementSaveDto element, Dictionary<string, List<string>> errors) { var elementId = element.GetType() == typeof(ElementUpdateDto) ? ((ElementUpdateDto)element).ElementId : 0M; if (await _elementRepo.DoesCodeExistAsync(elementId, element.Code)) { errors.AddItem(Fields.Code, $"Code [{element.Code}] already exists"); } } } }
using UnityEngine; using System.Collections.Generic; using System.Linq; namespace Ph.Bouncer { public class TargetHits { private Dictionary<Colour, int> targetHits; public TargetHits(IEnumerable<Target> targets) { targetHits = new Dictionary<Colour, int>(); foreach(var target in targets) { targetHits.Add(target.Colour, 0); } } public void UpdateHits(Colour colour, int hits) { // TODO Error checking? Colour not found targetHits[colour] = hits; } public bool AllTargetsHaveHitsGreaterOrEqualTo(int numberOfHits) { return !(targetHits.Where(x => x.Value < numberOfHits).Count() > 0); } } }
// // Copyright (c), 2017. Object Training Pty Ltd. All rights reserved. // Written by Tim Hastings. // using System; using Xamarin.Forms; namespace MyListApp { /// <summary> /// Sync manager. /// </summary> public class SyncManager { // Messages used by MessagingCenter public const String NotSynced = "Not Synced"; public const String Syncing = "Syncing"; public const String Synced = "Synced"; public const String LoggedIn = "Logged In"; public const String NotLoggedIn = "Not Logged In"; // Current state public String state { get; set; } public SyncManager() { state = NotSynced; } public void Send(String message) { state = message; MessagingCenter.Send<SyncManager>(this, message); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DriveMgr.WebUI.admin.StudentsDynamic { /// <summary> /// bg_preAppointmentHandler 的摘要说明 /// </summary> public class bg_preAppointmentHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; string action = context.Request.Params["action"]; DriveMgr.Model.UserOperateLog userOperateLog = null; //操作日志对象 try { DriveMgr.Model.User userFromCookie = DriveMgr.Common.UserHelper.GetUser(context); //获取cookie里的用户对象 userOperateLog = new Model.UserOperateLog(); userOperateLog.UserIp = context.Request.UserHostAddress; userOperateLog.UserName = userFromCookie.UserId; switch (action) { case "search": string strWhere = "1=1"; string sort = context.Request.Params["sort"]; //排序列 string order = context.Request.Params["order"]; //排序方式 asc或者desc int pageindex = int.Parse(context.Request.Params["page"]); int pagesize = int.Parse(context.Request.Params["rows"]); string ui_preAppointment_name = context.Request.Params["ui_preAppointment_name"] ?? ""; string ui_preAppointment_code = context.Request.Params["ui_preAppointment_code"] ?? ""; string ui_preAppointment_appstatus = context.Request.Params["ui_preAppointment_appstatus"] ?? ""; string subjectId = context.Request.Params["subjectId"] ?? ""; string ui_preAppointment_AppStartTime = context.Request.Params["ui_preAppointment_AppStartTime"] ?? ""; string ui_preAppointment_AppEndTime = context.Request.Params["ui_preAppointment_AppEndTime"] ?? ""; strWhere += " and flag=1 and PeriodsID = (SELECT TOP 1 CurrentPeroidID FROM tb_CurrentPeroid)"; if (subjectId.Trim() != "" && !DriveMgr.Common.SqlInjection.GetString(subjectId)) //防止sql注入 strWhere += string.Format(" and SubjectID = '{0}'", subjectId.Trim()); if (ui_preAppointment_AppStartTime.Trim() != "" && !DriveMgr.Common.SqlInjection.GetString(ui_preAppointment_AppStartTime)) //防止sql注入 strWhere += string.Format(" and AppointDate >= '{0}'", ui_preAppointment_AppStartTime.Trim()); if (ui_preAppointment_AppEndTime.Trim() != "" && !DriveMgr.Common.SqlInjection.GetString(ui_preAppointment_AppEndTime)) //防止sql注入 strWhere += string.Format(" and AppointDate <= '{0}'", ui_preAppointment_AppEndTime.Trim()); if (ui_preAppointment_appstatus.Trim() != "select" && ui_preAppointment_appstatus.Trim() != "") strWhere += " and AppointmentStatus = '" + ui_preAppointment_appstatus.Trim() + "'"; if (ui_preAppointment_name.Trim() != "" && !DriveMgr.Common.SqlInjection.GetString(ui_preAppointment_name)) //防止sql注入 strWhere += string.Format(" and StudentsName like '%{0}%'", ui_preAppointment_name.Trim()); if (ui_preAppointment_code.Trim() != "" && !DriveMgr.Common.SqlInjection.GetString(ui_preAppointment_code)) strWhere += string.Format(" and StudentCode like '%{0}%'", ui_preAppointment_code.Trim()); int totalCount; //输出参数 string strJson = new DriveMgr.BLL.AppointmentBLL().GetPager("V_PreAppointment", "*", sort + " " + order, pagesize, pageindex, strWhere, out totalCount); context.Response.Write("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}"); userOperateLog.OperateInfo = "查询预约"; userOperateLog.IfSuccess = true; userOperateLog.Description = "查询条件:" + strWhere + " 排序:" + sort + " " + order + " 页码/每页大小:" + pageindex + " " + pagesize; DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog); break; case "appointment": //预约考试 if (userFromCookie != null && new DriveMgr.BLL.Authority().IfAuthority("preAppointment", "preAppointment", userFromCookie.Id)) { int id = Convert.ToInt32(context.Request.Params["preAppointmentid_edit"]); DateTime ui_preAppointment_appDate_edit = DateTime.Parse(context.Request.Params["ui_preAppointment_appDate_edit"] ?? ""); int editsubjectId = Int32.Parse(context.Request.Params["subjectId"]); string ui_preAppointment_remark_edit = context.Request.Params["ui_preAppointment_remark_edit"] ?? ""; DriveMgr.Model.AppointmentModel appointmentEdit = new Model.AppointmentModel(); appointmentEdit.ID = id; appointmentEdit.AppointDate = ui_preAppointment_appDate_edit; appointmentEdit.Operater = userFromCookie.UserName; appointmentEdit.AppointStatus = 1; appointmentEdit.SubjectID = editsubjectId; appointmentEdit.Remark = ui_preAppointment_remark_edit; if (new DriveMgr.BLL.AppointmentBLL().Update(appointmentEdit)) { userOperateLog.OperateInfo = "预约考试信息"; userOperateLog.IfSuccess = true; userOperateLog.Description = "预约成功,预约主键:" + appointmentEdit.ID+";预约科目:"+appointmentEdit.SubjectID; context.Response.Write("{\"msg\":\"预约信息成功!\",\"success\":true}"); } else { userOperateLog.OperateInfo = "预约考试信息"; userOperateLog.IfSuccess = false; userOperateLog.Description = "预约失败"; context.Response.Write("{\"msg\":\"预约失败!\",\"success\":false}"); } } else { userOperateLog.OperateInfo = "预约考试信息"; userOperateLog.IfSuccess = false; userOperateLog.Description = "无权限,请联系管理员"; context.Response.Write("{\"msg\":\"无权限,请联系管理员!\",\"success\":false}"); } DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog); break; default: context.Response.Write("{\"msg\":\"参数错误!\",\"success\":false}"); break; } } catch (Exception ex) { context.Response.Write("{\"msg\":\"" + DriveMgr.Common.JsonHelper.StringFilter(ex.Message) + "\",\"success\":false}"); userOperateLog.OperateInfo = "预约考试功能异常"; userOperateLog.IfSuccess = false; userOperateLog.Description = DriveMgr.Common.JsonHelper.StringFilter(ex.Message); DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog); } } public bool IsReusable { get { return false; } } } }
using API_Test.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Threading.Tasks; namespace API_Test.Controllers { [Route("api/[controller]")] [ApiController] public class AdminController : ControllerBase { private readonly project1Context db; public AdminController(project1Context context) { db = context; } #region Admin Dashboard [Route("admin-dashboard")] [HttpGet] public IActionResult getRetailers() { var retailers = db.TblRetailers.Where(x => x.Approved == 0).ToList(); if (retailers.Count > 0) { return Ok(retailers); } else { return Ok("No Retailers"); } } #endregion #region Approve Retailer By Admin [Route("approve-retailer")] [HttpPut] public IActionResult ApproveRetailer(int retailerid, string retaileremail) { var retailer = db.TblRetailers.Find(retailerid); retailer.Approved = 1; db.Entry(retailer).State = EntityState.Modified; db.SaveChanges(); return Ok("Approved"); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using StudentInfoAPI.DTO.SubjectDTO; using StudentInfoAPI.Interface; namespace StudentInfoAPI.Controllers { [Route("api/[controller]")] [ApiController] public class SubjectController : ControllerBase { private readonly ISubjectRepo _repo; public SubjectController(ISubjectRepo repo) { _repo = repo; } [HttpGet("GetSubjectList")] public async Task<IActionResult> GetSubjectList([FromQuery] GetSubjectListRequest request) { var data = await _repo.GetSubjectLists(request); return Ok(data); } [HttpPost("CreateSubject")] public async Task<IActionResult> CreateSubject(CreateSubjectRequest request) { var data = await _repo.CreateSubjects(request); return Ok(data); } [HttpPost("UpdateSubject")] public async Task<IActionResult> UpdateSubject(UpdateSubjectRequest request) { var data = await _repo.UpdateSubjects(request); return Ok(data); } [HttpDelete("DeleteSubject")] public async Task<IActionResult> DeleteSubject(string Subjects) { var data = await _repo.DeleteSubject(Subjects); return Ok(data); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace Calcifer.Utilities.Logging { public static class Log { private static OutputList outputs; public static OutputList Output { get { return outputs ?? (outputs = new OutputList()); } } public static LogLevel Verbosity { get; set; } public static void WriteLine(LogLevel level, string format, params object[] args) { var message = string.Format(format, args); if (level < Verbosity) return; var stackFrames = new StackTrace().GetFrames(); if (stackFrames == null) return; var types = stackFrames.Select(frame => frame.GetMethod().DeclaringType); var type = types.First(t => t != typeof(Log) && t != null); Output [level](level, type.Name + ": " + message); } } public delegate void OutputDelegate(LogLevel level, string message); public class OutputList { private static readonly OutputDelegate deflt = (level, message) => { }; private static readonly Dictionary<LogLevel, OutputDelegate> outputs = new Dictionary<LogLevel, OutputDelegate>(); public OutputDelegate this [LogLevel level] { get { if ((level < LogLevel.Debug) || (level > LogLevel.Fatal)) throw new ArgumentOutOfRangeException("level"); if (!outputs.ContainsKey(level)) outputs.Add(level, deflt); return outputs [level]; } set { if (level == LogLevel.Any) for (var l = LogLevel.Debug; l <= LogLevel.Fatal; l++) outputs [l] = value; else outputs [level] = value; } } } public enum LogLevel { Any = 0, Debug = 1, Info = 2, Warning = 3, Error = 4, Fatal = 5, } }