text
stringlengths
13
6.01M
using System; namespace SuperSorter { public class ArrayGenerator { protected int n; protected int max; protected int seed; public String name { private set; get; } = "Random"; public ArrayGenerator(int n, int max, int seed) { this.n = n; this.max = max; this.seed = seed; } public ArrayGenerator(int n, int max, int seed, String name) { this.n = n; this.max = max; this.seed = seed; this.name = name; } public virtual int[] Generate() { int[] rnd_list = new int[n]; Random rnd = new Random(seed); for (int i = 0; i < n; i++) { rnd_list[i] = (rnd.Next(0, max)); } return rnd_list; } public override string ToString() { return name; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class MatchGameLogic : MonoBehaviour { List<List<Card>> grid; public int numTypes = 5; private int numRows; private int numCols; private Card pickedCard = null; private int numMatches = 0; public Texture2D tex; public Text goodjob; public Transform cardPrefab; private float cardWidth; private float cardHeight; public Button nextDiffButton; public GameObject buttons; public Camera cam; private InfoScript info; // Use this for initialization void Start () { goodjob.enabled = false; buttons.SetActive(false); info = GameObject.Find("Game Info").GetComponent<InfoScript>(); if (info != null) { numTypes = info.activeDifficulty; Debug.Log("num types"); Debug.Log(numTypes); } for (int i = 0; i <= 10; i++){ if (numTypes*2 >= i * i) { continue; } numRows = i; break; } if ((numTypes * 2) % numRows == 0) { numCols = numTypes * 2 / numRows; } else { numCols = (numTypes * 2 / numRows) + 1; } cardWidth = cardLength(numCols, true); cardHeight = cardLength(numRows, false); cardPrefab.localScale = new Vector3(cardWidth, cardHeight, 0); Debug.Log(string.Format("Card width: {0}, Card height: {1}, {0}", cardWidth, cardHeight)); grid = new List<List<Card>>(); populateGrid(); Debug.Log(cam.orthographicSize); // showGrid(); } private float cardLength (int numCards, bool width) { float screenLength = 0; if (width == true) { screenLength = 22f; } else { screenLength = 9f; } return screenLength / (1.25f * numCards + .25f * numCards); } // Update is called once per frame void Update () { } void populateGrid () { List<int> left = new List<int>(); for (int type = 0; type < numTypes; type++) { left.Add(type); left.Add(type); } Debug.Log(string.Format("There are {0} objects in list", left.Count)); for (int row = 0; row < numRows; row++) { grid.Add(new List<Card>()); for (int col = 0; col < numCols; col++) { if (row*numCols + col >= numTypes * 2) { break; } int randIndex = Random.Range(0, left.Count-1); float newX = -11f + + .25f * cardWidth + .25f * cardWidth * col + .5f * cardWidth + cardWidth * col; float newY = -4.5f + .25f * cardHeight + .25f * cardHeight * row + .5f * cardHeight + cardHeight * row; Vector3 newPosition = new Vector3(newX, newY, 0); Debug.Log(string.Format("new card at {0}, {1}", newX, newY)); Transform cardBody = Instantiate(cardPrefab, newPosition, cardPrefab.rotation); int newType = left[randIndex]; cardBody.gameObject.GetComponent<Card>().construct(newType, row, col); grid[row].Add(cardBody.GetComponent<Card>()); left.RemoveAt(randIndex); } } } void showGrid() { for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { Sprite mySprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, 50f, 50f), new Vector2(0.5f, 0.5f)); Debug.Log("sprite created"); } } } public void pickCard(Card card) { Debug.Log("picked card"); card.reveal(); if (pickedCard != null) { if (pickedCard.type == card.type) { numMatches++; if (numMatches >= numTypes) { goodjob.enabled = true; if (info.activeDifficulty >= 10) { nextDiffButton.enabled = false; } buttons.SetActive(true); if (info.activeDifficulty > info.MatchDiff) { info.MatchDiff = info.activeDifficulty; } Destroy(this); } } else { StartCoroutine(hideRoutine(card, pickedCard)); } pickedCard = null; } else { pickedCard = card; } } IEnumerator hideRoutine(Card card, Card pc) { yield return new WaitForSeconds(.5f); print(Time.time); card.hide(); pc.hide(); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using PhoneNumbers; namespace Grubber.Web.Infrastructure { public class PhoneNumberAttribute : ValidationAttribute, IClientValidatable { public PhoneNumberAttribute() { ErrorMessage = "The {0} field is not a valid phone number."; } public override bool IsValid(object value) { var valueString = value as string; if (string.IsNullOrEmpty(valueString)) { return true; } var util = PhoneNumberUtil.GetInstance(); try { var number = util.Parse(valueString, "US"); return util.IsValidNumber(number); } catch (NumberParseException) { return false; } } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "phonenumber" }; yield return rule; } } } /* https://blog.appharbor.com/2012/02/03/net-phone-number-validation-with-google-libphonenumber */
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 坦克生成器 /// </summary> public abstract class TankSpawner : MonoBehaviour { [Header("【坦克生成器】")] [Header("生成点")] public Transform[] spwanPoints; [Header("主要类型")] public GameObject mainTank; [Header("稀有类型和概率")] public rareTank[] rareTanks; [System.Serializable] public struct rareTank { public GameObject prefab; [Header("生成率(0-1)"), Range(0, 1)] public float rate; } #if UNITY_EDITOR protected virtual void Awake() { if (spwanPoints == null) { Debug.LogError("必须要有SpwanPoint!"); } foreach(Transform t in spwanPoints) { if(t == null) { Debug.LogError("出生点没有设置!"); } } if (rareTanks != null) { float sum = 0; foreach (rareTank rt in rareTanks) { if (rt.prefab == null) { Debug.LogError("稀有坦克种类没有设置!"); } sum += rt.rate; } if (sum >= 1) { Debug.LogError("稀有坦克几率之和不能大于1"); } } } #endif /// <summary> /// 随机获取一个坦克 /// </summary> /// <returns></returns> private GameObject GetATank() { if (rareTanks != null) { float rate = Random.value; for (int i = 0; i < rareTanks.Length; i++) { if (rate < rareTanks[i].rate) { return rareTanks[i].prefab; } rate -= rareTanks[i].rate; } } return mainTank; } //接口----------------------------------- public void GenerateTank() { StartCoroutine(generateTank()); } private IEnumerator generateTank() { Transform spawnPoint = spwanPoints[Random.Range(0, spwanPoints.Length)]; if (spawnPoint == null) { StopAllCoroutines(); } GameObject g = GameObject.Instantiate(GameSystem.Setter.setting.spwanStar, spawnPoint.position, Quaternion.identity, transform); yield return new WaitForSeconds(2); Destroy(g); g = GameObject.Instantiate(GetATank(), spawnPoint.position, Quaternion.identity, transform); g.GetComponent<Tank>().onDie += OnTankDie; OnTankSpwan(g.GetComponent<Tank>()); } /// <summary> /// 坦克阵亡时调用 /// </summary> /// <param name="value"></param> protected abstract void OnTankDie(int value); /// <summary> /// 坦克生成时调用 /// </summary> /// <param name="tank">生成的坦克类型</param> protected abstract void OnTankSpwan(Tank tank); }
using Android.Content; using Android.Support.CustomTabs; namespace Auth0.OidcClient { /// <summary> /// Implements browser integration using Chrome Custom Tabs. /// </summary> public class ChromeCustomTabsBrowser : AndroidBrowserBase { public ChromeCustomTabsBrowser(Context context = null) : base(context) { } protected override void OpenBrowser(Android.Net.Uri uri, Context context = null) { using (var builder = new CustomTabsIntent.Builder()) using (var customTabsIntent = builder.Build()) { customTabsIntent.Intent.AddFlags(ActivityFlags.NoHistory); if (IsNewTask) customTabsIntent.Intent.AddFlags(ActivityFlags.NewTask); customTabsIntent.LaunchUrl(context, uri); } } } }
namespace Triton.Game.Mapping { using ns25; using ns26; using System; using System.Collections.Generic; [Attribute38("EnterTheColiseumSpell")] public class EnterTheColiseumSpell : Spell { public EnterTheColiseumSpell(IntPtr address) : this(address, "EnterTheColiseumSpell") { } public EnterTheColiseumSpell(IntPtr address, string className) : base(address, className) { } public List<Card> FindSurvivors() { Class267<Card> class2 = base.method_14<Class267<Card>>("FindSurvivors", Array.Empty<object>()); if (class2 != null) { return class2.method_25(); } return null; } public Card GetTargetCardFromPowerTask(int index, PowerTask task) { object[] objArray1 = new object[] { index, task }; return base.method_14<Card>("GetTargetCardFromPowerTask", objArray1); } public void LiftCard(Card card) { object[] objArray1 = new object[] { card }; base.method_8("LiftCard", objArray1); } public void LowerCard(GameObject target, Vector3 finalPosition) { object[] objArray1 = new object[] { target, finalPosition }; base.method_8("LowerCard", objArray1); } public void OnAction(SpellStateType prevStateType) { object[] objArray1 = new object[] { prevStateType }; base.method_8("OnAction", objArray1); } public void PlayDustCloudSpell() { base.method_8("PlayDustCloudSpell", Array.Empty<object>()); } public void PlaySurvivorSpell(Card card) { object[] objArray1 = new object[] { card }; base.method_8("PlaySurvivorSpell", objArray1); } public float m_CameraShakeMagnitude { get { return base.method_2<float>("m_CameraShakeMagnitude"); } } public float m_DestroyMinionDelay { get { return base.method_2<float>("m_DestroyMinionDelay"); } } public Spell m_DustSpellPrefab { get { return base.method_3<Spell>("m_DustSpellPrefab"); } } public bool m_effectsPlaying { get { return base.method_2<bool>("m_effectsPlaying"); } } public Spell m_ImpactSpellPrefab { get { return base.method_3<Spell>("m_ImpactSpellPrefab"); } } public iTween.EaseType m_liftEaseType { get { return base.method_2<iTween.EaseType>("m_liftEaseType"); } } public float m_LiftOffset { get { return base.method_2<float>("m_LiftOffset"); } } public float m_LiftTime { get { return base.method_2<float>("m_LiftTime"); } } public iTween.EaseType m_lightFadeEaseType { get { return base.method_2<iTween.EaseType>("m_lightFadeEaseType"); } } public float m_LightingFadeTime { get { return base.method_2<float>("m_LightingFadeTime"); } } public float m_LowerDelay { get { return base.method_2<float>("m_LowerDelay"); } } public iTween.EaseType m_lowerEaseType { get { return base.method_2<iTween.EaseType>("m_lowerEaseType"); } } public float m_LowerOffset { get { return base.method_2<float>("m_LowerOffset"); } } public float m_LowerTime { get { return base.method_2<float>("m_LowerTime"); } } public int m_numSurvivorSpellsPlaying { get { return base.method_2<int>("m_numSurvivorSpellsPlaying"); } } public string m_RaiseSoundName { get { return base.method_4("m_RaiseSoundName"); } } public string m_SpellStartSoundPrefab { get { return base.method_4("m_SpellStartSoundPrefab"); } } public List<Card> m_survivorCards { get { Class267<Card> class2 = base.method_3<Class267<Card>>("m_survivorCards"); if (class2 != null) { return class2.method_25(); } return null; } } public float m_survivorLiftHeight { get { return base.method_2<float>("m_survivorLiftHeight"); } } public bool m_survivorsMeetInMiddle { get { return base.method_2<bool>("m_survivorsMeetInMiddle"); } } public Spell m_survivorSpellPrefab { get { return base.method_3<Spell>("m_survivorSpellPrefab"); } } } }
namespace IoUring { public enum TimeoutOptions : uint { /// <summary> /// Given timeout should be interpreted as relative value. /// </summary> Relative = 0, /// <summary> /// Given timeout should be interpreted as absolute value. /// </summary> Absolute = 1, // IORING_TIMEOUT_ABS } }
/* >>>----- Copyright (c) 2012 zformular -----> | | | Author: zformular | | E-mail: zformular@163.com | | Date: 2.4.2013 | | | ╰==========================================╯ */ using System; using System.Net.Mail; using System.Collections; using System.Configuration; using System.ComponentModel; using System.Collections.Generic; using System.Text.RegularExpressions; using ValueMail.Send.Infrastructure; using System.Xml.Linq; using ValueMail.Model; namespace ValueMail.Send { public class SendHelper { /// <summary> /// 包装发送的邮件的相关信息 /// </summary> /// <param name="model"></param> /// <returns></returns> public static MailMessage PacketMessage(SendModel model) { var mail = new MailMessage(); mail.Subject = model.Subject; mail.Body = model.Body; mail.BodyEncoding = System.Text.Encoding.UTF8; mail.IsBodyHtml = true; mail.Priority = model.Priority; if (model.To != null) foreach (var item in model.To) mail.To.Add(item); if (model.Attachments != null) foreach (var item in model.Attachments) mail.Attachments.Add(item); return mail; } /// <summary> /// 获得邮件服务器参数 /// </summary> /// <param name="address"></param> /// <returns></returns> public static HostModel GetHost(String address) { return MailHelper.GetHost(address).SmtpHost; } } }
using System.Data; using TLF.Framework.Config; namespace TLF.Framework.ControlLibrary { /// <summary> /// /// </summary> /// <remarks> /// 2008-12-16 최초생성 : 황준혁 /// 변경내역 /// /// </remarks> public partial class PCheckedListBoxEdit : DevExpress.XtraEditors.CheckedListBoxControl { /////////////////////////////////////////////////////////////////////////////////////////////// // Constructor & Global Instance /////////////////////////////////////////////////////////////////////////////////////////////// #region :: 생성자 :: /// <summary> /// Checked List Box Control을 생성합니다. /// </summary> public PCheckedListBoxEdit() { InitializeComponent(); } #endregion /////////////////////////////////////////////////////////////////////////////////////////////// // Method(Public) /////////////////////////////////////////////////////////////////////////////////////////////// #region :: InitData(+1 Overloading) :: CheckedListBoxEdit에 값을 넣습니다. /// <summary> /// CheckedListBoxEdit에 값을 넣습니다. /// </summary> /// <param name="valueList">Value가 될 배열</param> /// <param name="displayList">Text가 될 배열</param> /// <remarks> /// 2008-12-16 최초생성 : 황준혁 /// 변경내역 /// /// </remarks> public void InitData(object[] valueList, string[] displayList) { if (valueList.Length != displayList.Length) return; using (DataTable dt = new DataTable()) { dt.Columns.Add(AppConfig.VALUEMEMBER); dt.Columns.Add(AppConfig.DISPLAYMEMBER); for (int idx = 0; idx < valueList.Length; idx++) { DataRow dr = dt.NewRow(); dr[AppConfig.VALUEMEMBER] = valueList[idx]; dr[AppConfig.DISPLAYMEMBER] = displayList[idx]; dt.Rows.Add(dr); } this.InitData(dt, AppConfig.VALUEMEMBER, AppConfig.DISPLAYMEMBER); } } /// <summary> /// CheckedListBoxEdit에 값을 넣습니다. /// </summary> /// <param name="dt">Datasource 가 될 DataTable</param> /// <param name="valueMember">ValueMember 명</param> /// <param name="displayMember">DisplayMemeber 명</param> /// <remarks> /// 2008-12-16 최초생성 : 황준혁 /// 변경내역 /// /// </remarks> public void InitData(DataTable dt, string valueMember, string displayMember) { this.DataSource = dt; this.ValueMember = valueMember; this.DisplayMember = displayMember; } #endregion } }
using UnityEngine; using UnityEditor; using YoukiaUnity.Graphics; using YoukiaUnity.Graphics.FastShadowProjector; [CustomEditor(typeof(GraphicsManager))] public class GraphicsManagerEditor : UnityEditor.Editor { static Color green = new Color(0.4f, 1, 0.8f, 1); public override void OnInspectorGUI() { GraphicsManager mgr = (GraphicsManager)target; // base.OnInspectorGUI(); EditorGUILayout.HelpBox("视效管理器,请保持游戏中常驻,请勿修改子节点和内部数据", MessageType.Warning); GUI.color = green; if (Application.isPlaying) { string cameraName = mgr.CurrentSubCamera == null ? "无" : mgr.CurrentSubCamera.gameObject.name; EditorGUILayout.HelpBox("当期渲染摄像机:" + cameraName + " FPS:" + mgr.FPS, MessageType.Info); // EditorGUILayout.HelpBox("当前模式:"+ mgr.CurrentRenderMode, MessageType.Info); } else { EditorGUILayout.HelpBox("编辑器模式中", MessageType.Info); } int GraphicsQuality = EditorGUILayout.IntSlider(new GUIContent("当前视效等级", "Unity预设 Quality Level "), mgr.GraphicsQuality, 0, QualitySettings.names.Length - 1); GraphicsManager.RtSize finalSize = (GraphicsManager.RtSize)EditorGUILayout.EnumPopup(new GUIContent("显示分辨率", "相对屏幕分辨率大小的1,0.5,0.25"), mgr.FinalDrawRtSize); // bool fog = EditorGUILayout.Toggle(new GUIContent("大气雾效", "天空盒颜色作为雾效"), mgr.Fog); float CameraNearClip = EditorGUILayout.Slider("摄像机近裁面:", mgr.CameraNearClip, 0f, 100); // float CameraMiddleClip = EditorGUILayout.Slider("摄像机近远景分界:", mgr.CameraMiddleClip, CameraNearClip, 10000); float CameraFarClip = EditorGUILayout.Slider("摄像机远裁面:", mgr.CameraFarClip, mgr.CameraNearClip, 20000); GlobalProjectorManager.ShadowType ShadowType = (GlobalProjectorManager.ShadowType) EditorGUILayout.EnumPopup(new GUIContent("阴影类型", "帧数大杀器!"), mgr.ShadowType); GlobalProjectorManager.ShadowResolutions ShadowResolution = (GlobalProjectorManager.ShadowResolutions)EditorGUILayout.EnumPopup(new GUIContent("阴影类型", "帧数大杀器!"), mgr.ShadowResolution); // bool DistantView = EditorGUILayout.Toggle(new GUIContent("远景绘制", "不绘制远景能提高帧数"), mgr.ShowLandscape); bool AlwayReDrawFarCamera = false; GraphicsManager.RtSize Size = GraphicsManager.RtSize.Full; //实际游戏配置表中读取,不直接在此设置 float FogDestance = EditorGUILayout.Slider("大气雾距离:", mgr.FogDestance, 0f, 100); float FogDestiy = EditorGUILayout.Slider("大气雾密度:", mgr.FogDestiy, 0f, 100); if (GUI.changed) { EditorUtility.SetDirty(target); // mgr.Fog = fog; mgr.ShadowType = ShadowType; mgr.ShadowResolution = ShadowResolution; // mgr.ShowLandscape = DistantView; mgr.AlwayReDrawFarTexture = AlwayReDrawFarCamera; mgr.FogDestiy = FogDestiy; mgr.FogDestance = FogDestance; mgr.CameraNearClip = CameraNearClip; // mgr.CameraMiddleClip = CameraMiddleClip; mgr.CameraFarClip = CameraFarClip; mgr.GraphicsQuality = GraphicsQuality; mgr.FinalDrawRtSize = finalSize; } } }
using System; using System.Data.Entity; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Web.Areas.Admin.ViewModels.Todoes; using Web.Data; using Web.Dtos; using Web.Identity; using Web.Models; using Web.ViewModels.Reviews; namespace Web.Areas.Admin.Controllers { public class TodoesController : Controller { private readonly ApplicationDbContext _context; private readonly ICurrentUser _currentUser; public TodoesController(ApplicationDbContext context, ICurrentUser currentUser) { _context = context; _currentUser = currentUser; } // GET: Admin/Todoes public ActionResult Index() { var todos1 = _context.Todos .Include(t => t.AssignedTo) .Include(t => t.Sco) .Include(t => t.CourseSco) .Include(t => t.CreatedBy) .Include(t => t.TodoType) //.Where(f => f.FixedDate == null) .OrderBy(d => d.FixedDate) .ThenBy(d => d.CreateDate) .ToList(); var todos = todos1.Select(t => new TodoViewModel() { Id = t.Id, AssignedTo = t.AssignedTo.FirstName + " " + t.AssignedTo.LastName, Body = t.Body, AssignedToId = t.AssignedToId, Subject = t.Subject, TodoType = t.TodoType.Subject, CreateDate = t.CreateDate.ToString("MMM-dd-yyyy"), FixedDate = t.FixedDate, FixedDateString = t.FixedDate > DateTime.MinValue ? t.FixedDate.ToString("MMM-dd-yyyy") : "", Slide = t.Slide ?? "", ScoTitle = t.ScoTitle, CreatedById = t.CreatedById, CurrentUserId = _currentUser.User.Id }); return View(todos); } // GET: Admin/Todoes/Details/5 public async Task<ActionResult> Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Todo todo = await _context.Todos.FindAsync(id); if (todo == null) { return HttpNotFound(); } return View(todo); } // GET: Admin/Todoes/Create public ActionResult Create() { var assignedToList = _context.Users.ToList().Select(u => new UserLfNameDto { Id=u.Id, Name= u.LfName }); ViewBag.AssignedToId = new SelectList(assignedToList, "Id", "Name"); ViewBag.CourseScoId = new SelectList(_context.CourseScos, "Id", "Title"); ViewBag.CreatedById = new SelectList(_context.Users.OrderBy(u => u.FullName), "Id", "FullName"); ViewBag.TodoTypeId = new SelectList(_context.TodoTypes, "Id", "Subject"); var vm = new Todo(); { //Todo Remove Magic string vm.TodoTypeId = 1; }; return View(vm); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create([Bind(Include = "Id,TodoTypeId,Subject,Body,AssignedToId,Slide,Resource,CourseScoId")] Todo todo) { todo.CreateDate = DateTime.UtcNow; todo.CreatedById = _currentUser.User.Id; todo.AssignedToId = todo.AssignedToId; if (ModelState.IsValid) { _context.Todos.Add(todo); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } var assignedToList = _context.Users.ToList().Select(u => new UserLfNameDto { Id = u.Id, Name = u.LfName }); ViewBag.AssignedToIdList = new SelectList(assignedToList, "Id", "Name"); ViewBag.CourseScoId = new SelectList(_context.CourseScos, "Id", "Title", todo.ScoId); ViewBag.CreatedById = new SelectList(_context.Users, "Id", "FirstName", todo.CreatedById); ViewBag.TodoTypeId = new SelectList(_context.TodoTypes, "Id", "Subject", todo.TodoTypeId); return View(todo); } // GET: Admin/Todoes/Edit/5 public async Task<ActionResult> Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Todo todo = await _context.Todos.FindAsync(id); if (todo == null) { return HttpNotFound(); } ViewBag.AssignedToId = new SelectList(_context.Users, "Id", "FirstName", todo.AssignedToId); ViewBag.CourseScoId = new SelectList(_context.CourseScos, "Id", "Title", todo.ScoId); ViewBag.CreatedById = new SelectList(_context.Users, "Id", "FirstName", todo.CreatedById); ViewBag.TodoTypeId = new SelectList(_context.TodoTypes, "Id", "Subject", todo.TodoTypeId); return View(todo); } // POST: Admin/Todoes/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "Id,TodoTypeId,Subject,Body,CreatedById,CreateDate,FixNote,AssignedToId,FixedDate,IsApproved,ApprovedDate,ApprovedBy,Slide,Resource,CourseScoId")] Todo todo) { if (ModelState.IsValid) { _context.Entry(todo).State = EntityState.Modified; await _context.SaveChangesAsync(); return RedirectToAction("Index"); } ViewBag.AssignedToId = new SelectList(_context.Users, "Id", "FirstName", todo.AssignedToId); ViewBag.CourseScoId = new SelectList(_context.CourseScos, "Id", "Title", todo.ScoId); ViewBag.CreatedById = new SelectList(_context.Users, "Id", "FirstName", todo.CreatedById); ViewBag.TodoTypeId = new SelectList(_context.TodoTypes, "Id", "Subject", todo.TodoTypeId); return View(todo); } // GET: Admin/Todoes/Delete/5 public async Task<ActionResult> Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Todo todo = await _context.Todos.FindAsync(id); if (todo == null) { return HttpNotFound(); } return View(todo); } // POST: Admin/Todoes/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<ActionResult> DeleteConfirmed(int id) { Todo todo = await _context.Todos.FindAsync(id); _context.Todos.Remove(todo); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } public ActionResult Fix(int id, int? scoId) { var todo = _context.Todos.Find(id); var courseModule = _context.Scos.Find(scoId); var vm = new FixReviewNoteViewModel { Id = todo.Id, ScoId = todo.ScoId ?? -1, Slide = todo.Slide, Subject = todo.Subject, Details = todo.Body, Resource = todo.Resource, FixNote = todo.FixNote, CourseScoName = todo.ScoTitle, }; return View(vm); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Fix(FixReviewNoteViewModel form, HttpPostedFileBase file) { if (ModelState.IsValid) { var originalReviewNote = _context.Todos.Find(form.Id); originalReviewNote.FixNote = form.FixNote; originalReviewNote.AssignedToId = _currentUser.User.Id; originalReviewNote.FixedDate = DateTime.UtcNow; _context.SaveChanges(); return RedirectToAction("Index", "Todoes"); } return View(form); } public ActionResult Approve(int id) { var note = _context.Todos.Find(id); note.IsApproved = true; note.ApprovedDate = DateTime.UtcNow; note.ApprovedBy = _currentUser.User.Id; _context.SaveChanges(); return RedirectToAction("Index", "Todoes"); } public ActionResult UnApprove(int id) { var note = _context.Todos.Find(id); note.IsApproved = false; note.ApprovedDate = DateTime.UtcNow; note.ApprovedBy = _currentUser.User.Id; _context.SaveChanges(); return RedirectToAction("Index", "Todoes"); } protected override void Dispose(bool disposing) { if (disposing) { _context.Dispose(); } base.Dispose(disposing); } } }
#region Copyright (C) // --------------------------------------------------------------------------------------------------------------- // <copyright file="HiddenFormToAcceptCloseMessage.cs" company="Smurf-IV"> // // Copyright (C) 2012 Simon Coghlan (aka Smurf-IV) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> // <summary> // Url: http://amalgam.codeplex.com // Email: http://www.codeplex.com/site/users/view/smurfiv // </summary> // -------------------------------------------------------------------------------------------------------------------- #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Input; using AmalgamClientTray.CBFS; using AmalgamClientTray.ClientForms; using NLog; namespace AmalgamClientTray.GUI { /// <summary> /// Interaction logic for HiddenFormToAcceptCloseMessage.xaml /// </summary> public partial class HiddenFormToAcceptCloseMessage : Window { static private readonly Logger Log = LogManager.GetCurrentClassLogger(); public HiddenFormToAcceptCloseMessage() { InitializeComponent(); } protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); try { ClientConfigDetails csd; bool allowStart = Management.ReadConfigDetails(out csd); if (allowStart) { if (csd == null) throw new ExecutionEngineException("ClientConfigDetails failed to be created"); if ( csd.SharesToRestore != null ) foreach (ClientShareDetail shareDetail in csd.SharesToRestore) { HandleMappingThread newMapping = new HandleMappingThread(shareDetail); Handlers.ClientMappings[shareDetail.DriveLetter] = newMapping; newMapping.Start(); } } } catch (Exception ex) { Log.ErrorException("OnInitialized:\n", ex); Application.Current.Shutdown(); } } protected override void OnClosing(CancelEventArgs e) { notificationIcon.Visibility = Visibility.Hidden; try { if (Handlers.ClientMappings != null) foreach (KeyValuePair<string, HandleMappingThread> keyValuePair in Handlers.ClientMappings .Where(keyValuePair => keyValuePair.Value != null) ) { keyValuePair.Value.Stop(); } } catch (Exception ex) { Log.ErrorException("OnClosing:\n", ex); } finally { Application.Current.Shutdown(); } } #region Menu clickers private void OnNotificationAreaIconDoubleClick(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { Open(); } } private void OnMenuItemOpenClick(object sender, EventArgs e) { Open(); } private void Open() { new Management().ShowDialog(); } private void OnMenuItemExitClick(object sender, EventArgs e) { Close(); } private void OnMenuItemAboutClick(object sender, EventArgs e) { new WPFAboutBox1(null).ShowDialog(); } #endregion } }
using System; using ScrollsModLoader.Interfaces; using UnityEngine; using Mono.Cecil; using System.Collections.Generic; using System.Text; using System.Linq; namespace ChatFilter { public class ChatFilter : BaseMod { private const string INFO_COLOR = "aa803f"; private const string FILTER_COLOR = "fde50d"; private List<string> filteredTexts; private List<string> highlightedTexts; private List<string> highlightedCards; private bool filterLibrary; private string[] commands = { "/filter", "/f", "/resetfilter", "/rf", "/highlight", "/hl", "/resethighlight", "/rhl", "/filterlibrary" }; public ChatFilter() { filteredTexts = new List<string>(); highlightedTexts = new List<string>(); highlightedCards = new List<string>(); filterLibrary = false; } public static string GetName() { return "ChatFilter"; } public static int GetVersion() { return 3; } public static MethodDefinition[] GetHooks(TypeDefinitionCollection scrollsTypes, int version) { try { return new MethodDefinition[] { scrollsTypes["ChatRooms"].Methods.GetMethod("ChatMessage", new Type[]{ typeof(RoomChatMessageMessage) }), scrollsTypes["Communicator"].Methods.GetMethod("sendRequest", new Type[]{ typeof(Message) }) }; } catch { return new MethodDefinition[] {}; } } public override void BeforeInvoke(InvocationInfo info) { } public override void AfterInvoke(InvocationInfo info, ref object returnValue) { } public override bool WantsToReplace(InvocationInfo info) { if (info.targetMethod.Equals("sendRequest") && info.arguments[0] is RoomChatMessageMessage) { RoomChatMessageMessage msg = (RoomChatMessageMessage) info.arguments[0]; return IsCommand(msg.text); } else if (info.targetMethod.Equals("ChatMessage")) { RoomChatMessageMessage msg = (RoomChatMessageMessage) info.arguments[0]; msg.text = ColorizeText(msg.text); if (filteredTexts.Count == 0 || msg.from.ToLower() == App.MyProfile.ProfileInfo.name.ToLower() || msg.roomName.ToLower().StartsWith("trade-") || msg.from == "Scrolls" || msg.from == "ChatFilter") { // don't filter my messages return false; } bool hideMessage = filteredTexts.Count > 0 || filterLibrary; foreach (String card in highlightedCards) { if (msg.text.ToLower().Contains(card)) { hideMessage = false; } } foreach (String filteredText in filteredTexts) { if (msg.text.ToLower().Contains(filteredText)) { if (filterLibrary && !hideMessage) { return false; } else if (!filterLibrary) { return false; } else if (filterLibrary && hideMessage) { return true; } } } return hideMessage || filteredTexts.Count != 0; } return false; } public override void ReplaceMethod(InvocationInfo info, out object returnValue) { returnValue = null; if (info.targetMethod.Equals("sendRequest")) { if (info.arguments[0] is RoomChatMessageMessage) { RoomChatMessageMessage msg = (RoomChatMessageMessage) info.arguments[0]; if (msg.IsCommand("/filter") || msg.IsCommand("/f")) { String[] splitted = msg.text.Split(new char[] {' '}, 2); if (splitted.Length == 2) { AddFilter(splitted[1].ToLower()); SendMessage("Current filters: " + string.Join(", ", filteredTexts.ToArray())); } } else if (msg.IsCommand("/resetfilter") || msg.IsCommand("/rf")) { filteredTexts.Clear(); SendMessage("Filters have been reseted"); } else if (msg.IsCommand("/highlight") || msg.IsCommand("/hl")) { String[] splitted = msg.text.Split(new char[] {' '}, 2); if (splitted.Length == 2) { AddHighlight(splitted[1].ToLower()); SendMessage("Current highlights: " + string.Join(", ", highlightedTexts.ToArray())); } } else if (msg.IsCommand("/resethighlight") || msg.IsCommand("/rhl")) { highlightedTexts.Clear(); SendMessage("Highlights have been reseted"); } else if (msg.IsCommand("/filterlibrary")) { String[] splitted = msg.text.Split(new char[] {' '}, 2); int count = 0; if (splitted.Length == 2) { try { count = byte.Parse(splitted[1]); } catch (FormatException) { SendMessage("Incorrect parameter!"); } } LibraryManager libraryManager = new LibraryManager(); libraryManager.LoadLibrary(() => { Console.WriteLine("Loaded"); var cards = libraryManager.Cards.GroupBy(c => c.getName()).ToDictionary(grp => grp.Key, grp => grp.ToList()); highlightedCards.Clear(); foreach (var card in cards) { if (card.Value.Count > count) { highlightedCards.Add(card.Key.ToLower()); } } filterLibrary = true; SendMessage("Library filter activated!"); }); } } } } protected bool IsCommand(string command) { foreach (string c in commands) { if (command.StartsWith(c)) { return true; } } return false; } protected void SendMessage(string message) { RoomChatMessageMessage msg = new RoomChatMessageMessage(); msg.from = GetName(); msg.text = message.Colorize(INFO_COLOR); msg.roomName = App.ArenaChat.ChatRooms.GetCurrentRoom().name; App.ChatUI.handleMessage(msg); App.ArenaChat.ChatRooms.ChatMessage(msg); } public string ColorizeText(string text) { foreach (String filteredText in filteredTexts) { text = text.Colorize(filteredText, FILTER_COLOR); } foreach (String highlightedText in highlightedTexts) { text = text.Colorize(highlightedText, FILTER_COLOR); } foreach (String card in highlightedCards) { text = text.Colorize(card, FILTER_COLOR); } return text; } public void AddFilter(string text) { filteredTexts.Add(text); } public void AddHighlight(string text) { highlightedTexts.Add(text); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief UI。ボタン。 */ /** NUi */ namespace NUi { /** Button_Base */ public abstract class Button_Base : NDeleter.DeleteItem_Base , NEventPlate.OnOverCallBack_Base , NUi.OnTargetCallBack_Base { /** [Button_Base]コールバック。クリック。 */ public delegate void CallBack_Click(int a_id); /** s_down_instance */ protected static Button_Base s_down_instance = null; /** deleter */ protected NDeleter.Deleter deleter; /** 矩形。 */ protected NRender2D.Rect2D_R<int> rect; /** drawpriority */ protected long drawpriority; /** eventplate */ protected NEventPlate.Item eventplate; /** callback_click */ protected CallBack_Click callback_click; protected int callback_id; /** is_onover */ protected bool is_onover; /** down_flag */ protected bool down_flag; /** lock_flag */ protected bool lock_flag; /** clip_flag */ protected bool clip_flag; /** clip_rect */ protected NRender2D.Rect2D_R<int> clip_rect; /** visible_flag */ protected bool visible_flag; /** event_request */ protected int event_request; /** mode */ protected Button_Mode mode; /** constructor */ public Button_Base(NDeleter.Deleter a_deleter,NRender2D.State2D a_state,long a_drawpriority,CallBack_Click a_callback_click,int a_callback_id) { //deleter this.deleter = new NDeleter.Deleter(); //rect this.rect.Set(0,0,0,0); //drawpriority this.drawpriority = a_drawpriority; //eventplate this.eventplate = new NEventPlate.Item(this.deleter,NEventPlate.EventType.Button,this.drawpriority); this.eventplate.SetOnOverCallBack(this); //callback_click this.callback_click = a_callback_click; this.callback_id = a_callback_id; //is_onover this.is_onover = false; //down_flag this.down_flag = false; //lock_flag this.lock_flag = false; //clip_flag this.clip_flag = false; //clip_rect this.clip_rect.Set(0,0,0,0); //visible_flag this.visible_flag = true; //event_request this.event_request = 0; //mode this.mode = Button_Mode.Normal; //削除管理。 if(a_deleter != null){ a_deleter.Register(this); } } /** [Button_Base]コールバック。矩形変更。 */ protected abstract void OnChangeRect(); /** [Button_Base]コールバック。モード変更。 */ protected abstract void OnChangeMode(); /** [Button_Base]コールバック。クリップフラグ変更。 */ protected abstract void OnChangeClipFlag(); /** [Button_Base]コールバック。クリップ矩形変更。 */ protected abstract void OnChangeClipRect(); /** [Button_Base]コールバック。表示フラグ変更。 */ protected abstract void OnChangeVisibleFlag(); /** [Button_Base]コールバック。描画プライオリティ変更。 */ protected abstract void OnChangeDrawPriority(); /** 削除。 */ public void Delete() { this.deleter.DeleteAll(); //ターゲット解除。 NUi.Ui.GetInstance().UnSetTargetRequest(this); //ダウン解除。 if(Button_Base.s_down_instance == this){ Button_Base.s_down_instance = null; } } /** モード。設定。 */ private void SetMode(Button_Mode a_mode) { if(this.mode != a_mode){ this.mode = a_mode; //コールバック。モード変更。 this.OnChangeMode(); } } /** 描画プライオリティ。設定。 */ public void SetDrawPriority(long a_drawpriority) { if(this.drawpriority != a_drawpriority){ this.eventplate.SetPriority(a_drawpriority); //コールバック。描画プライオリティ変更。 this.OnChangeDrawPriority(); } } /** ロック。設定。 */ public void SetLock(bool a_flag) { if(this.lock_flag != a_flag){ this.lock_flag = a_flag; if(this.lock_flag == true){ this.SetMode(Button_Mode.Lock); }else{ if(this.is_onover == true){ this.SetMode(Button_Mode.On); }else{ this.SetMode(Button_Mode.Normal); } } } } /** クリップ。設定。 */ public void SetClip(bool a_flag) { if(this.clip_flag != a_flag){ this.clip_flag = a_flag; this.eventplate.SetClip(a_flag); //コールバック。クリップフラグ変更。 this.OnChangeClipFlag(); } } /** クリップ矩形。設定。 */ public void SetClipRect(ref NRender2D.Rect2D_R<int> a_rect) { this.clip_rect = a_rect; this.eventplate.SetClipRect(ref a_rect); //コールバック。クリップ矩形変更。 this.OnChangeClipRect(); } /** クリップ矩形。設定。 */ public void SetClipRect(int a_x,int a_y,int a_w,int a_h) { this.clip_rect.Set(a_x,a_y,a_w,a_h); this.eventplate.SetClipRect(a_x,a_y,a_w,a_h); //コールバック。クリップ矩形変更。 this.OnChangeClipRect(); } /** 矩形。設定。 */ public void SetRect(ref NRender2D.Rect2D_R<int> a_rect) { this.rect = a_rect; this.eventplate.SetRect(ref a_rect); //コールバック。矩形変更。 this.OnChangeRect(); } /** 矩形。設定。 */ public void SetRect(int a_x,int a_y,int a_w,int a_h) { this.rect.Set(a_x,a_y,a_w,a_h); this.eventplate.SetRect(a_x,a_y,a_w,a_h); //コールバック。矩形変更。 this.OnChangeRect(); } /** 矩形。設定。 */ public void SetX(int a_x) { this.rect.x = a_x; this.eventplate.SetX(a_x); //コールバック。矩形変更。 this.OnChangeRect(); } /** 矩形。設定。 */ public void SetY(int a_y) { this.rect.y = a_y; this.eventplate.SetY(a_y); //コールバック。矩形変更。 this.OnChangeRect(); } /** 矩形。設定。 */ public void SetW(int a_w) { this.rect.w = a_w; this.eventplate.SetW(a_w); //コールバック。矩形変更。 this.OnChangeRect(); } /** 矩形。設定。 */ public void SetH(int a_h) { this.rect.h = a_h; this.eventplate.SetH(a_h); //コールバック。矩形変更。 this.OnChangeRect(); } /** 矩形。取得。 */ public int GetX() { return this.rect.x; } /** 矩形。取得。 */ public int GetY() { return this.rect.y; } /** 矩形。取得。 */ public int GetW() { return this.rect.w; } /** 矩形。取得。 */ public int GetH() { return this.rect.h; } /** 表示。設定。 */ public void SetVisible(bool a_flag) { if(this.visible_flag != a_flag){ this.visible_flag = a_flag; this.eventplate.SetEnable(a_flag); //コールバック。表示フラグ変更。 this.OnChangeVisibleFlag(); } } /** [NEventPlate.OnOverCallBack_Base]OnOverEnter */ public void OnOverEnter(int a_value) { Tool.Log("Button_Base","OnOverEnter : " + a_value.ToString()); this.is_onover = true; //ターゲット登録。 Ui.GetInstance().SetTargetRequest(this); } /** [NEventPlate.OnOverCallBack_Base]OnOverLeave */ public void OnOverLeave(int a_value) { Tool.Log("Button_Base","OnOverLeave : " + a_value.ToString()); this.is_onover = false; } /** オンオーバー。取得。 */ public bool IsOnOver() { return this.is_onover; } /** クリックイベント。発行。 */ public void ClickEventRequest() { if((this.lock_flag == false)&&(this.visible_flag == true)){ //イベントリクエスト。 this.event_request = 13; //ターゲット登録。 Ui.GetInstance().SetTargetRequest(this); //ダウンキャンセル。 this.down_flag = false; if(Button_Base.s_down_instance == this){ Button_Base.s_down_instance = null; } } } /** [NUi.OnTargetCallBack_Base]OnTarget */ public void OnTarget() { if(this.lock_flag == true){ //ロック中。 //ターゲット解除。 if(this.is_onover == false){ Ui.GetInstance().UnSetTargetRequest(this); } //ダウンキャンセル。 this.down_flag = false; if(Button_Base.s_down_instance == this){ Button_Base.s_down_instance = null; } //リクエストキャンセル。 this.event_request = 0; this.SetMode(Button_Mode.Lock); }else if(this.visible_flag == false){ //非表示。 //ターゲット解除。 if(this.is_onover == false){ Ui.GetInstance().UnSetTargetRequest(this); } //ダウンキャンセル。 this.down_flag = false; if(Button_Base.s_down_instance == this){ Button_Base.s_down_instance = null; } //リクエストキャンセル。 this.event_request = 0; this.SetMode(Button_Mode.Normal); }else if(this.event_request > 0){ //イベント中。 //ダウンキャンセル。 this.down_flag = false; if(Button_Base.s_down_instance == this){ Button_Base.s_down_instance = null; } this.event_request--; if(this.event_request == 0){ //ターゲット解除。 Ui.GetInstance().UnSetTargetRequest(this); //コールバック。 if(this.callback_click != null){ this.callback_click(this.callback_id); } if(this.is_onover == true){ this.SetMode(Button_Mode.On); }else{ this.SetMode(Button_Mode.Normal); } }else{ this.SetMode(Button_Mode.Down); } }else{ if((this.is_onover == true)&&(this.down_flag == false)&&(NInput.Mouse.GetInstance().left.down == true)){ //ダウン。 //ダウン開始。 this.down_flag = true; Button_Base.s_down_instance = this; this.SetMode(Button_Mode.Down); }else if((this.down_flag == true)&&(NInput.Mouse.GetInstance().left.on == false)){ //アップ。 //ダウンキャンセル。 this.down_flag = false; if(Button_Base.s_down_instance == this){ Button_Base.s_down_instance = null; } //コールバック。 if(this.is_onover == true){ if(this.callback_click != null){ this.callback_click(this.callback_id); } } if(this.is_onover == true){ this.SetMode(Button_Mode.On); }else{ this.SetMode(Button_Mode.Normal); } }else if((this.is_onover == true)&&(this.down_flag == true)){ //ダウン中オーバー中。 this.SetMode(Button_Mode.Down); }else if(this.is_onover == true){ //オーバー中。 if(Button_Base.s_down_instance == null){ this.SetMode(Button_Mode.On); }else{ this.SetMode(Button_Mode.Normal); } }else if(this.down_flag == true){ //範囲外ダウン中。 this.SetMode(Button_Mode.On); }else{ //ターゲット解除。 Ui.GetInstance().UnSetTargetRequest(this); this.SetMode(Button_Mode.Normal); } } } } }
using System; using System.Runtime.InteropServices; [Serializable] public struct IntValue { public int Value; public int Max; public int Min; //public int Random { get { return Value + MasterScript.rand.Next(Min, Max); } } public float RatioValueMax { get { return Max < 1e-5f ? 0f : ((float)Value) / Max; } } public bool IsMax { get { return Value == Max; } } public void Set(int value) { if (value < Min) value = Min; else if (value > Max) value = Max; Value = value; } public bool Set(ref IntValue info) { int value = info.Value; bool res = value != Value || info.Max != Max || info.Min != Min; if (res) { Max = info.Max; Min = info.Min; Set(value); } return res; } } [Serializable] public struct FloatRange { public float Max; public float Min; } [Serializable] public struct FloatValue { public float Value; public float Max; public float Min; const float epsEquals = 1e-5f; const float negEpsEquals = -1e-5f; public override string ToString() { return string.Format("Health: value={0} Min={1} Max={2}", Value, Min, Max); } public float RatioValueMinMax { get { return Clamp01((Max - Min) < epsEquals ? 0f : (Value - Min) / (Max - Min)); } } public float RatioValueZeroMax { get { return Clamp01(Max < epsEquals ? 0f : Value / Max); } } //public float RatioValueMax { get { return Max < epsEquals ? 0f : Value / Max; } } public bool IsMax { get { return (Value - Max) < epsEquals && (Value - Max) > negEpsEquals; } } public bool IsMin { get { return (Value - Min) < epsEquals && (Value - Min) > negEpsEquals; } } public void Set(float value) { Value = Clamp(value); } public float Clamp(float value) { if (value < Min) value = Min; else if (value > Max) value = Max; return value; } public bool PercentLessOrEqualValue(float percentAbs) { percentAbs = Math.Abs(percentAbs) * 0.01f; float delta = Math.Abs(Max - Min); float val = delta * percentAbs; return val >= Value || ValuesEqual(val, Value); } public float Clamp01(float value) { if (value < 0f) value = 0f; else if (value > 1f) value = 1f; return value; } public float InverseClamp01(float value) { return 1f - Clamp01(value); } public float ClosestClamp01(float value) { if (value < Min) return 1f; if (value > Max) return 0f; float delta = Max - Min; if (ValuesEqual(delta, 0f)) { if (ValuesEqual(value, 0f)) return 1f; return 0f; } return (Max - value) / (Max - Min); } bool ValuesEqual(float val1, float val2) { return (val1 - val2) <= epsEquals && (val1 - val2) >= negEpsEquals; } public bool ValueEqual(float value) { return ValuesEqual(value, Value); } public static implicit operator float(FloatValue value) { return value.Value; } public float Normalize() { float delta = Max - Min; if (delta < epsEquals && epsEquals > negEpsEquals) return 0f; return Value / delta; } public bool Set(ref FloatValue info) { float value = info.Value; bool res = (value - Value) >= epsEquals || (value - Value) <= negEpsEquals || (info.Max - Max) >= epsEquals || (info.Max - Max) <= negEpsEquals || (info.Min - Min) >= epsEquals || (info.Min - Min) <= negEpsEquals; if (res) { Max = info.Max; Min = info.Min; Set(value); } return res; } }
using UnityEngine; using System.Collections; public class ShootBullets : MonoBehaviour { //properties go here public Vector3 size = new Vector3(0.25f,0.25f,0.25f); public float Speed = 300; //how fast the bullet moves public Rigidbody Projectile; //what he shoots, Note; must be set in Unity public Transform muzzlePoint; //location of object he shoots from...gun public Transform muzzlePoint2; //location of object he shoots from...gun public float Stimer = 8; // Update is called once per frame void Update () { Stimer -= Time.deltaTime; if (Stimer <= 1) { Shoot (); Stimer = 8; } if (Stimer >= 4 && Stimer <= 5) { Shoot2 (); Stimer = 4; } } void Shoot() { //creates projectiles Rigidbody pewpew; pewpew = Instantiate (Projectile, muzzlePoint.position, muzzlePoint.rotation) as Rigidbody; pewpew.velocity = muzzlePoint.forward * Time.deltaTime * Speed; pewpew.transform.localScale = size; pewpew.GetComponent<SteeringBehaviours> ().maxSpeed = 28; } void Shoot2() { Rigidbody pewpew2; pewpew2 = Instantiate(Projectile, muzzlePoint2.position, muzzlePoint2.rotation) as Rigidbody; pewpew2.velocity = muzzlePoint2.forward * Time.deltaTime * Speed; pewpew2.transform.localScale = size; pewpew2.GetComponent<SteeringBehaviours> ().maxSpeed = 20; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine.Events; namespace COM3D2.SimpleUI { public interface IGenericDropdown : IControl, IObjectControlValue { IGenericDropdown ClearChoices(); IGenericDropdown Choice<T>(T value, string text="", string selected=""); IGenericDropdown RemoveChoice<T>(T value); T GetValue<T>(); IGenericDropdown SetValue<T>(T value); bool UpdateTextOnValue { get; set; } IGenericDropdown SetUpdateTextOnValuechange(bool value); } public interface IDropdown: IControl, IStringControlValue { IEnumerable<string> Choices { get; set; } } }
using System; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Animation; namespace PICSimulator.View { /// <summary> /// Interaction logic for ChangeMarkTextBlock.xaml /// </summary> public partial class ChangeMarkTextBlock : UserControl { public string Text { get { return box.Text; } set { if (value != box.Text) { box.Text = value; Animate(); } } } public Color _Color = Colors.Transparent; public Color Color { get { return _Color; } set { panel.Background = new SolidColorBrush(value); _Color = value; } } public ChangeMarkTextBlock() { InitializeComponent(); } private void Animate() { panel.Background = new SolidColorBrush(Color); var anim = new ColorAnimation() { From = Colors.Red, To = Color, Duration = TimeSpan.FromMilliseconds(1500), }; panel.Background.BeginAnimation(SolidColorBrush.ColorProperty, anim); } } }
using AshlinCustomerEnquiry.supportingClasses.brightpearl; using System.IO; using System.Net; namespace AshlinCustomerEnquiry.supportingClasses.asi { /* * A class that connect to ASI and retrieve company informaiton */ [System.Serializable] public class Asi { // fields for web request private WebRequest request; private HttpWebResponse response; // field for storing auth token private readonly string token; /* constructor that retrieve the auth token in order to do the request after */ public Asi() { // field for login credentials string asi; string username; string password; // get credentials first from database using (var connection = new System.Data.SqlClient.SqlConnection(Properties.Settings.Default.ASCMcs)) { // [0] username, [1] password, [2] ASI number var command = new System.Data.SqlClient.SqlCommand("SELECT Username, Password, Field1_Value FROM ASCM_Credentials WHERE Source = 'ASI API'", connection); connection.Open(); var reader = command.ExecuteReader(); reader.Read(); username = reader.GetString(0); password = reader.GetString(1); asi = reader.GetString(2); } // create login uri const string loginUri = "http://asiservice.asicentral.com/credit/v1/login"; // posting request to get token request = (HttpWebRequest)WebRequest.Create(loginUri); request.Method = "POST"; request.ContentType = "application/json"; // generate JSON file string textJson = "{\"asi\":\"" + asi + "\",\"username\":\"" + username + "\",\"password\":\"" + password + "\"}"; // turn request string into a byte stream byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(textJson); // send request using (Stream requestStream = request.GetRequestStream()) requestStream.Write(postBytes, 0, postBytes.Length); // get the response from the server response = (HttpWebResponse)request.GetResponse(); string result; using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) result = streamReader.ReadToEnd(); // set token value token = result.Substring(1, result.Length - 2); } /* a method that return company info from the given asi number */ public BPvalues GetCompanyInfo(string asi) { // uri for getting company information string uri = "http://asiservice.asicentral.com/credit/v1/creditsummary/?asiNumber=" + asi; // post request to uri request = WebRequest.Create(uri); request.Headers.Add("AuthToken", token); request.Method = "GET"; try { // get the response from the server response = (HttpWebResponse)request.GetResponse(); } catch { // the case if the company does not exist (422 unprocessable entity0 -> return nothing return null; } // read all the text from JSON response string textJson; using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) textJson = streamReader.ReadToEnd(); // deserialize json to key value var info = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<System.Collections.Generic.Dictionary<string, dynamic>>(textJson); #region Data Retrieve // start getting data string name = info["CompanyDetails"]["Name"]; string phone = info["CompanyDetails"]["Phones"][0]["PhoneNumber"]; string email = info["CompanyDetails"]["Emails"][0]["Address"]; string address1 = info["CompanyDetails"]["Addresses"][0]["AddressLine1"]; string address2 = info["CompanyDetails"]["Addresses"][0]["AddressLine2"]; string city = info["CompanyDetails"]["Addresses"][0]["City"]; string province = info["CompanyDetails"]["Addresses"][0]["State"]; string postalCode = info["CompanyDetails"]["Addresses"][0]["ZipCode"]; string country = info["CompanyDetails"]["Addresses"][0]["CountryCode"]; #endregion return new BPvalues("", "", name, phone, email, address1, address2, city, province, postalCode, country, null, null, null, null, null, null, null, true, false, null, System.DateTime.Today); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using Entities.Concrete; using FluentValidation; namespace Business.ValidationRules.FluentValidation { public class UserValidator : AbstractValidator<User> { public UserValidator() { RuleFor(p => p.FirstName).MinimumLength(3); RuleFor(p => p.FirstName).NotEmpty(); RuleFor(p => p.LastName).NotEmpty(); // RuleFor(p => p.EMail).EmailAddress(); RuleFor(p => p.FirstName).Length(5); // RuleFor(p => p.FirstName).Length(5).When(p => p.Status == true); // RuleFor(p => p.FirstName).Must(StartWithA); } private bool StartWithA(string arg) { return arg.StartsWith("a"); } } }
using BPiaoBao.Cashbag.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.Cashbag.Domain.Services { public interface IFundClientProxy { /// <summary> /// 充值(银行) /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="money"></param> /// <param name="payBank"></param> /// <returns></returns> string RechargeByBank(string code, string key, decimal money, string payBank); /// <summary> /// 充值(第三方) /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="money"></param> /// <param name="payPlatform"></param> /// <returns></returns> string RechargeByPlatform(string code, string key, decimal money, string payPlatform); /// <summary> /// 还款(现金账户) /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="money"></param> /// <param name="CashAccount"></param> void RepayMoneyByCashAccount(string code, string key, string money, string pwd); /// <summary> /// 还款(银行卡) /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="money"></param> /// <param name="Bank"></param> /// <returns></returns> string RepayMoneyByBank(string code, string key, string money, string Bank); /// <summary> /// 还款(第三方) /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="money"></param> /// <param name="Platform"></param> /// <returns></returns> string RepayMoneyByPlatform(string code, string key, string money, string Platform); /// <summary> /// 转账 /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="targetcode"></param> /// <param name="money"></param> /// <param name="pwd"></param> /// <param name="notes"></param> void InnerTransfer(string code, string key, string targetcode, string money, string pwd, string notes); /// <summary> /// 结算(提现) /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="money"></param> /// <param name="bankCardId"></param> /// <param name="pwd"></param> /// <param name="Type">0当天到账 1次日到账</param> void CashOut(string code, string key, decimal money, string bankCardId, string pwd, string Type); /// <summary> /// 获取结算手续费 /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="money"></param> /// <param name="Type">0当天到账 1次日到账</param> /// <returns></returns> string GetFeeAmount(string code, string key, string money, string Type); /// <summary> /// 获取提现手续费规则 /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <returns></returns> FeeRuleInfo GetFeeRule(string code, string key); /// <summary> /// 在线收款(银行卡) /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="money"></param> /// <param name="NotifyUrl"></param> /// <param name="payBank"></param> /// <returns></returns> string OnLineRecieveByBank(string code, string key, decimal money, string NotifyUrl, string payBank); /// <summary> /// 在线收款(第三方) /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="money"></param> /// <param name="NotifyUrl"></param> /// <param name="payPlatform"></param> /// <returns></returns> string OnLineRecieveByPlatform(string code, string key, decimal money, string NotifyUrl, string payPlatform); /// <summary> /// 获取最高结算金额 /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="Type">到账模式0当天到账 1次日到账</param> /// <returns></returns> string GetApplicationMaxAmount(string code, string key, string Type); /// <summary> /// 获取可用临时申请额度 /// </summary> /// <returns></returns> decimal GetTempCreditAmount(string code, string key); /// <summary> /// 申请临时额度 /// </summary> /// <param name="key"></param> /// <param name="pwd"></param> /// <param name="tempAmount"></param> /// <param name="code"></param> void TempCreditApplication(string code, string key, string pwd, decimal tempAmount); /// <summary> /// 申请临时额度条件相关 /// </summary> /// <param name="key"></param> /// <param name="code"></param> /// <returns></returns> TempCreditInfo GetTempCreditSetting(string code, string key); #region 支付宝快捷充值,还款 /// <summary> /// 支付宝签约充值 /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="money"></param> /// <param name="payPwd"></param> void AlipaySignRecharge(string code, string key, decimal money, string payPwd); /// <summary> /// 支付宝签约还款 /// </summary> /// <param name="code"></param> /// <param name="key"></param> /// <param name="money"></param> /// <param name="payPwd"></param> void AlipaySignRepay(string code, string key, decimal money, string payPwd); #endregion } }
using System; using DependencyInjectionExample.Interfaces; namespace DependencyInjectionExample.Classes { public class MultiplyCommand : ICommand { private readonly ICalculator _calculator; public MultiplyCommand(ICalculator calculator) { this._calculator = calculator; } public bool ShouldProcess(string input) { return input.StartsWith("multiply", StringComparison.InvariantCultureIgnoreCase); } public void Process(string input) { var arguments = input.Split(" ", 3); if (arguments.Length != 3) { throw new InvalidOperationException("You must supply a command like: multiply 5 2.5"); } var canParseFirstNumber = double.TryParse(arguments[1], out var firstNumber); var canParseSecondNumber = double.TryParse(arguments[2], out var secondNumber); if (!canParseFirstNumber || !canParseSecondNumber) { throw new InvalidCastException("Unable to cast arguments to doubles."); } Console.WriteLine($"Multiplied numbers and result is: {this._calculator.Multiply(firstNumber, secondNumber)}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace FuiteAdmin { /// <summary> /// Ecran d'affichage de tous les reports de fuite en fonction de leur état dans un tableau /// </summary> public partial class History : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.Update(); } /// <summary> /// Met à jour la construction de la page /// </summary> /// <param name="state">Etat des reports à afficher</param> private void Update(ReportService.State state = ReportService.State.New) { string ticket = (string)Session["Ticket"]; ReportService.ReportServiceClient client = new ReportService.ReportServiceClient(); ReportService.GetReportsRequest request = new ReportService.GetReportsRequest(); request.ticket = ticket; request.state = state; request.minIndex = -1; request.maxIndex = Int32.MaxValue; ReportService.ResultReports results = client.GetReports(request); if (results.Code != 0) throw new HttpException(500, results.Message); this.history.Controls.Clear(); string[] states = new string[] { "Nouveau", "Affecté", "Traité" }; results.Data = results.Data.OrderBy(x => x.Date).ToArray(); if (state != ReportService.State.New) results.Data = results.Data.Reverse().ToArray(); // Construction du tableau des reports foreach (ReportService.ReportRequest report in results.Data) { HtmlTableRow tr = new HtmlTableRow(); HtmlTableCell td = new HtmlTableCell(); td.InnerText = "#"+report.Id.ToString(); tr.Controls.Add(td); td = new HtmlTableCell(); td.InnerText = states[(int)report.State]; tr.Controls.Add(td); td = new HtmlTableCell(); td.InnerText = report.Date.ToString("dd/MM/yy HH:mm"); tr.Controls.Add(td); td = new HtmlTableCell(); HtmlAnchor a = new HtmlAnchor(); a.InnerText = "Voir"; a.Attributes["class"] = "button small"; a.HRef = "Details.aspx?id=" + report.Id; td.Controls.Add(a); tr.Controls.Add(td); this.history.Controls.Add(tr); } } /// <summary> /// Affichage des nouveaux reports /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void new_Click(object sender, EventArgs e) { this.Update(ReportService.State.New); this.@new.CssClass += " selected"; this.current.CssClass = this.current.CssClass.Replace(" selected", ""); this.closed.CssClass = this.closed.CssClass.Replace(" selected", ""); } /// <summary> /// Affichage des reports en cours de traitement /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void current_Click(object sender, EventArgs e) { this.Update(ReportService.State.Affected); this.current.CssClass += " selected"; this.@new.CssClass = this.@new.CssClass.Replace(" selected", ""); this.closed.CssClass = this.closed.CssClass.Replace(" selected", ""); } /// <summary> /// Affichage des reports terminés /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void closed_Click(object sender, EventArgs e) { this.Update(ReportService.State.Closed); this.closed.CssClass += " selected"; this.@new.CssClass = this.@new.CssClass.Replace(" selected", ""); this.current.CssClass = this.current.CssClass.Replace(" selected", ""); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.Odbc; namespace SistemaPreguntas { public partial class alumno : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Checa si hizo login como Alumno if (Session["usuarioAlumno"] == null) { Session.Abandon(); Response.Redirect("login.aspx"); } //Dar bienvenida, ocultar panel de seleccion y cargar GridViews Label1.Text = Session["nombreUsuario"].ToString(); Panel1.Visible = false; updateGridViews(); //DropDownList de Profesores en Nueva Pregunta if (DropDownList1.Items.Count == 0) { String queryDropDown = "select Usuario,Nombre from Prof"; OdbcConnection conexion = new ConexionBD().con; OdbcCommand comando = new OdbcCommand(queryDropDown, conexion); OdbcDataReader lector = comando.ExecuteReader(); DropDownList1.DataSource = lector; DropDownList1.DataValueField = "Usuario"; DropDownList1.DataTextField = "Nombre"; DropDownList1.DataBind(); } //DropDownList de Profesores en Filtro if (DropDownList2.Items.Count == 0) { String queryDropDown = "select Usuario,Nombre from Prof"; OdbcConnection conexion = new ConexionBD().con; OdbcCommand comando = new OdbcCommand(queryDropDown, conexion); OdbcDataReader lector = comando.ExecuteReader(); DropDownList2.DataSource = lector; DropDownList2.DataValueField = "Usuario"; DropDownList2.DataTextField = "Nombre"; DropDownList2.DataBind(); DropDownList2.Items.Insert(0, new ListItem("Todos", "")); } } protected void Button1_Click(object sender, EventArgs e) { //Botton de Cerrar Sesion Session.Abandon(); Response.Redirect("login.aspx"); } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { //Pregunta respondida seleccionada. Usuario puede ver respuesta. //Cargar Datos de Pregunta en Panel de Seleccion Label2.Text = GridView1.SelectedRow.Cells[1].Text; //Folio Label3.Text = GridView1.SelectedRow.Cells[3].Text; //Fecha Pregunta Label4.Text = "Fecha Respuesta: "+GridView1.SelectedRow.Cells[5].Text; //Fecha Respuesta Label8.Text = GridView1.SelectedRow.Cells[4].Text; //Pregunta Label9.Text = "Respuesta: \"" + GridView1.SelectedRow.Cells[6].Text + "\""; //Respuesta Label7.Text= GridView1.SelectedRow.Cells[2].Text; //Profesor Panel1.Visible = true; Button2.Visible = false; Button3.Visible = false; TextBox1.Visible = false; Panel1.Focus(); } protected void GridView2_SelectedIndexChanged(object sender, EventArgs e) { //Pregunta no contestada seleccionada //Cargar Pregunta en Panel de Seleccion Label2.Text = GridView2.SelectedRow.Cells[1].Text; //Folio Label3.Text = GridView2.SelectedRow.Cells[3].Text; //Fecha Pregunta //byte[] bytes = System.Text.UTF8Encoding.Default.GetBytes(GridView2.SelectedRow.Cells[4].Text); //TextBox1.Text = System.Text.UTF8Encoding.UTF8.GetString(bytes); TextBox1.Text = System.Web.HttpUtility.HtmlDecode(GridView2.SelectedRow.Cells[4].Text); //Pregunta Label7.Text = GridView2.SelectedRow.Cells[2].Text; //Profesor Label6.Text = ""; //Respuesta Label4.Text = ""; //Fecha Respuesta Panel1.Visible = true; Button2.Enabled = true; Button3.Enabled = true; Label6.Text = ""; Label9.Text = ""; Label8.Text = ""; Button2.Visible = true; Button3.Visible = true; TextBox1.Visible = true; Panel1.Focus(); } protected void Button2_Click(object sender, EventArgs e) { //Editar Pregunta string folio = GridView2.SelectedRow.Cells[1].Text; string pregunta = TextBox1.Text; string query = "update Pregunta set Pregunta=? where folio=?"; OdbcConnection conexion = new ConexionBD().con; OdbcCommand comando = new OdbcCommand(query, conexion); comando.Parameters.AddWithValue("Pregunta", pregunta); comando.Parameters.AddWithValue("folio", folio); try { comando.ExecuteNonQuery(); Label6.Text = "Edito la pregunta exitosamente"; } catch (Exception ex) { Label6.Text = "Error al editar pregunta:" + ex.ToString(); } conexion.Close(); updateGridViews(); } protected void updateGridViews() { //Metodo que carga los datos de ambos GridViews. Se usa varias veces. //Preguntas contestadas string query = "select Folio,Nombre,FechaPregunta,Pregunta,FechaRespuesta,Respuesta from Pregunta inner join Prof on Pregunta.UsuarioProf=Prof.Usuario where Pregunta.Respuesta is not null and Pregunta.UsuarioAlumno=?"; bool filtro = false; if (!DropDownList2.SelectedValue.ToString().Equals("")) { query = "select Folio,Nombre,FechaPregunta,Pregunta,FechaRespuesta,Respuesta from Pregunta inner join Prof on Pregunta.UsuarioProf=Prof.Usuario where Pregunta.Respuesta is not null and Pregunta.UsuarioAlumno=? and Pregunta.UsuarioProf=?"; filtro = true; } ConexionBD objetoParaConexion = new ConexionBD(); OdbcConnection conexion = objetoParaConexion.con; OdbcCommand comando = new OdbcCommand(query, conexion); comando.Parameters.AddWithValue("Pregunta.UsuarioAlumno", Session["usuarioAlumno"]); if (filtro) { comando.Parameters.AddWithValue("Pregunta.UsuarioProf", DropDownList2.SelectedValue.ToString()); } OdbcDataReader lector = comando.ExecuteReader(); GridView1.DataSource = lector; GridView1.DataBind(); //Preguntas no contestadas query = "select Folio,Nombre,FechaPregunta,Pregunta from Pregunta inner join Prof on Pregunta.UsuarioProf=Prof.Usuario where Pregunta.Respuesta is null and Pregunta.UsuarioAlumno=?"; if (filtro) { query = "select Folio,Nombre,FechaPregunta,Pregunta from Pregunta inner join Prof on Pregunta.UsuarioProf=Prof.Usuario where Pregunta.Respuesta is null and Pregunta.UsuarioAlumno=? and Pregunta.UsuarioProf=?"; } objetoParaConexion = new ConexionBD(); conexion = objetoParaConexion.con; comando = new OdbcCommand(query, conexion); comando.Parameters.AddWithValue("Pregunta.UsuarioAlumno", Session["usuarioAlumno"]); if (filtro) { comando.Parameters.AddWithValue("Pregunta.UsuarioProf", DropDownList2.SelectedValue.ToString()); } lector = comando.ExecuteReader(); GridView2.DataSource = lector; GridView2.DataBind(); } protected void Button4_Click(object sender, EventArgs e) { //Boton de Cancelar en Panel de Seleccion Panel1.Visible = false; } protected void Button3_Click(object sender, EventArgs e) { //Borrar pregunta string query = "delete from Pregunta where folio=?"; string folio = GridView2.SelectedRow.Cells[1].Text; OdbcConnection conexion = new ConexionBD().con; OdbcCommand comando = new OdbcCommand(query, conexion); comando.Parameters.AddWithValue("folio", folio); try { comando.ExecuteNonQuery(); Label6.Text = "Borro la pregunta exitosamente"; } catch (Exception ex) { Label6.Text = "Error al borrar pregunta:" + ex.ToString(); } conexion.Close(); updateGridViews(); } protected void Button5_Click(object sender, EventArgs e) { //Buton de Mandar Pregunta en Nueva Pregunta //Intenta hacer insert con folio aleatorio hasta que se encuentre uno que no este en la BD. string query = "insert into Pregunta values(?,?,?,?,null,GETDATE(),null);"; while (true) { OdbcConnection conexion = new ConexionBD().con; OdbcCommand comando = new OdbcCommand(query, conexion); comando.Parameters.AddWithValue("Folio", new Random().Next(1000000)); comando.Parameters.AddWithValue("UsuarioAlumno", Session["usuarioAlumno"]); comando.Parameters.AddWithValue("UsuarioProf", DropDownList1.SelectedValue.ToString()); comando.Parameters.AddWithValue("Pregunta", TextBox2.Text); try { comando.ExecuteNonQuery(); Label6.Text = "Mando la pregunta exitosamente"; break; } catch (Exception ex) { Label6.Text = "Error al mandar pregunta:" + ex.ToString(); } conexion.Close(); } TextBox2.Text = ""; updateGridViews(); } protected void Button6_Click(object sender, EventArgs e) { //Boton de Filtro updateGridViews(); } protected void Button7_Click(object sender, EventArgs e) { Response.Redirect("CambioPasswd.aspx"); } protected void ButtonCambio_Click(object sender, EventArgs e) { Response.Redirect("CambioPasswd.aspx"); } } }
using MKService.ModelUpdaters; using MKService.Updates; using Service; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MKService.MessageHandlers { internal abstract class ServerMessageHandlerBase<TMessage, TQuery, TQueryComponent> : IServerMessageHandler where TMessage : class, IMessage where TQuery : class, IQueryResponse where TQueryComponent : class, IUpdatable { /// <summary> /// The model updater resolver. /// </summary> private readonly IModelUpdaterResolver modelUpdaterResolver; /// <summary> /// Initializes a new instance of the <see cref="ServerMessageHandlerBase{TMessage,TQuery,TQueryComponent}" /> class. /// </summary> /// <param name="modelUpdaterResolver">The model updater resolver.</param> protected ServerMessageHandlerBase(IModelUpdaterResolver modelUpdaterResolver) { this.modelUpdaterResolver = modelUpdaterResolver; } /// <summary> /// Determine if the handler can handle the specified message given the specified query. /// </summary> /// <param name="message">The message.</param> /// <param name="query">The query.</param> /// <returns><c>true</c>, if the handler can handle the message; otherwise, <c>false</c>.</returns> public bool CanHandle(IMessage message, IQueryResponse query) { if (message == null || query == null) { return false; } return typeof(TMessage) == message.GetType() && typeof(TQuery) == query.GetType(); } /// <summary> /// Determines whether this instance can handle the specified message type. /// </summary> /// <param name="message">The message.</param> /// <returns> /// <c>true</c>, if this instance can handle the specified message type; otherwise, <c>false</c>. /// </returns> public bool CanHandleMessageType(IMessage message) { if (message == null) { return false; } return typeof(TMessage) == message.GetType(); } /// <summary> /// Handles the specified message by updating the specified query to reflect the state changes described in the /// specified message. /// </summary> /// <param name="message">The message.</param> /// <param name="query">The query to be updated.</param> public void Handle(IMessage message, IQueryResponse query) { var msg = message as TMessage; var q = query as TQuery; if (msg == null || q == null) { return; } var component = this.LocateQueryComponent(msg, q); if (component == null) { return; } this.modelUpdaterResolver.GetUpdater<TQueryComponent, TMessage>().Update(component, msg); } /// <summary> /// Locates the query or query component of the specified query that needs to be updated in response to the /// specified message. This method should not actually update the query as this is handled in the model updater. /// It is safe to return <c>null</c> from this method. /// </summary> /// <param name="message">The message.</param> /// <param name="query">The query to be updated.</param> /// <returns> /// If the query or query component affected by the specified message is found, the query or query component; /// otherwise, <c>null</c>. /// </returns> protected abstract TQueryComponent LocateQueryComponent(TMessage message, TQuery query); } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace EducationManual.Models { public class Student { [Key] [ForeignKey("ApplicationUser")] public string Id { get; set; } public int ClassroomId { get; set; } public Classroom Classroom { get; set; } public ApplicationUser ApplicationUser { get; set; } } }
// Author(s): UWBothell Cross Reality Collaboration Sandbox, Aaron Holloway // Fall 2018 // Last Modified: 12/2/2018 using System; using System.IO; using System.Net; using System.Threading; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; // Originally in Summer2018CRCSProject/Assets/ASL/RC/Scripts as WebSteam.cs // Modified slightly, including option to render out to Texture2D or RawImage // as needed. Also moved GetStream() into a coroutine in an attempt to solve // Unity engine hangs during intermittent or timed out connection. // Likely still needs improvement, especially moving the stream processing onto // a secondary thread. public class WebStream : MonoBehaviour { // Opentopia.com Webcam IP Adress // private const string sourceURL = "http://194.103.218.15/mjpg/video.mjpg"; // UW Seattle Webcam IP Address //private const string sourceURL = "http://128.208.252.2/mjpg/video.mjpg"; // RC Car IP Address public bool left; private string sourceURL; private Texture2D texture; private MeshRenderer frame; public RawImage image; /* * The Start method, called when the object is instantiated, initializes * variables for the script, assigns the appropriate sorting layer to * the MeshRenderer for the object, and calls the GetStream method. */ void Start() { if (left) sourceURL = "http://172.24.1.1:8080/?action=stream"; else sourceURL = "http://172.24.1.1:8070/?action=stream"; frame = this.GetComponent<MeshRenderer>(); texture = new Texture2D(2, 2); // texture = new Texture2D(640, 480, TextureFormat.YUY2, false); StartCoroutine(GetStream()); } public Texture getTextureFeed() { return texture; } /* * The GetStream method creates and sends an HTTP GET request * to the sourceURL, receives the response from the address, * and starts the FillFrame coroutine. */ IEnumerator GetStream() { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sourceURL); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); StartCoroutine(FillFrame(stream)); yield return null; } /* * The FillFrame method uses a MemoryStream created from reading * the bytes in the stream to load the image into a texture and * attach it to the MeshRenderer. The StreamLength() method is * called to determine the number of bytes to read. * @return IEnumerator The IEnumerator that determines How long * the coroutine will yield. In most cases the coroutine will * start again on the next update. */ IEnumerator FillFrame(Stream stream) { Byte[] imageData = new Byte[150000]; while(true) { int totalBytes = StreamLength(stream); if (totalBytes == -1) yield break; int remainingBytes = totalBytes; while(remainingBytes > 0) { remainingBytes -= stream.Read(imageData, totalBytes - remainingBytes, remainingBytes); yield return null; } MemoryStream memStream = new MemoryStream(imageData, 0, totalBytes, false, true); texture.LoadImage(memStream.GetBuffer()); // texture.LoadRawTextureData(memStream.GetBuffer()); // texture.Apply(); if (frame) { frame.material.mainTexture = texture; } if(image) { image.texture = texture; } stream.ReadByte(); stream.ReadByte(); } } /* * The StreamLength method returns the total number of bytes in * the stream excluding header and metadata information. */ int StreamLength(Stream stream) { int b; string line = ""; int result = -1; bool atEOL = false; while ((b = stream.ReadByte()) != -1) { if (b == 10) continue; if (b == 13) { if (atEOL) { stream.ReadByte(); return result; } if (line.StartsWith("Content-Length:")) { result = Convert.ToInt32(line.Substring("Content-Length:".Length).Trim()); line = ""; } else { line = ""; } atEOL = true; } else { atEOL = false; line += (char)b; } } return -1; } } /* ------------------ Old Code --------------------- // Debug Prints from GetStream() // - For Debug - if(left) print("Left: Received response with Content Length: " + response.ContentLength); else print("Received response with Content Length: " + response.ContentLength); // - End Debug - // - For Debug - print("Stream created with Content Length: " + response.ContentLength); // -End Debug - // Debug Prints from FillFrame() // - For Debug - // print("Starting Coroutine"); // - End Debug - // - For Debug - if (left) print("Left: Stream Length: " + totalBytes); else print("Stream Length: " + totalBytes); // - End Debug - // - For Debug - // print("Yielding Coroutine, because there are no bytes to read from the stream"); // - End Debug - // - For Debug - if (left) print("Left: In Read Loop ... Remaining: " + remainingBytes); else print("In Read Loop ... Remaining: " + remainingBytes); // - End Debug - // - For Debug - // print("Yielding for one update .."); // - End Debug - // - For Debug - if(left) print("Left: Loading Image and Exiting Coroutine"); else print("Loading Image and Exiting Coroutine"); // - End Debug - */
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace Backend.WebApp.Migrations { public partial class RemoveGroupRole : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Roles"); migrationBuilder.DropTable( name: "Groups"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Groups", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Created = table.Column<DateTimeOffset>(nullable: false), CreatedBy = table.Column<string>(maxLength: 64, nullable: false), Modified = table.Column<DateTimeOffset>(nullable: true), ModifiedBy = table.Column<string>(maxLength: 64, nullable: true), Name = table.Column<string>(maxLength: 65, nullable: false) }, constraints: table => { table.PrimaryKey("PK_Groups", x => x.Id); }); migrationBuilder.CreateTable( name: "Roles", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Created = table.Column<DateTimeOffset>(nullable: false), CreatedBy = table.Column<string>(maxLength: 64, nullable: false), GroupId = table.Column<int>(nullable: false), Modified = table.Column<DateTimeOffset>(nullable: true), ModifiedBy = table.Column<string>(maxLength: 64, nullable: true), Name = table.Column<string>(maxLength: 65, nullable: false) }, constraints: table => { table.PrimaryKey("PK_Roles", x => x.Id); table.ForeignKey( name: "FK_Roles_Groups_GroupId", column: x => x.GroupId, principalTable: "Groups", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Roles_GroupId", table: "Roles", column: "GroupId"); } } }
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using IdentityServer4.Services.InMemory; using IdsvrMultiTenant.Services.MultiTenancy; using Microsoft.AspNetCore.Http; using System.Linq; using System.Security.Claims; using IdentityModel; using IdentityServer4; namespace IdsvrMultiTenant.Services.IdSvr { /// <summary> /// Extraction of the IdSvr4 Host example for validating in memory users. /// This is needed because we need to resolve the users per tenant. /// </summary> public interface IUserLoginService { bool ValidateCredentials(string username, string password); InMemoryUser FindByUsername(string username); InMemoryUser FindByExternalProvider(string provider, string userId); InMemoryUser AutoProvisionUser(string provider, string userId, List<Claim> claims); } public class UserLoginResolver : IUserLoginService { private readonly IUserLoginService _userLoginServiceImplementation; public UserLoginResolver(IHttpContextAccessor httpContextAccessor) { if(httpContextAccessor == null) throw new ArgumentNullException(nameof(httpContextAccessor)); // just to be sure, we are in a tenant context var tenantContext = httpContextAccessor.HttpContext.GetTenantContext<IdsvrTenant>(); if(tenantContext == null) throw new ArgumentNullException(nameof(tenantContext)); if (tenantContext.Tenant.Name == "first") { _userLoginServiceImplementation = new InMemoryUserLoginService(GetUsersForFirstTenant()); } else if (tenantContext.Tenant.Name == "second") { _userLoginServiceImplementation = new InMemoryUserLoginService(GetUsersForSecondTenant()); } else { _userLoginServiceImplementation = new InMemoryUserLoginService(new List<InMemoryUser>()); } } public bool ValidateCredentials(string username, string password) { return _userLoginServiceImplementation.ValidateCredentials(username, password); } public InMemoryUser FindByUsername(string username) { return _userLoginServiceImplementation.FindByUsername(username); } public InMemoryUser FindByExternalProvider(string provider, string userId) { return _userLoginServiceImplementation.FindByExternalProvider(provider, userId); } public InMemoryUser AutoProvisionUser(string provider, string userId, List<Claim> claims) { return _userLoginServiceImplementation.AutoProvisionUser(provider, userId, claims); } private List<InMemoryUser> GetUsersForFirstTenant() { return new List<InMemoryUser>() { new InMemoryUser{Subject = "818727", Username = "alice", Password = "alice", Claims = new Claim[] { new Claim(JwtClaimTypes.Name, "Alice Smith"), new Claim(JwtClaimTypes.GivenName, "Alice"), new Claim(JwtClaimTypes.FamilyName, "Smith"), new Claim(JwtClaimTypes.Email, "AliceSmith@email.com"), new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean), new Claim(JwtClaimTypes.Role, "Admin"), new Claim(JwtClaimTypes.Role, "Geek"), new Claim(JwtClaimTypes.WebSite, "http://alice.com"), new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServerConstants.ClaimValueTypes.Json) } } }; } private List<InMemoryUser> GetUsersForSecondTenant() { return new List<InMemoryUser>() { new InMemoryUser{Subject = "88421113", Username = "bob", Password = "bob", Claims = new Claim[] { new Claim(JwtClaimTypes.Name, "Bob Smith"), new Claim(JwtClaimTypes.GivenName, "Bob"), new Claim(JwtClaimTypes.FamilyName, "Smith"), new Claim(JwtClaimTypes.Email, "BobSmith@email.com"), new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean), new Claim(JwtClaimTypes.Role, "Developer"), new Claim(JwtClaimTypes.Role, "Geek"), new Claim(JwtClaimTypes.WebSite, "http://bob.com"), new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServerConstants.ClaimValueTypes.Json) } } }; } } public class InMemoryUserLoginService : IUserLoginService { public List<InMemoryUser> _users; public InMemoryUserLoginService(List<InMemoryUser> users) { _users = users; } public bool ValidateCredentials(string username, string password) { var user = FindByUsername(username); if (user != null) { return user.Password.Equals(password); } return false; } public InMemoryUser FindByUsername(string username) { return _users.FirstOrDefault(x=>x.Username.Equals(username, System.StringComparison.OrdinalIgnoreCase)); } public InMemoryUser FindByExternalProvider(string provider, string userId) { return _users.FirstOrDefault(x => x.Provider == provider && x.ProviderId == userId); } public InMemoryUser AutoProvisionUser(string provider, string userId, List<Claim> claims) { // create a list of claims that we want to transfer into our store var filtered = new List<Claim>(); foreach(var claim in claims) { // if the external system sends a display name - translate that to the standard OIDC name claim if (claim.Type == ClaimTypes.Name) { filtered.Add(new Claim(JwtClaimTypes.Name, claim.Value)); } // if the JWT handler has an outbound mapping to an OIDC claim use that else if (JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.ContainsKey(claim.Type)) { filtered.Add(new Claim(JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap[claim.Type], claim.Value)); } // copy the claim as-is else { filtered.Add(claim); } } // if no display name was provided, try to construct by first and/or last name if (!filtered.Any(x=>x.Type == JwtClaimTypes.Name)) { var first = filtered.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value; var last = filtered.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value; if (first != null && last != null) { filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last)); } else if (first != null) { filtered.Add(new Claim(JwtClaimTypes.Name, first)); } else if (last != null) { filtered.Add(new Claim(JwtClaimTypes.Name, last)); } } // create a new unique subject id var sub = CryptoRandom.CreateUniqueId(); // check if a display name is available, otherwise fallback to subject id var name = filtered.FirstOrDefault(c => c.Type == JwtClaimTypes.Name)?.Value ?? sub; // create new user var user = new InMemoryUser() { Enabled = true, Subject = sub, Username = name, Provider = provider, ProviderId = userId, Claims = filtered }; // add user to in-memory store _users.Add(user); return user; } } }
// Copyright 2020 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Linq; namespace NtApiDotNet.Utilities.SafeBuffers { /// <summary> /// A buffer which contains an array of GUID pointers. /// </summary> public class SafeGuidArrayBuffer : SafeHGlobalBuffer { private static int CalculateSize(Guid[] guids) { return guids.Length * (IntPtr.Size + 16); } private SafeGuidArrayBuffer() : base(IntPtr.Zero, 0, false) { } /// <summary> /// The count of GUIDs. /// </summary> public int Count { get; } /// <summary> /// Constructor. /// </summary> /// <param name="guids">The list of GUIDs.</param> public SafeGuidArrayBuffer(Guid[] guids) : base(CalculateSize(guids)) { Count = guids.Length; int guid_base = guids.Length * IntPtr.Size; IntPtr[] ptrs = Enumerable.Range(0, guids.Length).Select(i => DangerousGetHandle() + (i * 16 + guid_base)).ToArray(); WriteArray(0, ptrs, 0, ptrs.Length); WriteArray((ulong)guid_base, guids, 0, guids.Length); } /// <summary> /// Get NULL safe buffer. /// </summary> new static public SafeGuidArrayBuffer Null => new SafeGuidArrayBuffer(); } }
using System; using System.Collections.Generic; using System.Text; using LuizalabsWishesManager.Data.Repositories; using LuizalabsWishesManager.Domains.Models; using LuizalabsWishesManager.Domains.Repositories; namespace LuizalabsWishesManager.Data.Repositories { public class WishProductRepository : RepositoryBase<WishProduct>, IWishProductRepository { } }
using console; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; namespace ConsoleTestProj { /// <summary> ///This is a test class for _007_ContainerWithMostWaterTest and is intended ///to contain all _007_ContainerWithMostWaterTest Unit Tests ///</summary> [TestClass()] public class _007_ContainerWithMostWaterTest { private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //public static void MyClassInitialize(TestContext testContext) //{ //} // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //public static void MyClassCleanup() //{ //} // //Use TestInitialize to run code before running each test //[TestInitialize()] //public void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run //[TestCleanup()] //public void MyTestCleanup() //{ //} // #endregion /// <summary> ///A test for FindLargestContainerBrutal ///</summary> [TestMethod()] public void FindLargestContainerBrutalTest() { _007_ContainerWithMostWater target = new _007_ContainerWithMostWater(); // TODO: Initialize to an appropriate value List<int> actual, actualbrutal; int[] input = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; actualbrutal = target.FindLargestContainerBrutal(input); actual = target.FindLargestContainer(input); Assert.AreEqual(25, actual[0], "max capacity should be 25"); for (int i = 0; i < actual.Count; i++) { Assert.AreEqual(actual[i], actualbrutal[i], "brutal force and one way scan should come out with same solution"); } input = new int[] { 2,3,10,5,7,8,9 }; actualbrutal = target.FindLargestContainerBrutal(input); actual = target.FindLargestContainer(input); Assert.AreEqual(36, actual[0], "max capacity should be 25"); for (int i = 0; i < actual.Count; i++) { Assert.AreEqual(actual[i], actualbrutal[i], "brutal force and one way scan should come out with same solution"); } } } }
using BlackJackDudekGueguen.Model; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace BlackJackDudekGueguen.ViewModel { class GameViewModel { public Deck Deck { get; set; } public User Bank { get; set; } public User Player { get; set; } public bool hasForgiven { get; set; } public bool hasInsurance { get; set; } public bool hasDoubled { get; set; } public bool hasSplit { get; set; } public GameViewModel() { hasForgiven = false; hasSplit = false; hasInsurance = false; hasDoubled = false; this.Deck = new Deck(); this.Bank = new User(); this.Bank.Hand = new Hand(); this.Player = new User(); this.Player.Hand = new Hand(); AskBet(); DrawCards(); StartGame(); } //On demande au joueur de parier public void AskBet() { } //On fait les tirages du début du tour public void DrawCards() { Draw(Player.Hand, true); Draw(Bank.Hand, true); Draw(Player.Hand, true); Draw(Bank.Hand, false); } //Code pour distribuer une carte public void Draw(Hand UserHand, bool isVisible) { //La carte tirée est la dernière du paquet Card cardDrawed = this.Deck.Cards.Last(); //face ou visible ou cachée cardDrawed.IsVisible = isVisible; //on l'ajoute à la main du joueur UserHand.Cards.Add(cardDrawed); //on supprime la drnière carte du paquet (celle qui vient d'être tiré) int numberCard = Deck.Cards.Count; Deck.Cards.RemoveAt(numberCard); } //Pas eu le temps d'avancer plus le code, //beaucoup trop de souci avec le git qu'on a dû réparer public void StartGame() { //Display Bet PopUp //Do you want to play //if yes if (Player.Hand.Cards[0].Number == Player.Hand.Cards[1].Number) { //Display Split Button } if (Bank.Hand.Cards[0].Number == 1) { //Display Insurance Button } //else //stop Game } // //si il clique sur le bouton split public void Split() { Player.SplitHand = new Hand(); Player.SplitHand.Cards = new ObservableCollection<Card>(); Player.SplitHand.Cards.Add(Player.Hand.Cards[1]); Player.Hand.Cards.RemoveAt(1); Player.SplitHand.Bet = Player.Hand.Bet; hasSplit = true; } //Si il clique sur le bouton assurance public void Insurance() { Player.Hand.SideBet = Player.Hand.Bet; hasInsurance = true; } //il clic sur le bouton Forgive public void Forgive() { hasForgiven = true; } //si il clique sur le bouton double //il double les gains de sa mise public void Double() { hasDoubled = true; } //Se fait à la fin d'un tour public async void UpdateStack(int moneyWin) { string apiUrl = "user/" + Player.Email + "/stack/" + moneyWin; using (var client = new HttpClient()) { //send the new stack to api in GET client.BaseAddress = new Uri("http://demo.comte.re/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await client.GetAsync(apiUrl); if (response.IsSuccessStatusCode) { string res = await response.Content.ReadAsStringAsync(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /* Создать класс "Сотрудник" с полями: ФИО, должность, email, телефон, зарплата, возраст; Конструктор класса должен заполнять эти поля при создании объекта; Внутри класса «Сотрудник» написать метод, который выводит информацию об объекте в консоль; Создать массив из 5 сотрудников Пример: Person[] persArray = new Person[5]; // Вначале объявляем массив объектов persArray[0] = new Person("Ivanov Ivan", "Engineer", "ivivan@mailbox.com", "892312312", 30000, 30); // потом для каждой ячейки массива задаем объект persArray[1] = new Person(...); ... persArray[4] = new Person(...); С помощью цикла вывести информацию только о сотрудниках старше 40 лет; */ namespace l5p { class l5p6 { public static void Person_list() { Person[] person_list = Create_array(); select_more_age(person_list, 40); } public static void select_more_age(Person[] person_list, int age) { for(int i = 0; i < person_list.Length; i++) { if(person_list[i].age > 40) { person_list[i].Select_info(); } } } public static Person[] Create_array() { Person[] person_list = new Person[5]; person_list[0] = new Person("Смирнов М.И.", "инженер", "smir85@mail.ru", "9-720-111-11-12-15", 30000, 40); person_list[1] = new Person("Петров В.Г.", "проектировщик", "petro22_15@mail.ru", "9-720-111-11-12-16", 35000, 43); person_list[2] = new Person("Васильев Т.Р.", "разнорабочий", "vasilievtr@mail.ru", "9-720-111-11-12-44", 25000, 32); person_list[3] = new Person("Третьяков Р.Р.", "разнорабочий", "rtret@mail.ru", "9-720-111-11-11-22", 25000, 43); person_list[4] = new Person("Михайлов М.П.", "инженер", "mikhaiylov@mail.ru", "9-720-111-11-11-23", 33000, 45); return person_list; } } class Person { public string FLP { get; set; } public string work { get; set; } public string email { get; set; } public string phone { get; set; } public decimal pay { get; set; } public int age { get; set; } public Person(string _flp, string _work, string _email, string _phone, decimal _pay, int _age) { FLP = _flp; work = _work; email = _email; phone = _phone; pay = _pay; age = _age; } public void Select_info() { Console.WriteLine($"ФИО: {FLP}\nДолжность: {work}\nemail: {email}\nТелефон: {phone}\nЗарплата: {pay}\nВозраст: {age}\n"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace лаба_5 { class Paper : Plant { string vidPaper; string color; public string Color { get => color; set { color = value; } } public string VidPaper { get { return vidPaper; } set { vidPaper = value; } } public Paper(string vidPaper) { VidPaper = vidPaper; } public Paper() { } public override string ToString() { return GetInfo(); } public override string GetInfo() { string str; str = $"вид растения: {Vid}\nвид бумаги: {VidPaper}\nвысота: {Hidth}\nЦвет: {Color}\nвозраст растения: {Age}\n"; return str; } } }
using System; using OpenCookly.Modules.Core; using OpenCookly.Common.UI; namespace OpenCookly.Modules.Core.UI.Models { public class IngredientModel : BaseEntityModel<Entities.Ingredient> { public virtual string Name { get; set; } public virtual string Description { get; set; } } }
using System.Runtime.InteropServices; namespace ww898.AELauncher.Impl.Interop { internal static unsafe class Advapi32Dll { private const string LibraryName = "advapi32.dll"; [DllImport(LibraryName, ExactSpelling = true, SetLastError = true)] public static extern int OpenProcessToken(void* ProcessHandle, uint DesiredAccess, void** TokenHandle); [DllImport(LibraryName, ExactSpelling = true, SetLastError = true)] public static extern int GetTokenInformation(void* TokenHandle, int TokenInformationClass, void* TokenInformation, uint TokenInformationLength, uint* ReturnLength); } }
// ----------------------------------------------------------------------- // <copyright file="Dimensions.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.Collections.ObjectModel; namespace Mlos.Model.Services.Spaces { public enum DimensionTypeName { /// <summary> /// Models a dimension that can assume continuous values. /// </summary> ContinuousDimension, /// <summary> /// Models a dimension whose values can assume uniformly spaced discrete values. /// </summary> DiscreteDimension, /// <summary> /// A dimension whose values have a total ordering but the distance between consecutive values is unspecified. /// </summary> OrdinalDimension, /// <summary> /// A dimension whose values have a total ordering but the distance between consecutive values is unspecified. /// </summary> CategoricalDimension, } public interface IDimension { public string Name { get; set; } } public sealed class ContinuousDimension : IDimension { public DimensionTypeName ObjectType { get; set; } public string Name { get; set; } public double Min { get; set; } public double Max { get; set; } public bool IncludeMin { get; set; } public bool IncludeMax { get; set; } public ContinuousDimension(string name, double min, double max, bool includeMin = true, bool includeMax = true) { ObjectType = DimensionTypeName.ContinuousDimension; Name = name; Min = min; Max = max; IncludeMin = includeMin; IncludeMax = includeMax; } } public class DiscreteDimension : IDimension { public DimensionTypeName ObjectType { get; set; } // TODO: private setter, read only, make sure works with serializer, move to base class public string Name { get; set; } public long Min { get; set; } public long Max { get; set; } public DiscreteDimension(string name, long min, long max) { ObjectType = DimensionTypeName.DiscreteDimension; Name = name; Min = min; Max = max; } } public class OrdinalDimension : IDimension { public DimensionTypeName ObjectType { get; set; } public string Name { get; set; } public ReadOnlyCollection<object> OrderedValues { get; } public bool Ascending { get; set; } public OrdinalDimension(string name, bool ascending, params object[] orderedValues) { ObjectType = DimensionTypeName.OrdinalDimension; Name = name; OrderedValues = new ReadOnlyCollection<object>(orderedValues); Ascending = ascending; } } public class CategoricalDimension : IDimension { public DimensionTypeName ObjectType { get; set; } public string Name { get; set; } public ReadOnlyCollection<object> Values { get; } public CategoricalDimension(string name, params object[] values) { ObjectType = DimensionTypeName.CategoricalDimension; Name = name; Values = new ReadOnlyCollection<object>(values); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Shapes; using Xceed.Wpf.Toolkit; namespace EntomoLabels { public class LabelSet { public string TemplateName { get; set; } public double LabelWidth { get; set; } public double LabelHeight { get; set; } public int LabelQuantity { get; set; } public List<Element> Elements { get; set; } = new List<Element>(); public LabelSet DeepCopy() { LabelSet other = (LabelSet)this.MemberwiseClone(); other.TemplateName = String.Copy(TemplateName); other.Elements = this.Elements.Select(x => x.ShallowCopy()).ToList(); // duplikowana etykietka powinna mieć quantity=1 other.LabelQuantity = 1; return other; } } // lista parametrów wydruku public class PrintParams { public string PageSize { get; set; } public string PageOrientation { get; set; } public double PageLeftMargin { get; set; } public double PageTopMargin { get; set; } public double PageRightMargin { get; set; } public double PageBottomMargin { get; set; } public double LabelRightMargin { get; set; } public double LabelBottomMargin { get; set; } public string SortCriteria { get; set; } } // struktura obiektu - lista etykiet - paczka - do przechowywania danych w pamięci public static class EntomoLabelList { private static List<LabelSet> LabelsList { get; set; } = new List<LabelSet>(); private static ListBox labelsListBox; static Label labelCurrentRecord; public static void init(ListBox _labelsListBox, Label _labelCurrentRecord) { labelsListBox = _labelsListBox; labelCurrentRecord = _labelCurrentRecord; } #region label list public static void forEachLabel(Action<LabelSet> func) { foreach (var labelset in LabelsList) { func(labelset); } } public static void duplicateLabel() { var current = getCurrentLabel(); var labelset = current.DeepCopy(); LabelsList.Add(labelset); labelsListBox.Items.Add("" + labelsListBox.SelectedValue); setCurrentLabel_theLast(); } public static void addLabel(LabelSet labelset, string title) { LabelsList.Add(labelset); labelsListBox.Items.Add(title); } public static void clearLabelsList() { labelsListBox.Items.Clear(); LabelsList.Clear(); } public static int labelsListCount() { return labelsListBox.Items.Count; } #endregion #region save/load public static void serialize(string pathAndFileName) { Utils.Serialize(pathAndFileName, LabelsList); } public static void deserialize(string pathAndFileName) { LabelsList = Utils.Deserialize<List<LabelSet>>(pathAndFileName); // utworzyć listę etykietek foreach (var element in LabelsList) labelsListBox.Items.Add(element.TemplateName); } #endregion #region current label public static LabelSet getCurrentLabel() { return LabelsList[labelsListBox.SelectedIndex]; } public static bool isLabelSelected() { return labelsListBox.SelectedIndex > -1; } public static void updateCurrentRecordLabel() { labelCurrentRecord.Content = "Label " + (labelsListBox.SelectedIndex + 1).ToString() + " of " + labelsListBox.Items.Count.ToString(); } public static void clearCurrentLabel() { labelsListBox.SelectedIndex = -1; labelCurrentRecord.Content = "Label <none>"; } public static void setCurrentLabel_theFirst() { labelsListBox.SelectedIndex = 0; } public static void setCurrentLabel_theLast() { labelsListBox.SelectedIndex = labelsListBox.Items.Count - 1; } internal static void deleteCurrent() { int saveCurrentPosition = labelsListBox.SelectedIndex; LabelsList.RemoveAt(labelsListBox.SelectedIndex); labelsListBox.Items.RemoveAt(labelsListBox.SelectedIndex); if (labelsListBox.Items.Count > 0) { if (labelsListBox.Items.Count > saveCurrentPosition) labelsListBox.SelectedIndex = saveCurrentPosition; else setCurrentLabel_theLast(); } } #endregion } public static class EntomoLabelManager { static ComboBox object_selected; static DoubleUpDown label_width; static DoubleUpDown label_height; static Canvas canvas; static TextBox label_quantity; static Rectangle l_border; public static void init(ComboBox _object_selected, DoubleUpDown _label_width, DoubleUpDown _label_height, Canvas _canvas, TextBox _label_quantity, Rectangle _l_border) { object_selected = _object_selected; label_width = _label_width; label_height = _label_height; canvas = _canvas; label_quantity = _label_quantity; l_border = _l_border; } public static void render() { if (!EntomoLabelList.isLabelSelected()) return; DrawLabel(); object_selected.Items.Clear(); var list = ElementsManager.getListOfObjects_ExtraData(); foreach (Element_AllData extra_data in list) { object_selected.Items.Add(extra_data.name); } EntomoLabelList.updateCurrentRecordLabel(); updateWidthHeightLabels(); CoreButtonsManager.showButtons(); } private static void updateWidthHeightLabels() { if (!EntomoLabelList.isLabelSelected()) return; var labelset = EntomoLabelList.getCurrentLabel(); label_width.Text = labelset.LabelWidth.ToString(); label_height.Text = labelset.LabelHeight.ToString(); } public static void clearLabel() { ElementsManager.clearObjects(); canvas.Children.Clear(); } public static void clearAll() { clearLabel(); EntomoLabelList.clearCurrentLabel(); //ActionButtonsManager.clearButtonsVisibility(); l_border.Visibility = Visibility.Hidden; CoreButtonsManager.hideButtons(); } private static void DrawLabel() { if (!EntomoLabelList.isLabelSelected()) return; clearLabel(); var labelset = EntomoLabelList.getCurrentLabel(); label_quantity.Text = labelset.LabelQuantity.ToString(); l_border.Width = labelset.LabelWidth * CONSTS.POINT_TO_SCREEN_SCALE * CONSTS.L_BORDER_SCALE; l_border.Height = labelset.LabelHeight * CONSTS.POINT_TO_SCREEN_SCALE * CONSTS.L_BORDER_SCALE; foreach (var element in labelset.Elements) { var _struct = drawElement(element); var ui_elem = _struct.ui_elem; var actionButtons = _struct.actionButtons; if (ui_elem != null) { canvas.Children.Add(ui_elem); ElementsManager.registerNewObject(ui_elem, element, actionButtons); } } } public static Element_AllData addNewElement(Element element) { var labelset = EntomoLabelList.getCurrentLabel(); labelset.Elements.Add(element); var _struct = drawElement(element); FrameworkElement frameworkElement = _struct.ui_elem; var actionButtons = _struct.actionButtons; canvas.Children.Add(frameworkElement); var extra_data = ElementsManager.registerNewObject(frameworkElement, element, actionButtons); object_selected.Items.Add(extra_data.name); return extra_data; } public static void deleteObject(Element_AllData extra_data) { // graficzne canvas.Children.Remove(extra_data.framework_element); // lista wyboru setObjectSelected(null); foreach(var name in object_selected.Items) { if (name.Equals(extra_data.name)) { object_selected.Items.Remove(name); break; } } // dane etykiety var labelset = EntomoLabelList.getCurrentLabel(); labelset.Elements.Remove(extra_data.element); } public static dynamic drawElement(Element element) { FrameworkElement ui_elem = null; List<ActionButtonsEnums> actionButtons = null; if (element is EL_TextBox) { EL_TextBox textBox = (EL_TextBox)element; if (textBox.IsEditable) { ui_elem = TextBoxRender.draw(textBox); actionButtons = TextBoxRender.getActionButtons(); } else { ui_elem = LabelRender.draw(textBox); actionButtons = LabelRender.getActionButtons(); } } else if (element is EL_Line) { ui_elem = ShapeRender.drawLine((EL_Line)element); actionButtons = ShapeRender.getLineActionButtons(); } else if (element is EL_Rectangle) { ui_elem = ShapeRender.drawRectangle((EL_Rectangle)element); actionButtons = ShapeRender.getRectangleActionButtons(); } else if (element is EL_Graphics) { ui_elem = ImageRender.draw((EL_Graphics)element); actionButtons = ImageRender.getActionButtons(); } return new { ui_elem, actionButtons }; } public static void create(string template) { var labelset = ReadTemplate(template); EntomoLabelList.addLabel(labelset, template); l_border.Visibility = Visibility.Visible; EntomoLabelList.setCurrentLabel_theLast(); // render(); //EntomoLabelList.updateCurrentRecordLabel(); // updateWidthHeightLabels(); } private static LabelSet ReadTemplate(string templateName) { string pathAndFileName = Globals.baseDir + @"\Templates\" + templateName + ".ELT"; if (File.Exists(pathAndFileName)) { LabelSet TemplateLabelSet = new LabelSet(); TemplateLabelSet = Utils.Deserialize<LabelSet>(pathAndFileName); return TemplateLabelSet; } else { LabelSet TemplateLabelSet = new LabelSet { TemplateName = "Default", LabelWidth = 14, LabelHeight = 7, LabelQuantity = 1, Elements = new List<Element> { new EL_Rectangle {X = 0, Y = 0, Width = 14, Height = 7, Radius = 0, Border = 0.5}, new EL_Graphics {X = 1, Y = 3.3, Width = 0.4, Height = 0.4, FileName = "pin_point.bmp"}, new EL_TextBox {X = 1.5, Y = 0.2, Width = 12.3, Height = 6.6, FontName = "Arial", FontSize = 4, Text = "Default", Bold = false, Italic = false, Vertical = 0, Justify = 0, Interline = 1.16, IsEditable = true } } }; return TemplateLabelSet; } } public static void setObjectSelected(string name) { // Tag potrzebny dla Object_selected_SelectionChanged // jest to rozwiazanie na problem dwukrotnego wywolania setFocusOnObject try { object_selected.Tag = "manual"; if (string.IsNullOrEmpty(name)) { object_selected.SelectedValue = -1; }else { object_selected.SelectedValue = name; } } finally { object_selected.Tag = null; } } internal static void delete() { EntomoLabelList.deleteCurrent(); if (EntomoLabelList.labelsListCount() > 0) { render(); //ActionButtonsManager.clearButtonsVisibility(); } else { clearAll(); } Globals.LabelsPackChanged = true; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SIPCA.CLASES.Models { [Table("DetalleCarrito")] public class DetalleCarrito { [Key] public int IdDetalleCarrito { get; set; } [Required(ErrorMessage = "Fallo en el {0} ")] [Display(Name = "Cantidad")] public int cantidad { get; set; } [Required(ErrorMessage = "Fallo en el {0} ")] [Display(Name = "Sub Total")] public float SubTotal { get; set; } [Required] [ScaffoldColumn(false)] public bool estado { get; set; } [Required] [DataType(DataType.DateTime)] [ScaffoldColumn(false)] public DateTime Fecha { get; set; } [Required(ErrorMessage = "Se requiere el {0}")] [Display(Name = "Producto")] public int ProductoId { get; set; } [ForeignKey("ProductoId")] public Producto Producto { get; set; } public int IdCarrito { get; set; } [ForeignKey("IdCarrito")] public virtual Carrito Carritos { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.PostProcessing; public class PostProcessingInGame : MonoBehaviour { public static PostProcessingInGame Instance = null; void Awake() { if (Instance == null) Instance = this; else if (Instance != this) Destroy(gameObject); } public PostProcessingBehaviour PostProcessingBehaviour; [HideInInspector] public PostProcessingProfile PostProcessingProfile; [HideInInspector] public ColorGradingModel.Settings gradient; [HideInInspector] public GrainModel.Settings grain; private Spawner spawner; private Coroutine FailLast, SuccessLast; private float period = 2.0f / 180.0f; void Start() { SettingUpPPVariables(); ResetPostProcess(); spawner = FindObjectOfType<Spawner>(); StartCoroutine(EffectsTimingCoroutine()); } private void SettingUpPPVariables() { PostProcessingProfile = PostProcessingBehaviour.profile; gradient = PostProcessingProfile.colorGrading.settings; grain = PostProcessingProfile.grain.settings; } private void ResetPostProcess() { gradient.basic.temperature = 0.0f; gradient.basic.hueShift = 0.0f; grain.intensity = 0.0f; PostProcessingProfile.grain.settings = grain; PostProcessingProfile.colorGrading.settings = gradient; } public void Fail() { if (FailLast != null) StopCoroutine(FailLast); FailLast = StartCoroutine(FailCoroutine()); } public void Success() { if (SuccessLast != null) StopCoroutine(SuccessCoroutine()); SuccessLast = StartCoroutine(SuccessCoroutine()); } public IEnumerator FailCoroutine() { for (int i = 0; i < 10; i++) { grain.intensity += 0.1f; PostProcessingProfile.grain.settings = grain; yield return new WaitForSeconds(0.01f); } for (int i = 0; i < 10; i++) { grain.intensity -= 0.1f; PostProcessingProfile.grain.settings = grain; yield return new WaitForSeconds(0.03f); } grain.intensity = 0.0f; PostProcessingProfile.grain.settings = grain; } public IEnumerator SuccessCoroutine() { for (int i = 0; i < 10; i++) { gradient.basic.temperature -= 10.0f; PostProcessingProfile.colorGrading.settings = gradient; yield return new WaitForSeconds(0.01f); } for (int i = 0; i < 10; i++) { gradient.basic.temperature += 10.0f; PostProcessingProfile.colorGrading.settings = gradient; yield return new WaitForSeconds(0.03f); } } public IEnumerator EffectsTimingCoroutine() { spawner.dropEffect = false; fun = false; yield return new WaitForSeconds(48f); spawner.dropEffect = true; fun = true; yield return new WaitForSeconds(20f); spawner.dropEffect = false; gradient.basic.hueShift = 0f; PostProcessingProfile.colorGrading.settings = gradient; fun = false; yield return new WaitForSeconds(39f); spawner.dropEffect = true; fun = true; yield return new WaitForSeconds(40f); spawner.dropEffect = false; gradient.basic.hueShift = 0f; PostProcessingProfile.colorGrading.settings = gradient; fun = false; yield return new WaitForSeconds(38f); spawner.dropEffect = true; fun = true; yield return new WaitForSeconds(19f); spawner.dropEffect = false; gradient.basic.hueShift = 0f; PostProcessingProfile.colorGrading.settings = gradient; fun = false; } float timer; bool fun = false; private void Update() { if (fun) { if (timer > period) { gradient.basic.hueShift -= 1.0f; PostProcessingProfile.colorGrading.settings = gradient; timer -= period; } timer += Time.deltaTime; } } }
//------------------------------------------------------------------- //版权所有:版权所有(C) 2010,Wakaoyun //系统名称: //作 者:dengqibin //邮箱地址:wakaoyun@gmail.com //创建日期:9/8/2010 10:41:44 AM //功能说明: //------------------------------------------------------------------- //修改 人: //修改时间: //修改内容: //------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace Wakaoyun.DQB.DataAccess.Interface { public interface IEntityHelper { T FillEntity<T>(DataRow dr); T FillEntity<T>(IDataReader dr); List<T> FillEntityList<T>(DataTable dt); List<T> FillEntityList<T>(IDataReader dr); } }
using UnityEngine; using UnityEngine.SceneManagement; public class MainMenu : MonoBehaviour { public void Solo() { SceneManager.LoadScene("Solo Menu"); } public void Multi() { } public void Options() { } public void Quit() { Application.Quit(); } }
using System; namespace Ganss.Excel { /// <summary> /// A caching factory of <see cref="TypeMapper"/> objects. /// </summary> public interface ITypeMapperFactory { /// <summary> /// Creates a <see cref="TypeMapper"/> for the specified type. /// </summary> /// <param name="type">The type to create a <see cref="TypeMapper"/> object for.</param> /// <returns>A <see cref="TypeMapper"/> for the specified type.</returns> TypeMapper Create(Type type); /// <summary> /// Creates a <see cref="TypeMapper"/> for the specified object. /// </summary> /// <param name="o">The object to create a <see cref="TypeMapper"/> object for.</param> /// <returns>A <see cref="TypeMapper"/> for the specified object.</returns> TypeMapper Create(object o); } }
using System; using System.Collections.Generic; using Sample.Domain.Shared; namespace Sample.Domain.V2 { public class Job { public Guid Id { get; set; } public Customer Customer { get; set; } public Status Status { get; set; } public string Location { get; set; } public List<Appointment> Appointments { get; set; } private Job(Guid id, Customer customer, string location = null) { if (customer == null) throw new Exception("Customer should be provided"); Id = id; Customer = customer; Location = location; Status = Status.Initiated; } public static Job Create(Customer customer, string location = null, List<Appointment> appointments = null) { Printer.Print(ConsoleColor.Cyan); return new Job(Guid.NewGuid(), customer, location) { Appointments = appointments }; } } }
using System.Runtime.Serialization; using BPiaoBao.Common.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Reflection; using BPiaoBao.Common; namespace BPiaoBao.AppServices.DataContracts.DomesticTicket { public class FlightResponse { public List<FlightLineResponse> List { get; set; } } public class FlightLineResponse { public FlightSkyWayResponse SkyWay { get; set; } public SeatResponse[] SeatList { get; set; } } /// <summary> /// /// </summary> public class FlightSkyWayResponse { /// <summary> /// 出发城市三字码 /// </summary> public string FromCityCode { get; set; } /// <summary> /// 到达城市三字码 /// </summary> public string ToCityCode { get; set; } /// <summary> /// 出发城市名称 /// </summary> public string FromCity { get; set; } /// <summary> /// 到达城市名称 /// </summary> public string ToCity { get; set; } /// <summary> /// 出发城市机场名称 /// </summary> public string FromAirPortrName { get; set; } /// <summary> /// 到达城市机场名称 /// </summary> public string ToAirPortrName { get; set; } /// <summary> /// 出发航站楼 /// </summary> public string FromTerminal { get; set; } /// <summary> /// 到达航站楼 /// </summary> public string ToTerminal { get; set; } /// <summary> /// 起飞时间 /// </summary> public DateTime StartDateTime { get; set; } public DateTime ToDateTime { get; set; } /// <summary> /// 航空公司编码 /// </summary> public string CarrayCode { get; set; } public string CarrayShortName { get; set; } /// <summary> /// 航班号 /// </summary> public string FlightNumber { get; set; } /// <summary> /// 机型 /// </summary> public string Model { get; set; } /// <summary> /// 机建费 /// </summary> public decimal TaxFee { get; set; } /// <summary> /// 燃油费 /// </summary> public decimal RQFee { get; set; } /// <summary> /// 是否经停 /// </summary> public bool IsStop { get; set; } /// <summary> /// 是否共享 /// </summary> public bool IsShareFlight { get; set; } } public class SeatResponse { /// <summary> /// 舱位 /// </summary> public string SeatCode { get; set; } /// <summary> /// 折扣 /// </summary> public decimal Discount { get; set; } /// <summary> /// 舱位价 /// </summary> public decimal SeatPrice { get; set; } /// <summary> /// IBE原始舱位价不变 /// </summary> public decimal IbeSeatPrice { get; set; } /// <summary> ///该航空公司的Y舱价格 /// </summary> public decimal YPrice { get; set; } /// <summary> /// 政策点数 /// </summary> public decimal PolicyPoint { get; set; } /// <summary> /// 剩余座位数 /// </summary> public string SeatCount { get; set; } /// <summary> /// 票面价 /// </summary> public decimal TicketPrice { get; set; } /// <summary> /// 政策特殊类型 /// </summary> public EnumPolicySpecialType PolicySpecialType { get; set; } } public class DestineResponse { public DestineResponse() { this.AdultPnrData = new PnrData(); this.ChdPnrData = new PnrData(); } /// <summary> /// 成人编码内容包含PAT /// </summary> public string AdultPnrContent { get; set; } /// <summary> /// 儿童编码内容 包含PAT /// </summary> public string ChdPnrContent { get; set; } /// <summary> /// 成人编码 /// </summary> public string AdultPnr { get; set; } /// <summary> /// 儿童编码 /// </summary> public string ChdPnr { get; set; } /// <summary> /// 是否显示换编码政策 /// </summary> public bool IsChangePnr { get; set; } /// <summary> /// 编码中的婴儿人数和预定的婴儿人数是否一致 /// </summary> public bool INFPnrIsSame = true; /// <summary> /// 成人的编码解析 /// </summary> public PnrData AdultPnrData { get; set; } /// <summary> /// 儿童的编码解析 /// </summary> public PnrData ChdPnrData { get; set; } } public class DestineRequest { public DestineSkyWayRequest[] SkyWay { get; set; } public PassengerRequest[] Passengers { get; set; } public string Tel { get; set; } /// <summary> /// 单独生成儿童编码时备注的成人PNR 这个从关联的订单号中获取成人编码 /// </summary> public string ChdRemarkAdultPnr { get; set; } /// <summary> /// 儿童关联成人订单号 /// </summary> public string OldOrderId { get; set; } /// <summary> /// 是否显示换编码政策 /// </summary> public bool IsChangePnr { get; set; } /// <summary> /// 多个价格(高低价格) true低价格(默认) false高价格 /// </summary> public bool IsLowPrice { get; set; } /// <summary> /// 政策特殊类型 /// </summary> public EnumPolicySpecialType PolicySpecialType { get; set; } /// <summary> /// 特价舱位价 /// </summary> public decimal SpecialPrice { get; set; } /// <summary> /// 特价机建 /// </summary> public decimal SpecialTax { get; set; } /// <summary> /// 特价燃油 /// </summary> public decimal SpecialFuelFee { get; set; } /// <summary> /// 特价Y舱的舱位价 /// </summary> public decimal SpecialYPrice { get; set; } /// <summary> /// Ibe机建费 /// </summary> public decimal IbeTaxFee { get; set; } /// <summary> /// Ibe燃油费 /// </summary> public decimal IbeRQFee { get; set; } /// <summary> /// Ibe舱位价 /// </summary> public decimal IbeSeatPrice { get; set; } /// <summary> /// 字符串显示 用于记录日志 /// </summary> /// <returns></returns> public override string ToString() { StringBuilder sbBuilder = new StringBuilder(); sbBuilder.Append("\r\n Tel=" + Tel + "\r\n"); if (SkyWay != null && SkyWay.Length > 0) { for (int i = 0; i < SkyWay.Length; i++) { sbBuilder.Append("航段" + (i + 1) + ":\r\n"); DestineSkyWayRequest item = SkyWay[i]; PropertyInfo[] properties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.GetProperty); object obj = null; foreach (PropertyInfo p in properties) { obj = p.GetValue(item, null); sbBuilder.Append(p.Name + "=" + (obj == null ? "null" : obj) + "\r\n"); } } } if (Passengers != null && Passengers.Length > 0) { for (int i = 0; i < Passengers.Length; i++) { sbBuilder.Append("乘客" + (i + 1) + ":\r\n"); PassengerRequest item = Passengers[i]; PropertyInfo[] properties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.GetProperty); object obj = null; foreach (PropertyInfo p in properties) { obj = p.GetValue(item, null); sbBuilder.Append(p.Name + "=" + (obj == null ? "null" : obj) + "\r\n"); } } } return sbBuilder.ToString(); } } public class DestineSkyWayRequest { /// <summary> /// 航空公司二字码 /// </summary> public string CarrayCode { get; set; } /// <summary> /// 航班号 /// </summary> public string FlightNumber { get; set; } /// <summary> /// 起飞日期和时间 /// </summary> public DateTime StartDate { get; set; } /// <summary> /// 到达时间 /// </summary> public DateTime EndDate { get; set; } /// <summary> /// 舱位 /// </summary> public string Seat { get; set; } /// <summary> /// 出发城市三字码 /// </summary> public string FromCityCode { get; set; } /// <summary> /// 到达城市城市三字码 /// </summary> public string ToCityCode { get; set; } /// <summary> /// 出发航站楼 /// </summary> public string FromTerminal { get; set; } /// <summary> /// 到达航站楼 /// </summary> public string ToTerminal { get; set; } /// <summary> /// 折扣 /// </summary> public decimal? Discount { get; set; } /// <summary> /// 机型 /// </summary> public string FlightModel { get; set; } /// <summary> /// 机建费 /// </summary> public decimal TaxFee { get; set; } /// <summary> /// 燃油费 /// </summary> public decimal RQFee { get; set; } /// <summary> /// 舱位价 /// </summary> public decimal SeatPrice { get; set; } /// <summary> /// 政策特殊类型 /// </summary> public EnumPolicySpecialType PolicySpecialType { get; set; } /// <summary> /// 特价舱位价 /// </summary> public decimal SpecialPrice { get; set; } /// <summary> /// 特价机建 /// </summary> public decimal SpecialTax { get; set; } /// <summary> /// 特价燃油 /// </summary> public decimal SpecialFuelFee { get; set; } /// <summary> /// 特价Y舱的舱位价 /// </summary> public decimal SpecialYPrice { get; set; } } public class PassengerRequest { /// <summary> /// 乘客姓名 /// </summary> public string PassengerName { get; set; } /// <summary> /// 航空公司卡号 /// </summary> public string MemberCard { get; set; } /// <summary> /// 1.成人 2.儿童 3.婴儿 /// </summary> public int PassengerType { get; set; } /// <summary> /// 证件类型 /// </summary> public EnumIDType IdType { get; set; } /// <summary> /// 性别类型 /// </summary> public EnumSexType SexType { get; set; } /// <summary> /// 证件号 /// </summary> public string CardNo { get; set; } /// <summary> /// 乘客类型为儿童或者婴儿的出生日期 /// </summary> public DateTime ChdBirthday { get; set; } /// <summary> /// 联系人手机号 /// </summary> public string LinkPhone { get; set; } /// <summary> /// 出生日期 /// </summary> public DateTime? Birth { get; set; } } public enum PnrType { /// <summary> /// 成人编码 /// </summary> [Description("成人编码")] Adult = 1, /// <summary> /// 儿童编码 /// </summary> [Description("儿童编码")] Child = 2 } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Xamarin.Forms; using static City_Center.Models.EventosResultado; using GalaSoft.MvvmLight.Helpers; using City_Center.ViewModels; using City_Center.Clases; using System.Linq; using Xamarin.Forms; namespace City_Center.Page.SlideMenu { public partial class TerminosCondiciones : ContentPage { public TerminosCondiciones() { InitializeComponent(); NavigationPage.SetTitleIcon(this, "logo@2x.png.png"); } protected override void OnDisappearing() { base.OnDisappearing(); ActualizaBarra.Cambio(VariablesGlobales.VentanaActual); GC.Collect(); } } }
using System.Collections.Generic; using System.Threading.Tasks; namespace HangmanGame.App.Services.Interfaces { internal interface IWordsProvider { IReadOnlyCollection<string> GetWordCategories(); Task<IReadOnlyCollection<string>> GetWordsByCategoryOrEmptyAsync(string category); Task<IReadOnlyCollection<string>> GetWordsByCategoryAsync(string category); } }
namespace CRM.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class CreateSomeEntities : DbMigration { public override void Up() { DropForeignKey("dbo.Offers", "CustomerId", "dbo.Customers"); DropForeignKey("dbo.Offers", "EmployeeId", "dbo.Employees"); DropForeignKey("dbo.ProductOffer", "ProductRefId", "dbo.Offers"); DropForeignKey("dbo.ProductOffer", "OfferRefId", "dbo.Products"); DropIndex("dbo.Offers", new[] { "CustomerId" }); DropIndex("dbo.Offers", new[] { "EmployeeId" }); DropIndex("dbo.ProductOffer", new[] { "ProductRefId" }); DropIndex("dbo.ProductOffer", new[] { "OfferRefId" }); CreateTable( "dbo.OfferItems", c => new { Id = c.Guid(nullable: false), SerialNumber = c.String(), ProductName = c.String(), Stock = c.Int(nullable: false), OfferPrice = c.Decimal(nullable: false, precision: 18, scale: 2), Quantity = c.Decimal(nullable: false, precision: 18, scale: 2), CustomerId = c.Guid(), ProductId = c.Guid(), OfferId = c.Guid(), CreatedBy = c.String(), CreatedAt = c.DateTime(nullable: false), UpdatedBy = c.String(), UpdatedAt = c.DateTime(), Employee_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Customers", t => t.CustomerId) .ForeignKey("dbo.Offers", t => t.OfferId) .ForeignKey("dbo.Products", t => t.ProductId) .ForeignKey("dbo.Employees", t => t.Employee_Id) .Index(t => t.CustomerId) .Index(t => t.ProductId) .Index(t => t.OfferId) .Index(t => t.Employee_Id); DropColumn("dbo.Offers", "Description"); DropColumn("dbo.Offers", "Amount"); DropColumn("dbo.Offers", "CustomerId"); DropColumn("dbo.Offers", "EmployeeId"); DropColumn("dbo.OrderItems", "OrderNumber"); DropTable("dbo.ProductOffer"); } public override void Down() { CreateTable( "dbo.ProductOffer", c => new { ProductRefId = c.Guid(nullable: false), OfferRefId = c.Guid(nullable: false), }) .PrimaryKey(t => new { t.ProductRefId, t.OfferRefId }); AddColumn("dbo.OrderItems", "OrderNumber", c => c.Guid()); AddColumn("dbo.Offers", "EmployeeId", c => c.Guid(nullable: false)); AddColumn("dbo.Offers", "CustomerId", c => c.Guid(nullable: false)); AddColumn("dbo.Offers", "Amount", c => c.String(nullable: false, maxLength: 100)); AddColumn("dbo.Offers", "Description", c => c.String(nullable: false, maxLength: 1000)); DropForeignKey("dbo.OfferItems", "Employee_Id", "dbo.Employees"); DropForeignKey("dbo.OfferItems", "ProductId", "dbo.Products"); DropForeignKey("dbo.OfferItems", "OfferId", "dbo.Offers"); DropForeignKey("dbo.OfferItems", "CustomerId", "dbo.Customers"); DropIndex("dbo.OfferItems", new[] { "Employee_Id" }); DropIndex("dbo.OfferItems", new[] { "OfferId" }); DropIndex("dbo.OfferItems", new[] { "ProductId" }); DropIndex("dbo.OfferItems", new[] { "CustomerId" }); DropTable("dbo.OfferItems"); CreateIndex("dbo.ProductOffer", "OfferRefId"); CreateIndex("dbo.ProductOffer", "ProductRefId"); CreateIndex("dbo.Offers", "EmployeeId"); CreateIndex("dbo.Offers", "CustomerId"); AddForeignKey("dbo.ProductOffer", "OfferRefId", "dbo.Products", "Id", cascadeDelete: true); AddForeignKey("dbo.ProductOffer", "ProductRefId", "dbo.Offers", "Id", cascadeDelete: true); AddForeignKey("dbo.Offers", "EmployeeId", "dbo.Employees", "Id", cascadeDelete: true); AddForeignKey("dbo.Offers", "CustomerId", "dbo.Customers", "Id", cascadeDelete: true); } } }
namespace YoctoScheduler.Core.ExecutionTasks.PowerShell { public struct Configuration { public string Script; } }
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== // // // Notes: // // ============================================================================ // using System; namespace EnhancedEditor { /// <summary> /// Ends a foldout group began with <see cref="BeginFoldoutAttribute"/>. /// </summary> [AttributeUsage(AttributeTargets.Field, AllowMultiple = true, Inherited = true)] public class EndFoldoutAttribute : EnhancedPropertyAttribute { } }
using UnityEngine; using System.Collections; namespace Ph.Bouncer { public class DebugSceneName : MonoBehaviour { void Start() { UILabel label = GetComponent<UILabel>(); label.text = Application.loadedLevelName; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace OMIKAS { public partial class AlloyAllForm : ContentPage { /// <summary> /// Konstruktor okna z lista skladnikow stopowych /// </summary> public AlloyAllForm() { InitializeComponent(); //Wypelnij liste na ekranie wszystkimi stopami jakie sa w bazie alloymetalView.ItemsSource = App.DAUtil.GetAllAlloys(); } /// <summary> /// Pokazuje okno z informacja o konkretnym skladniku stopowym /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void btn_info_Clicked(object sender, EventArgs e) { //Klikniety przycisk jest sygnalem ktory powiazuje kontekts z skladnikiem stopowym z listy var signal = sender as Button; var metal = signal.BindingContext as Alloy; //odpal ta strone z informacja o skladniku await Navigation.PushAsync(new AlloyDetailForm(metal)); } /// <summary> /// Wyswietla komunikat z zapytaniem czy usunac skladnik /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void btn_delAlloy_Clicked(object sender, EventArgs e) { //Klikniety przycisk jest sygnalem ktory powiazuje kontekts z skladnikiem stopowym z listy var signal = sender as Button; var metal = signal.BindingContext as Alloy; //Na podstawie odpowiedzi usun skladnik z bazy var answer = await DisplayAlert("Usun", "Na pewno usunac " + metal.name + "?", "Tak", "Nie"); if(answer) { App.DAUtil.DeleteAlloy(metal); } OnAppearing(); //A nastepnie uruchom funkcje odswiezajaca ekran } /// <summary> /// Pokazuje okno dodania nowego elementu do skladnikow /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void btn_addAlloy_Clicked(object sender, EventArgs e) { //Konstruktor okna bez argumentow = dodaj nowy element await Navigation.PushAsync(new AlloyEditForm()); } /// <summary> /// Pokazuje okno edycji skladnika stopowego /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void btn_editAlloy_Clicked(object sender, EventArgs e) { //Klikniety przycisk jest sygnalem ktory powiazuje kontekts z skladnikiem stopowym z listy var signal = sender as Button; var metal = signal.BindingContext as Alloy; //Konstruktor okna z dwoma argumentami = edycja istniejacego elementu await Navigation.PushAsync(new AlloyEditForm(metal, App.alloymetals.IndexOf(metal))); } /// <summary> /// Powrot do poprzedniego okna /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ToolbarItem_Clicked(object sender, EventArgs e) { //Schowaj ten ekran await Navigation.PopModalAsync(); } /// <summary> /// Po pojawieniu się ekranu, odświeża listę i sortuje ją alfabetycznie /// </summary> protected override void OnAppearing() { //Dla poprawnego dzialania zeruje widok listy i cala liste laduje z bazy alloymetalView.ItemsSource = null; var currentList = App.DAUtil.GetAllAlloys(); this.alloymetalView.ItemsSource = currentList; var newList = currentList.OrderBy(x => x.name).ToList(); this.alloymetalView.ItemsSource = newList; } } }
using System; using System.Text.RegularExpressions; using Bjerner.LoremIpsum; using Bjerner.LoremIpsum.Providers; namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { LoremIpsumGenerator generator = new LoremIpsumGenerator(); foreach (string str in generator.MakeParagraphs()) { Content.Text += "<pre style=\"white-space: pre-wrap;\">" + Validate(str) + "</pre>\n"; } Content.Text += "<hr />"; Content.Text += "<pre style=\"white-space: pre-wrap;\">" + Validate(generator.MakeParagraph(LoremIpsumType.WordsAndFillers)) + "</pre>\n"; Content.Text += "<pre style=\"white-space: pre-wrap;\">" + Validate(generator.MakeParagraph(LoremIpsumType.WordsAndFillers)) + "</pre>\n"; Content.Text += "<pre style=\"white-space: pre-wrap;\">" + Validate(generator.MakeParagraph(LoremIpsumType.WordsAndFillers)) + "</pre>\n"; Content.Text += "<hr />"; foreach (string str in generator.MakeParagraphs(LoremIpsumType.Words)) { Content.Text += "<pre style=\"white-space: pre-wrap;\">" + Validate(str) + "</pre>\n"; } Content.Text += "<hr />"; Content.Text += "<pre style=\"white-space: pre-wrap;\">" + Validate(generator.MakeParagraph(LoremIpsumType.Words)) + "</pre>\n"; Content.Text += "<pre style=\"white-space: pre-wrap;\">" + Validate(generator.MakeParagraph(LoremIpsumType.Words)) + "</pre>\n"; Content.Text += "<pre style=\"white-space: pre-wrap;\">" + Validate(generator.MakeParagraph(LoremIpsumType.Words)) + "</pre>\n"; } public static string Validate(string str) { bool valid = true; str = Regex.Replace(str, "(\\. [a-z])", delegate(Match match) { valid = false; return "<span style=\"background: #f7c8c8; color: #880000;\">" + match.Value + "</span>"; }); return "<span style=\"background: " + (valid ? "#dfd" : "#fdd") + ";\">" + str + "</span>"; } } }
using amsdemo.Models; using amsdemo.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace amsdemo.DAL.Interface { public interface IEmployeeRepository { IEnumerable<tblEmployee> GetAll(); tblEmployee GetById(int employeeId); void Add(tblEmployee obj); void Update(int employeeid,int userid); IEnumerable<tblPosition> Getpos(); void Delete(int employeeId); void Save(); } }
using course_voiture.operation_publique; using course_voiture.terrain; using course_voiture.userinterface; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace course_voiture.voiture { class Lent : Voiture { /// <summary> /// constructeur /// </summary> /// <parametre name="p_couleur"></le couleur de la voiture> public Lent(string p_couleur) { Console.WriteLine("Votre voiture lent a ete cree elle est de couleur {0}", p_couleur); } /// <summary> /// fonction pour le parcours du terrain /// </summary> /// <parametre name="p_terrain_course"></objet terrain creer c est le terrain a parcourir> /// <parametre name="p_vitesse_moyenne"></la vitesse moyenne> protected override internal void parcours_terrain(Terrain p_terrain_course , int p_vitesse_moyenne) { Stopwatch timer = new Stopwatch(); timer.Start(); while (p_terrain_course.distance > 0) { bool boost = false; p_vitesse_moyenne = 14; p_vitesse_moyenne = Boost_vitesse(100, boost, p_vitesse_moyenne); p_terrain_course.distance = p_terrain_course.distance - p_vitesse_moyenne; Console.WriteLine("Vitesse moyenne : {0}", p_vitesse_moyenne); Console.WriteLine("Distance restante: {0}", p_terrain_course.distance); Thread.Sleep(1000); } timer.Stop(); // Format par defaut du Stopwatch. TimeSpan ts = timer.Elapsed; // Changement de format de heure,minute seconde. string elapsedTime = String.Format("{0:00} heures:{1:00} minutes:{2:00} secondes.{3:00} millisecondes", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("Fin de la course votre temps de course est:"); Console.WriteLine(elapsedTime); } /// <summary> /// fonction pour le boost de vitesse /// </summary> /// <parametre name="max_chance"></chance maximale quand j ai appele j y ai mis 100 pour 100%> /// <parametre name="p_boost"></variable boolean pour verifier si boost est activer> /// <parametre name="vitesse"></variable de la vitesse_moyenne qui change d apres les condition de boost> /// <returns></returns> internal static int Boost_vitesse(int max_chance, bool p_boost , int vitesse) { Random rnd = new Random(); int chance = rnd.Next(max_chance + 1); //car 1,13 donne un nb de 1 a 12 et si 52 ce sera de 0 a 51 //on va supposer que max_chance et egale a 100 pour random value entre 0 et 100 //si le nombre est entre 0 et 60 alors la piece de voiture est casse pour 60% if (0 <= chance && chance <= 30 && p_boost == false) { p_boost = Ok_vitesse(p_boost); Console.WriteLine(p_boost); if (true) { vitesse = 33; } else if (false) { vitesse = 14; } else { Console.WriteLine("ni l un ni l autre"); } } return vitesse; } /// <summary> /// fonciton qui retourn un boolean pour savoir si la vitesse apres sera active(1 des conditions d activation) /// </summary> /// <param name="p_boost"></variable boolean pour le boost de vitesse> /// <returns></returns> protected static bool Ok_vitesse(bool p_boost) { Stopwatch time_boost = new Stopwatch(); //debut d'un timer pour compter les 3 secondes time_boost.Start(); TimeSpan ts = time_boost.Elapsed; //Ici on va commencer le melange de mot pour VITESSE string mot = "VITESSE"; //j ai creer 4 mot_melange different car ca renvoie le meme mot melange a chq fois suivi d'un switch pour l'application string mot_melange = Operation.mot_melange(mot); string mot_melange1 = Operation.mot_melange(mot_melange); string mot_melange2 = Operation.mot_melange(mot_melange1); string mot_melange3 = Operation.mot_melange(mot_melange2); string mot_melange4 = Operation.mot_melange(mot_melange3); Random rnd = new Random(); int chance = rnd.Next(4); //car 1,13 donne un nb de 1 a 12 et si 52 ce sera de 0 a 51 //on va supposer que max_chance et egale a 100 pour random value entre 0 et 100 //si le nombre est entre 0 et 60 alors la piece de voiture est casse pour 60% switch (chance) { case 0: //Ici s'arrete le mot avec un variable string qu 'on recoit du mot_melangee avec le mot VITESSE melange Console.WriteLine("Bravo entrez {0} dans les 3 secondes qui suivent pour" + "avoir un booste de vitesse :", mot_melange); string votreVariable = Operation.enregistrer_variable_string(); Console.WriteLine(time_boost.ElapsedMilliseconds); if (time_boost.ElapsedMilliseconds <= 3000 && votreVariable == mot_melange) { p_boost = true; Console.WriteLine(mot_melange); } else { p_boost = false; Console.WriteLine(mot_melange); } break; case 1: //Ici s'arrete le mot avec un variable string qu 'on recoit du mot_melangee avec le mot VITESSE melange Console.WriteLine("Bravo entrez {0} dans les 3 secondes qui suivent pour" + "avoir un booste de vitesse :", mot_melange1); string votreVariable1 = Operation.enregistrer_variable_string(); Console.WriteLine(time_boost.ElapsedMilliseconds); if (time_boost.ElapsedMilliseconds <= 3000 && votreVariable1 == mot_melange1) { p_boost = true; Console.WriteLine(mot_melange1); } else { p_boost = false; Console.WriteLine(mot_melange1); } break; case 2: //Ici s'arrete le mot avec un variable string qu 'on recoit du mot_melangee avec le mot VITESSE melange Console.WriteLine("Bravo entrez {0} dans les 3 secondes qui suivent pour" + "avoir un booste de vitesse :", mot_melange2); string votreVariable2 = Operation.enregistrer_variable_string(); Console.WriteLine(time_boost.ElapsedMilliseconds); if (time_boost.ElapsedMilliseconds <= 3000 && votreVariable2 == mot_melange2) { p_boost = true; Console.WriteLine(mot_melange2); } else { p_boost = false; Console.WriteLine(mot_melange2); } break; case 3: //Ici s'arrete le mot avec un variable string qu 'on recoit du mot_melangee avec le mot VITESSE melange Console.WriteLine("Bravo entrez {0} dans les 3 secondes qui suivent pour" + "avoir un booste de vitesse :", mot_melange3); string votreVariable3 = Operation.enregistrer_variable_string(); Console.WriteLine(time_boost.ElapsedMilliseconds); if (time_boost.ElapsedMilliseconds <= 3000 && votreVariable3 == mot_melange3) { p_boost = true; Console.WriteLine(mot_melange3); } else { p_boost = false; Console.WriteLine(mot_melange3); } break; case 4: //Ici s'arrete le mot avec un variable string qu 'on recoit du mot_melangee avec le mot VITESSE melange Console.WriteLine("Bravo entrez {0} dans les 3 secondes qui suivent pour" + "avoir un booste de vitesse :", mot_melange4); string votreVariable4 = Operation.enregistrer_variable_string(); Console.WriteLine(time_boost.ElapsedMilliseconds); if (time_boost.ElapsedMilliseconds <= 3000 && votreVariable4 == mot_melange4) { p_boost = true; Console.WriteLine(mot_melange4); } else { p_boost = false; Console.WriteLine(mot_melange4); } break; default: Console.WriteLine("default case"); break; } //arret du timer time_boost.Stop(); mot_melange=null; return p_boost; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using BPiaoBao.AppServices.Contracts.SystemSetting; using BPiaoBao.AppServices.DataContracts.SystemSetting; using BPiaoBao.Client.UIExt; using GalaSoft.MvvmLight.Threading; namespace BPiaoBao.Client.SystemSetting.ViewModel { /// <summary> /// 赠送短信ViewModel /// </summary> public class GiveDetailViewModel : PageBaseViewModel { #region 实例对象 private static GiveDetailViewModel _instance; public static GiveDetailViewModel CreateInstance() { if (_instance == null) _instance = new GiveDetailViewModel(); _instance.Init(); return _instance; } #endregion #region 公开属性 #region GiveDetailDto private const string GiveDetailDtoPropertyName = "GiveDetailDtos"; private List<GiveDetailDto> _giveDetailDtos; public List<GiveDetailDto> GiveDetailDtos { get { return _giveDetailDtos; } set { if (_giveDetailDtos == value) return; RaisePropertyChanging(GiveDetailDtoPropertyName); _giveDetailDtos = value; RaisePropertyChanged(GiveDetailDtoPropertyName); } } #endregion #endregion #region 公开命令 #region QueryCommand protected override void ExecuteQueryCommand() { Init(); } #endregion #endregion #region 公开方法 public void Init() { if (StartTime != null & EndTime != null) { if (DateTime.Compare(StartTime.Value, EndTime.Value) > 0) { UIManager.ShowMessage("结束时间大于开始时间"); return; } } IsBusy = true; Action action = () => CommunicateManager.Invoke<IBusinessmanService>(service => { var data = service.GetSmsGiveDetail(CurrentPageIndex, PageSize, StartTime, EndTime); if (data.TotalCount <= 0) return; TotalCount = data.TotalCount; GiveDetailDtos = data.List; }, UIManager.ShowErr); Task.Factory.StartNew(action).ContinueWith(task => { Action setAction = () => { IsBusy = false; }; DispatcherHelper.UIDispatcher.Invoke(setAction); }); } #endregion } }
namespace College.Model.Models { public class CollegeInstitution : BaseModel { public string Name { get; set; } public string Address { get; set; } public int CityId { get; set; } public City City { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SniperGolf_ClubController : MonoBehaviour { public Transform clubPosition; public SniperGolf_GolfHit golfController; SniperGolf_PowerMinigameController minigame; Vector3 targetPos; Vector3 targRot; Vector3 golfSwingRot; float snapBackSpeed = 1; // Start is called before the first frame update void Start() { minigame = golfController.powerMinigame; minigame.hitSpaceUpdate.AddListener(AddToTargetRot); minigame.hitSpace.AddListener(SnapBack); } void AddToTargetRot(float progress) { golfSwingRot = new Vector3(0, 0, -progress * 90); } void SnapBack(float progress) { golfSwingRot = Vector3.zero; snapBackSpeed = 5.0f; } // Update is called once per frame void Update() { if (golfController.canHit) { targetPos = golfController.transform.position - (golfController.transform.position - golfController.player.transform.position).normalized *0.3f; var targetRot = golfController.transform.position - this.transform.position; var angle = Mathf.Atan2(targetRot.y, targetRot.x) * Mathf.Rad2Deg; targRot = new Vector3(0, 0, angle); } else { targetPos = clubPosition.position; targRot = Vector3.zero; } var target = Vector3.Lerp(this.transform.position, targetPos, Time.deltaTime * 3); this.transform.position = new Vector3(target.x, target.y, this.transform.position.z); if (snapBackSpeed > 1) { snapBackSpeed -= Time.deltaTime * 3; } this.transform.rotation = Quaternion.Lerp(this.transform.rotation, Quaternion.Euler(targRot + golfSwingRot), Time.deltaTime * 3 * snapBackSpeed); } }
using MySql.Data.MySqlClient; using ShopBillingApp.BAL; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ShopBillingApp.DAL { class ProductDAL { DB C = new DB(); public int InsertProduct(ProductBAL B) { try { DataTable dt = CheckProductByName(B.Product_Name); int Res=0; foreach (DataRow dr in dt.Rows) { Res = Convert.ToInt32(dr[0].ToString()); } if (Res == 0) { using (C.Con) { MySqlCommand cmd = new MySqlCommand("AddProduct", C.Con) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.Add(new MySqlParameter("P_Name", B.Product_Name)); cmd.Parameters.Add(new MySqlParameter("Brand_ID", B.Brand_ID)); cmd.Parameters.Add(new MySqlParameter("B_Rate", B.Selling_Rate)); cmd.Parameters.Add(new MySqlParameter("S_Rate", B.Product_Cost)); cmd.Parameters.Add(new MySqlParameter("Description", B.Description)); cmd.Connection.Open(); int Result = cmd.ExecuteNonQuery(); C.Con.Close(); return Result; } } else { MessageBox.Show("Entered Product "+ B.Product_Name + " Exist Already! Please Use a Unique Name for Each Product"); return 0; } } catch (Exception ex) { MessageBox.Show(ex.Message); return 0; } } public DataTable CheckProductByName(string PName) { try { MySqlCommand cmd = new MySqlCommand("CheckExistingProductByName", C.Con) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.Add(new MySqlParameter("P_Name", PName)); MySqlDataAdapter Sda = new MySqlDataAdapter(cmd); DataTable dt = new DataTable(); Sda.Fill(dt); return dt; } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } } public DataTable LoadDGVProducts() { try { MySqlCommand cmd = new MySqlCommand("LoadDGVProducts", C.Con) { CommandType = CommandType.StoredProcedure }; MySqlDataAdapter Sda = new MySqlDataAdapter(cmd); DataTable dt = new DataTable(); Sda.Fill(dt); return dt; } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } } public DataTable LoadProductID(string PName) { try { MySqlCommand cmd = new MySqlCommand("GetProductID", C.Con) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.Add(new MySqlParameter("Pro_Name", PName)); MySqlDataAdapter Sda = new MySqlDataAdapter(cmd); DataTable dt = new DataTable(); Sda.Fill(dt); return dt; } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } } public int UpdateProduct(ProductBAL B) { try { using (C.Con) { MySqlCommand cmd = new MySqlCommand("UpdateProduct", C.Con) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.Add(new MySqlParameter("P_ID", B.Product_ID)); cmd.Parameters.Add(new MySqlParameter("P_Name", B.Product_Name)); cmd.Parameters.Add(new MySqlParameter("B_ID", B.Brand_ID)); cmd.Parameters.Add(new MySqlParameter("B_Rate", B.Product_Cost)); cmd.Parameters.Add(new MySqlParameter("S_Rate", B.Selling_Rate)); cmd.Parameters.Add(new MySqlParameter("Description", B.Description)); cmd.Connection.Open(); int Result = cmd.ExecuteNonQuery(); C.Con.Close(); return Result; } } catch (Exception ex) { MessageBox.Show(ex.Message); throw; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using TryToCloneMy.Game; using TryToCloneMe.Models; namespace TryToCloneMe.UI.Components { public class GestureDrawing : MonoBehaviour { public GameObject PointElement; List<GameObject> _HidenObjectsPool; List<GameObject> _ActivatedObjectsPool; void Start() { _ActivatedObjectsPool = new List<GameObject>(); _HidenObjectsPool = new List<GameObject>(); GameManager.Instance.OnGestureUpdate += _OnGestureUpdate; GameManager.Instance.OnGameOver += HideAll; } private void _OnGestureUpdate(GestureObject obj) { HideAll(); if (obj.PointArray != null) { foreach (Vector3 tmPos in obj.PointArray) { CreateGameObject(tmPos); } } } public void HideAll() { foreach (GameObject go in _ActivatedObjectsPool) { go.SetActive(false); _HidenObjectsPool.Add(go); } _ActivatedObjectsPool.Clear(); } public void CreateGameObject(Vector3 position) { GameObject go; if (_HidenObjectsPool.Count > 0) { go = _HidenObjectsPool[0]; _HidenObjectsPool.Remove(go); _ActivatedObjectsPool.Add(go); go.SetActive(true); } else { go = Instantiate(PointElement, Vector3.zero, new Quaternion()) as GameObject; go.transform.SetParent(transform); _ActivatedObjectsPool.Add(go); } go.transform.localPosition = position; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Select : MonoBehaviour { public GameObject outline; public GameObject parent; public bool unit; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0)) { RaycastHit hitInfo = new RaycastHit(); if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo) && hitInfo.transform.gameObject == this.transform.gameObject) { outline.SetActive(true); if (unit) { parent.GetComponent<Unit>().selected = true; parent.GetComponent<Build>().selected = true; } else { parent.GetComponent<Factory>().selected = true; } } else if(!Input.GetKey(KeyCode.LeftControl)) { outline.SetActive(false); if (unit) { parent.GetComponent<Unit>().selected = false; parent.GetComponent<Build>().selected = false; } else { parent.GetComponent<Factory>().selected = false; } } } } }
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.RazorPages; using WebMongo.Model; using WebMongo.Service; namespace WebMongo.Pages { public class IndexModel : PageModel { private readonly MongoService _service; public List<Formation> Formations { get; private set; } public IndexModel(MongoService service) { _service = service; } public void OnGet() { Formations = _service.Get(); } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL { public static class ConnectionString { //public static SqlConnection Connection { get; set; } = new SqlConnection("Data Source=vetontracksqlserver.ce7vxurcnd8m.sa-east-1.rds.amazonaws.com;Initial Catalog=BDVetOnTrack;User ID=admin;Password=12345678"); public static SqlConnection Connection { get; set; } = new SqlConnection(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=model;Integrated Security=True"); } }
using System.Collections.Generic; using System.Linq; namespace HaloSharp.Model { public class ValidationResult { public ValidationResult() { Messages = new List<string>(); } public List<string> Messages { get; } public bool Success => !Messages.Any(); } }
using System; using System.Collections; using System.Diagnostics; using UnityEngine; namespace RO { [CustomLuaClass] public class SceneAnimation : LuaGameObject { public Animator animator; public SpriteFade screenMask; public float screenMaskFadeDuration = 1f; private Coroutine checkEndCoroutine; [DebuggerHidden] private IEnumerator CheckEnd() { SceneAnimation.<CheckEnd>c__Iterator2F <CheckEnd>c__Iterator2F = new SceneAnimation.<CheckEnd>c__Iterator2F(); <CheckEnd>c__Iterator2F.<>f__this = this; return <CheckEnd>c__Iterator2F; } public void DoStop() { if (this.checkEndCoroutine == null) { return; } this.checkEndCoroutine = null; if (null != this.screenMask) { this.screenMask.FadeOut(); } this.animator.set_enabled(false); } public void Play() { if (this.checkEndCoroutine != null) { return; } this.animator.set_enabled(true); this.checkEndCoroutine = base.StartCoroutine(this.CheckEnd()); } public void Stop() { if (this.checkEndCoroutine == null) { return; } if (null != this.screenMask) { if (this.screenMask.phase == SpriteFade.Phase.INVISIBLE) { this.screenMask.fadeDuration = this.screenMaskFadeDuration; this.screenMask.FullScreen(); this.screenMask.FadeIn(); } } else { this.DoStop(); } } [DoNotToLua] public void ActionEvent_ScreenMaskFadeIn(float duration) { if (null != this.screenMask) { this.screenMask.fadeDuration = duration; this.screenMask.FullScreen(); this.screenMask.FadeIn(); } } protected override void Awake() { this.animator.set_enabled(false); base.Awake(); } } }
using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using NetCoreWebApp.Controllers; using NetCoreWebApp.Models; using NetCoreWebApp.Models.Repositories; using System.Collections.Generic; namespace NetCoreWebAppTests { [TestClass] public class HomeControllerTests { [TestMethod] public void DataAction_CharacterObjectReturned() { //Arrange Mock<ICharacterRepository> characterRepository = new Mock<ICharacterRepository>(); characterRepository.Setup(x => x.GetCharacters()).Returns(new List<Character>() { new Character() }); var homeController = new HomeController(characterRepository.Object); //Act var viewResult = homeController.Data(); //Assert var character = viewResult.ViewData["character"]; Assert.IsInstanceOfType(character, typeof(Character)); } } }
namespace Count_of_Given_Element_in_Array { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class CountOfGivenElementInArray { static void Main(string[] args) { //read the input and split into array; var input = Console.ReadLine().Split(' ').Select(double.Parse).ToArray(); //read the match number; var matchNumber = double.Parse(Console.ReadLine()); //var count of match numbers; var countMatch = 0; for (int i = 0; i < input.Length; i++) { if (input[i] == matchNumber) { countMatch++; } } Console.WriteLine(countMatch); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; using static System.Diagnostics.Debug; namespace UnidebRSA.Algorithms { public static class RandomBitNumberGenerator { public static async Task<BigInteger> Random(int bitCount) { BigInteger result = new BigInteger(1); BigInteger toAdd = new BigInteger(2); var randomizer = new Random(Guid.NewGuid().GetHashCode() * Environment.TickCount); for (var i = 1; i < bitCount; i++) { var shouldAdd = randomizer.Next(0, 2); if (shouldAdd == 1) result = result + toAdd; toAdd = toAdd << 1; } //WriteLine(result); return result; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace LoginRegistration { public partial class ChangePassword : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["UserIDforPassword"] == null) Response.Redirect("ForgotPassword.aspx"); } protected void Button1_Click(object sender, EventArgs e) { if (Password1.Text == "" || Password2.Text == "") { message.Attributes.Add("class", "alert-danger"); message.Text = "Please Fill all the Fields"; } else if (Password2.Text != Password1.Text) { message.Attributes.Add("class", "alert-danger"); message.Text = "Passwords are not matching"; } else { try { string id = Session["UserIDforPassword"].ToString(); string pass = Password1.Text; using (SqlConnection connectionString = new SqlConnection(ConfigurationManager.ConnectionStrings["TempConnectionString1"].ConnectionString)) { connectionString.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = connectionString; cmd.CommandText = "USP_ChangePassword"; cmd.Parameters.Add("@UserID", SqlDbType.VarChar).Value = id; cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = pass; cmd.CommandType = CommandType.StoredProcedure; int rd = cmd.ExecuteNonQuery(); if (rd > 0) { message.Attributes.Add("class", "alert-success"); message.Text = "Change password Successful"; Password1.Text = ""; Password2.Text = ""; Session["UserIDforPassword"] = null; } else throw (new Exception()); } } catch (Exception ex) { message.Attributes.Add("class", "alert-danger"); message.Text = "Change Password Failed"; } } } protected void Button2_Click1(object sender, EventArgs e) { Session["UserIDforPassword"] = null; Session.Clear(); Response.Redirect("Login.aspx"); } } }
using System; using System.Linq; using System.Security.Cryptography; using System.Text; namespace OhSoSecure.Core.Security { public class HashedPassword { protected HashedPassword() {} public HashedPassword(string password) { PasswordSalt = CreateSalt(); PasswordHash = CreateHash(password, PasswordSalt); } public HashedPassword(string passwordHash, string salt) { PasswordHash = passwordHash; PasswordSalt = salt; } public virtual string PasswordHash { get; private set; } public virtual string PasswordSalt { get; private set; } public bool Matches(string password) { var hashAttempt = CreateHash(password, PasswordSalt); return PasswordHash == hashAttempt; } static string CreateHash(string password, string salt) { var passwordBytes = Encoding.UTF8.GetBytes(password); var saltBytes = Convert.FromBase64String(salt); var bytes = passwordBytes.Concat(saltBytes).ToArray(); using (var sha256 = SHA256.Create()) { return Convert.ToBase64String(sha256.ComputeHash(bytes)); } } static string CreateSalt() { var saltBytes = new byte[32]; using (var provider = RandomNumberGenerator.Create()) { provider.GetNonZeroBytes(saltBytes); } var salt = Convert.ToBase64String(saltBytes); return salt; } } }
using System; using System.Collections.Generic; #if NETSTANDARD1_1 namespace yocto { internal class ThreadLocal<T> where T : class { private readonly System.Threading.ThreadLocal<T> _threadLocal; public ThreadLocal(Func<T> factory) { _threadLocal = new System.Threading.ThreadLocal<T>(factory, true); } public T Value => _threadLocal.Value; public IList<T> Values => _threadLocal.Values; } } #endif
using FourSeafile.Extensions; using System.Collections.Generic; using System.Linq; namespace FourSeafile.ViewModel { public partial class FileBrowserViewModel : ViewModelBase { public List<LibraryViewModel> Libraries { get { OnPropertyGet(); return _libs; } set { _libs = value; OnPropertyChanged(); } } private List<LibraryViewModel> _libs; public FileViewModelBase SelectedFolder { get { OnPropertyGet(); return _selectedFolder; } set { _selectedFolder = value; if (!History.Any() || History.Peek() != value) History.Push(value); OnPropertyChanged(); OnPropertyChanged(nameof(Address)); UpdateBackHandler(); } } private FileViewModelBase _selectedFolder; public string Address => SelectedFolder?.LibId != null && App.LibCache != null ? $"{App.LibCache[SelectedFolder.LibId].Name}{LocalAddress}" : string.Empty; private string LocalAddress { get { var folder = SelectedFolder as FileViewModel; return folder?.Path ?? string.Empty; } } private void UpdateBackHandler() { if (CanGoBack) App.CurrentPage.AttachBackHandler(GoBack); else App.CurrentPage.DetachBackHandler(); } } }
using System; using Microsoft.Win32.SafeHandles; using SDL2; namespace SharpDL.Graphics { internal class SafeFontHandle : SafeHandleZeroOrMinusOneIsInvalid { public SafeFontHandle(IntPtr handle) : base(true) { SetHandle(handle); } protected override bool ReleaseHandle() { SDL_ttf.TTF_CloseFont(handle); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using EWF.Util; using System.Data; using EWF.IServices; using System.IO; using Microsoft.AspNetCore.Hosting; using EWF.Application.Web.Controllers; using Microsoft.AspNetCore.Authorization; // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace EWF.Application.Web.Areas.RealData.Controllers { [Authorize] public class IceJamController : EWFBaseController { private IIcejamService service; private IStationService staService; private IHostingEnvironment hostingEnvironmen; public IceJamController(IIcejamService _service, IStationService _staService,IHostingEnvironment _hostingEnvironmen) { service = _service; staService = _staService; hostingEnvironmen = _hostingEnvironmen; } //public IActionResult RealData() //{ // return View(); //} #region 单站温度对比 public IActionResult SingleTempContra() { return View(); } public IActionResult GetSingleTempContraData(string stcds, string startDate, string endDate) { var lineDB = service.GetSingleTempData(stcds, startDate, endDate); var data = new { total = lineDB.Count(), rows = lineDB }; return Content(data.ToJson()); } #endregion #region 多站温度对比 public IActionResult MultiTempContra() { return View(); } public IActionResult GetMultiTempContraData(string stcds,string sqnm, string startDate, string endDate) { var result = service.GetTempDataByMultiStcds(stcds,sqnm, startDate, endDate); return Content(result); } #endregion public IActionResult GetQelByKeywords(string q) { var list = service.GetSearchKeywords(q); return Content(list.ToJson()); } #region 查询实时凌情信息 public IActionResult IceJamDate() { return View(); } /// <summary> /// 查询实时凌情信息 /// </summary> /// <param name="stcds"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> public IActionResult GetIceDate(string stcds, string startDate, string endDate) { string addvcd = HttpContext.User.Claims.First().Value.Split(',')[3]; string type = HttpContext.User.Claims.First().Value.Split(',')[2]; string result = service.GetIceDate(stcds, startDate, endDate, addvcd, type); return Content(result); } #endregion #region 凌情动态 public IActionResult IceJamDynamic() { //string dt = service.GetIceJamDynamic("2018-01-01 08:00", "2019-01-01 08:00"); return View(); } public IActionResult GetDynamicJson() { string str = ""; string contentRootPath = hostingEnvironmen.WebRootPath; using (StreamReader sr = new StreamReader(contentRootPath+ @"\MapDate\Dynamic.geojson")) { str=sr.ReadToEnd(); } return Content(str); } public IActionResult GetDynamicPoint(string state) { //state = "2019-06-01 08:00:00.000"; DataTable dt = service.GetIceJam_River(state); //DataTable dt = dts.Tables[0]; //DataTable dtResult = dts.Tables[1]; //var result = "{\"rows\":" + dt.ToJson()+ ",\"total\":" + dt.Rows.Count + ",\"Rvalue\":'"+dtResult.Rows[0]["CONTEXTSTR"].ToString()+"'}"; var result = "{\"rows\":" + dt.ToJson() + ",\"total\":" + dt.Rows.Count + "}"; return Content(result); } public string GetDynamicLQ(string state) { //state = "2016-11-24 08:00:00.000"; DataTable dts = service.GetIceJam_LQDT(state); string value = ""; //DataTable dtResult = dts.Tables[1]; //var result = "{\"Rvalue\":'" + dtResult.Rows[0]["CONTEXTSTR"].ToString() + "'}"; //var result = "{\"rows\":" + dt.ToJson() + ",\"total\":" + dt.Rows.Count + "}"; if(dts.Rows.Count>0) { value= dts.Rows[0]["CONTEXTSTR"].ToString(); } return value; } public IActionResult GetIceDynamice(string state) { //state = "2019-03-01 08:00"; DataTable dt = service.GetIceJamDynamic(state); var result = "{\"rows\":" + dt.ToJson() + ",\"total\":" + dt.Rows.Count + "}"; return Content(result); } #endregion } }
using ATSBackend.Service; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace ATSBackend { class Program { static void Main(string[] args) => CreateHostBuilder(args).Build().Run(); public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(c => c.UseStartup<Startup>()); } }
using MvvmCross.Platform.Plugins; namespace EsMo.Android.WeiBo.Bootstrap { public class ResourceLoaderPluginBootstrap : MvxPluginBootstrapAction<global::MvvmCross.Plugins.ResourceLoader.PluginLoader> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Common; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Routing; using Newtonsoft.Json.Linq; namespace Redux.Controllers { [Route("api")] public class RootController : Controller { // GET api/modules /// <summary> /// Возвращает доступные для отображения модули /// </summary> [HttpGet("modules")] public object GetModules() { Dictionary<string, Dictionary<string, string>> modules = new Dictionary<string, Dictionary<string, string>> { { "#messages", new Dictionary<string, string> { { "displayName", "Messages" }, { "script", "messages.js" }, { "template", "messages.tmp" } } }, { "#mathes", new Dictionary<string, string> { { "displayName", "Matches" }, { "script", "matches.js" }, { "template", "matches.tmp" } } }, { "#abilities", new Dictionary<string, string> { { "displayName", "Abilities" }, { "script", "abilities.js" }, { "template", "abilities.tmp" } } }, { "#heroes", new Dictionary<string, string> { { "displayName", "Heroes" }, { "script", "heroes.js" }, { "template", "heroes.tmp" } } } }; // Администратору видна страничка загрузки билдов if (User.IsInRole("Admin")) { /* modules.Add("#builds", new Dictionary<string, string> { {"displayName", "Builds"}, {"script", "builds.js"}, {"template", "builds.tmp"} } ); */ modules.Add("#players", new Dictionary<string, string> { {"displayName", "Players"}, {"script", "players.js"}, {"template", "players.tmp"} } ); } return modules; } // GET api/methods [HttpGet("methods")] public object GetMethods() { JObject apiList = new JObject(); Assembly assembly = Assembly.GetExecutingAssembly(); foreach (Type type in assembly.GetTypes().Where(t => t.Name.IsMatch("Controller"))) { JArray controllerMethods = new JArray(); RouteAttribute route = (RouteAttribute)type.GetCustomAttributes(typeof(RouteAttribute)).FirstOrDefault(); string controllerName = type.Name.Replace("Controller", string.Empty); string mainRoute = route.Template.Replace("[controller]", controllerName.ToLower()); foreach (MethodInfo method in type.GetMethods()) foreach (HttpMethodAttribute attr in method.GetCustomAttributes(typeof(HttpMethodAttribute))) { JObject apiMethod = new JObject { { "route", $"{string.Join(", ", attr.HttpMethods)} {string.Join("/", new string[] { mainRoute, attr.Template }.Where(s => !string.IsNullOrEmpty(s)))}" } }; AuthorizeAttribute authAttr = (AuthorizeAttribute)method.GetCustomAttributes(typeof(AuthorizeAttribute)).FirstOrDefault(); if (authAttr != null) apiMethod.Add("auth", new JObject{ { "roles", authAttr.Roles }, { "policy", authAttr.Policy } } ); ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length > 0) { JArray methodParams = new JArray(); foreach (ParameterInfo parameter in method.GetParameters()) methodParams.Add(new JObject { { "name", parameter.Name }, { "type", parameter.ParameterType.Name }, { "default", parameter.RawDefaultValue.ToString() } }); apiMethod.Add("params", methodParams); } controllerMethods.Add(apiMethod); } apiList.Add(controllerName, controllerMethods); } return apiList; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class bombaOffline : MonoBehaviour { public GameObject padre; public float poder; public GameObject explocion; // Use this for initialization void Start () { poder = padre.GetComponent<Poder>().poder; } // Update is called once per frame void Update () { } void OnCollisionEnter (Collision col) { if(col.gameObject.tag == "Piso") { Explo(); } } public void Explo() { var explo = (GameObject)Instantiate(explocion, transform.position, Quaternion.identity); explo.GetComponent<ExploOffline>().poder = poder; Destroy(gameObject); } }
using UnityEngine; using System.Collections; [RequireComponent(typeof(BoxCollider2D))] public class PointDrag : MonoBehaviour { private Vector3 screenPoint; private Vector3 offset; public Rigidbody2D rb; public BoxCollider2D bc; public BoxCollider2D bc2; public SpriteRenderer spriteRenderer; public bool listenToAi; public bool locked; public bool changed = false; public bool loaded = false; void start() { } void Update() { if (listenToAi && !loaded) { if (AiTracking.instance.disableRoute) { locked = true; } } loaded = true; if (locked) { spriteRenderer.color = new Color(255, 0, 0); } if(PlayerControl.instance.hacking == false) { if(!locked) { spriteRenderer.color = new Color(255, 255, 255); } bc.enabled = false; bc2.enabled = false; } else { if (!locked) { spriteRenderer.color = new Color(0, 255, 255); } bc2.enabled = true; } } void OnMouseDown() { if (PlayerControl.instance.hacking && !locked) { if (!changed) { AiTracking.instance.route++; AiTracking.instance.routeTotal++; changed = true; } bc.enabled = true; screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position); offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z)); } } void OnMouseDrag() { if (PlayerControl.instance.hacking && !locked) { Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z); Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset; /*transform.position = curPosition;*/ rb.MovePosition(curPosition); } } void OnMouseUp() { bc.enabled = false; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Rotate_Main_L1 : MonoBehaviour { public float speed = 10.0f; private void Update(){ OrbitAround(); } void OrbitAround(){ transform.Rotate(Vector3.forward * speed * Time.deltaTime); } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace BiPolarTowerDefence.Entities { public class BaseObject :GameComponent { protected readonly Game1 _game; public Vector3 position; public float width = 16; public float height = 16; public BaseObject(Game1 game, Vector3 position):base(game) { _game = game; this.position = position; } public Rectangle GetRect() { return new Rectangle((int)this.position.X, (int)this.position.Z, (int)this.width,(int)this.height); } public Vector2 GetPosition2() { return new Vector2(position.X,position.Z); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System; using System.ComponentModel.DataAnnotations; using DotNetNuke.Entities.Users; using DotNetNuke.Services.Localization; namespace Dnn.PersonaBar.Security.Attributes { [AttributeUsage(AttributeTargets.Property)] class UserEmailAsUsernameAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var propertyName = validationContext.DisplayName; bool userEmailAsUsername; if (!bool.TryParse(value.ToString(), out userEmailAsUsername)) { return new ValidationResult(string.Format(Localization.GetString(Components.Constants.NotValid, Components.Constants.LocalResourcesFile), propertyName, value.ToString())); } if (userEmailAsUsername && UserController.GetDuplicateEmailCount() > 0) { return new ValidationResult(Localization.GetString(Components.Constants.ContainsDuplicateAddresses, Components.Constants.LocalResourcesFile)); } return ValidationResult.Success; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameController : MonoBehaviour { public GameObject inventory; // Use this for initialization void Start() { } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.I)) { ToggleInventory(); } } void ToggleInventory() { inventory.SetActive(!inventory.activeInHierarchy); Cursor.visible = inventory.activeInHierarchy; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Paddle : MonoBehaviour { public float speed = 5f; private float input; // Use this for initialization void Start() { } // Update is called once per frame void Update() { input = Input.GetAxisRaw("Horizontal"); } void FixedUpdate() { GetComponent<Rigidbody2D>().velocity = Vector2.right * input * speed; } void OnCollisionEnter2D(Collision2D other) { if (FindObjectOfType<BrickManager>().playSoundOnDestroyBrick) { Camera.main.GetComponents<AudioSource>()[1].Play(); } } }
namespace ReadyGamerOne.Utility { public static class IntExtension { /// <summary> /// 获取Int数从右往左第Index位上的数字,只会返回 0 或 1 /// </summary> /// <param name="self"></param> /// <param name="index"></param> /// <returns></returns> public static int GetNumAtBinary(this int self, int index) { return (((self & (1 << index)) >> index) == 1) ? 1 : 0; } } }
namespace WcfServiceWeekDays.Library { using System; using System.ServiceModel; [ServiceContract] public interface IServiceWeekDays { [OperationContract] string GetDayOfWeekInBulgarian(DateTime dateTime); } }
using GalaSoft.MvvmLight.Command; using sample.wpf.library; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace sample.wpf { public class MainViewModel : GalaSoft.MvvmLight.ViewModelBase { private string _logThis; private ILogger _logger; public MainViewModel(ILogger logger) { _logger = logger; LogThisCommand = new RelayCommand(Log); } public string LogThis { set { _logThis = value; } } public ICommand LogThisCommand { get; } private void Log() { _logger.Log(_logThis); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class PlayerEntity : CharacterEntity { public int Experience; private Dungeon dungeonStatus; public GameObject basicAttack; private bool attacking = false; public CharacterEquipment equip; public PlayerSave.PlayerInfo current; public GameObject saveInfo; public CharacterInventory inv; public PlayerEntity () { } public void Awake() { //obj = GameObject.Find("PlayerParty/Player1/Attacks/Basic"); // equip = GameObject.Find("GUI/CharacterInventory/EquipmentPanel").GetComponent<CharacterEquipment>(); // inv = GameObject.Find("GUI/CharacterInventory/InventoryPanel").GetComponent<CharacterInventory>(); //current = GameObject.Find("SaveInfo").GetComponent<PlayerSave>().playerInfo; } public override void Start () { //current = GameObject.Find("SaveInfo").GetComponent<PlayerSave>().playerInfo; //current = PlayerSave; current = saveInfo.GetComponent<PlayerSave>().playerInfo; Debug.Log("start happened " + current.CurrentLife); this.Name = "Ogre"; this.Description = "Just a normal monster"; this.MaxLife = 100; this.CurrentLife = 100;; this.ExperienceGiven = 100; this.Level = 1; this.MoveSpeed = 10; this.Damage = 15; this.OptimalRange = 1; this.MaxRange = 5; this.AttackSpeed = 1.5f; /* this.Name = current.Name; this.Description = current.Description; this.MaxLife = current.MaxLife; this.CurrentLife = current.CurrentLife; this.MaxMana = current.MaxMana; this.CurrentMana = current.CurrentMana; this.ExperienceGiven = current.ExperienceGiven; this.Level = current.Level; this.Endurance = current.Endurance; this.Strength = current.Strength; this.Intellect = current.Intellect; this.MoveSpeed = current.MoveSpeed; this.Gold = current.Gold; this.Damage = current.Damage; this.OptimalRange = current.OptimalRange; this.MaxRange = current.MaxRange; this.AttackSpeed = current.AttackSpeed; */ CurrentState = States.IDLE; droppableLoot = new List<BaseItem>(); //CreateNewWeapon thing = new CreateNewWeapon(); //Loot.Add(thing.CreateWeapon()); //nav = GetComponent<NavMeshAgent>(); //nav.updateRotation = false; // Target = GameObject.FindGameObjectWithTag("Enemy").GetComponent<BaseEntity>(); particleTest = gameObject.GetComponent<ParticleSystem>(); } void UpdateStats() { //this.MaxLife = 200; //this.CurrentLife = 200; //this.Damage = 10; } void LevelUp() { MaxLife += 50; CurrentLife = MaxLife; } public void InitializeNavMeshAgent() { nav = GetComponent<NavMeshAgent>(); } public void GainExperience(int e) { Experience += e; if(Experience > (100 * Level)) { Level++; LevelUp(); Experience -= (100*Level); } } public override void Update () { //UpdateStats(); //playerLocation = playerObject.transform.position; //todo limit rate of move if(active) { /*if(Target == null) { Target = GameObject.FindGameObjectWithTag("Enemy").GetComponent<BaseEntity>(); } */ if(Target == null) { Target = ChooseBestTarget(); } else{ if (Time.time > nextActionTime ) { nextActionTime = Time.time + period; MoveToTargetAtOptimalRange(Target); transform.LookAt(Target.transform.position); if(!attacking) { if(Vector3.Distance(Target.transform.position, transform.position) < MaxRange) { StartCoroutine(AttackZ()); } } } } if (CurrentLife <= 0) { DestroyObject(this.gameObject); } } } IEnumerator AttackZ() { attacking = true; basicAttack.SetActive(true); yield return new WaitForSeconds(0.125f); basicAttack.SetActive(false); yield return new WaitForSeconds(AttackSpeed); attacking = false; } EnemyEntity ChooseBestTarget() { RoomTransition(); EnemyEntity min = null; float minDist = Mathf.Infinity; Vector3 currentPos = transform.position; foreach(Component c in dungeonStatus.enemies) { if(c != null) { Vector3 directionToTarget = c.transform.position - currentPos; float dist = directionToTarget.sqrMagnitude; if(dist < minDist) { min = (EnemyEntity)c; minDist = dist; } } } return min; } void RoomTransition() { dungeonStatus = GameObject.Find("DungeonStatus").GetComponent<Dungeon>(); } public void TakeDamage (int damage) { damage = 2; CurrentLife -= damage; if(CurrentLife < 0) { CurrentLife = 0; } } }
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 PetShopForms.Vistas.Menu { public partial class MenuEmpleado : Form { Inicio inicioForm; Inicio InicioForm { get { return this.inicioForm; } set { this.inicioForm = value; } } public MenuEmpleado(Inicio inicioForm) { InitializeComponent(); this.InicioForm = inicioForm; } private void btnClientes_Click(object sender, EventArgs e) { InicioForm.ChangeBody(new Clientes.Listado()); Inicio.PlaySound(Inicio.SwitchSoundPath); } private void btnVentas_Click(object sender, EventArgs e) { InicioForm.ChangeBody(new Ventas.Listado()); Inicio.PlaySound(Inicio.SwitchSoundPath); } } }
using System.Linq; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Threading; using CMkvPropEdit.Classes; using System.Data; using System.Windows.Forms; namespace CMkvPropEdit.Helper { static class ExecuteService { private static string PadNumber(int pad, int number) { int numberLength = number.ToString().Length; return new string('0', pad - numberLength) + number; } private static StringBuilder SetCmdLineGeneral(GeneralInfo info, string fileName, int index) { StringBuilder builder = new StringBuilder(); if (info.Tags.IsEnabled) { builder.Append(" --tags all:"); switch (info.Tags.Action) { case ModifyAction.ActionType.From: if (!string.IsNullOrWhiteSpace(info.Tags.FilePath)) { builder.Append($"\"{info.Tags.FilePath}\""); } break; case ModifyAction.ActionType.Match: string tmpTags = Path.GetFileNameWithoutExtension(fileName) + info.Tags.Match.Text + info.Tags.Match.Extension; builder.Append($"\"{tmpTags}\""); break; default: break; } } if (info.Chapters.IsEnabled) { builder.Append(" --chapters "); switch (info.Chapters.Action) { case ModifyAction.ActionType.Remove: builder.Append("''"); break; case ModifyAction.ActionType.From: if (string.IsNullOrWhiteSpace(info.Chapters.FilePath)) { builder.Append("''"); } else { builder.Append($"\"{info.Chapters.FilePath}\""); } break; case ModifyAction.ActionType.Match: string tmpChaps = Path.GetFileNameWithoutExtension(fileName) + info.Chapters.Match.Text + info.Chapters.Match.Extension; builder.Append($"\"{tmpChaps}\""); break; } } if (info.TrackNameAndNumber.TrackName.IsEnabled) { builder.Append(" --edit info"); string newTitle = info.TrackNameAndNumber.TrackName.Text; if (info.TrackNameAndNumber.Numbering.IsEnabled) { newTitle = newTitle.Replace("{num}", PadNumber(info.TrackNameAndNumber.Numbering.Padding, info.TrackNameAndNumber.Numbering.Start + index)); } newTitle = newTitle.Replace("{file_name}", Path.GetFileNameWithoutExtension(fileName)); builder.Append($" --set title=\"{newTitle}\""); } if (info.Parameters.IsEnabled && !string.IsNullOrWhiteSpace(info.Parameters.Text)) { builder.Append(" ").Append(info.Parameters.Text); } return builder; } private static StringBuilder GetTrackLine(TrackInfo[] infos, string fileName, int index) { StringBuilder fileCmd = new StringBuilder(); for (int j = 0; j < infos.Length; j++) { TrackInfo info = infos[j]; StringBuilder builder = new StringBuilder(); if (info.IsEnabled) { if (info.DefaultTrack.IsEnabled) { builder.Append(" --set flag-default=").Append(info.DefaultTrack.Value ? '1' : '0'); } if (info.ForcedTrack.IsEnabled) { builder.Append(" --set flag-forced=").Append(info.ForcedTrack.Value ? '1' : '0'); } if (info.TrackNameAndNumber.TrackName.IsEnabled) { string text = info.TrackNameAndNumber.TrackName.Text.Replace("{file_name}", Path.GetFileNameWithoutExtension(fileName)); if (info.TrackNameAndNumber.TrackName.IsEnabled && info.TrackNameAndNumber.Numbering.IsEnabled) { text = text.Replace("{num}", PadNumber(info.TrackNameAndNumber.Numbering.Padding, info.TrackNameAndNumber.Numbering.Start + index)); } builder.Append($" --set name=\"{text}\""); } if (info.Language.IsEnabled) { builder.Append($" --set language=\"{info.Language.Text}\""); } if (info.Parameters.IsEnabled && !string.IsNullOrWhiteSpace(info.Parameters.Text)) { builder.Append(" ").Append(info.Parameters.Text); } if (builder.Length != 0) { builder.Insert(0, $" --edit track:{info.Type}{j + 1}"); } } fileCmd.Append(builder); } return fileCmd; } private static string SetCmdLineAttachmentsAdd(DataTable table) { StringBuilder attachments = new StringBuilder(); foreach(DataRow row in table.AsEnumerable()) { string file = row[0].ToString(); string name = row[1].ToString(); string desc = row[2].ToString(); string mime = row[3].ToString(); SetAttachmentMeta(name, desc, mime, attachments); attachments.Append($" --add-attachment \"{file}\""); } return attachments.ToString(); } private static void SetAttachmentMeta(string name, string desc, string mime, StringBuilder builder) { if (!string.IsNullOrWhiteSpace(name)) { builder.Append($" --attachment-name \"{name}\""); } if (!string.IsNullOrWhiteSpace(mime)) { builder.Append($" --attachment-description \"{desc}\""); } if (!string.IsNullOrWhiteSpace(desc)) { builder.Append($" --attachment-mime-type \"{mime}\""); } } private static string SetCmdLineAttachmentsReplace(DataTable table) { StringBuilder attachmentsReplace = new StringBuilder(); foreach(DataRow row in table.AsEnumerable()) { AttachmentType type = (AttachmentType)row[0]; string orig = row[1].ToString(); string replace = row[2].ToString(); string name = row[3].ToString(); string desc = row[4].ToString(); string mime = row[5].ToString(); SetAttachmentMeta(name, desc, mime, attachmentsReplace); switch (type) { case AttachmentType.Name: attachmentsReplace.Append($" --replace-attachment \"name:{orig}:{replace}\""); break; case AttachmentType.Id: attachmentsReplace.Append($" --replace-attachment \"{orig}:{replace}\""); break; case AttachmentType.Type: attachmentsReplace.Append($" --replace-attachment \"mime-type:{orig}:{replace}\""); break; } } return attachmentsReplace.ToString(); } private static string SetCmdLineAttachmentsDelete(DataTable table) { StringBuilder attachmentDelete = new StringBuilder(); foreach(DataRow row in table.AsEnumerable()) { AttachmentType type = (AttachmentType)row[0]; string value = row[1].ToString(); switch (type) { case AttachmentType.Name: attachmentDelete.Append(" --delete-attachment \"name:{value}\""); break; case AttachmentType.Id: attachmentDelete.Append($" --delete-attachment \"{value}\""); break; case AttachmentType.Type: attachmentDelete.Append($" --delete-attachment \"mime-type:{value}\""); break; } } return attachmentDelete.ToString(); } internal static void SetCmdLine(GeneralInfo generalInfo, TrackInfo[] videoInfo, TrackInfo[] audioInfo, TrackInfo[] subtitleInfo, Attachments attachments, string[] fileNames, Action<string, string> update) { //string[] cmdLineGeneralOpt = SetCmdLineGeneral(generalInfo, fileNames); //string cmdLineAttachmentsAddOpt = SetCmdLineAttachmentsAdd(attachments.AddTable); //string cmdLineAttachmentsDeleteOpt = SetCmdLineAttachmentsReplace(attachments.ReplaceTable); //string cmdLineAttachmentsReplaceOpt = SetCmdLineAttachmentsDelete(attachments.DeleteTable); Thread thread = new Thread(() => { try { for (int i = 0; i < fileNames.Length; i++) { string fileName = fileNames[i]; //string cmdLineAllOpt = cmdLineGeneralOpt[i] + cmdLineAttachmentsDeleteOpt + cmdLineAttachmentsAddOpt // + cmdLineAttachmentsReplaceOpt + cmdLineVideoOpt[i] + cmdLineAudioOpt[i] + cmdLineSubtitleOpt[i]; string command = $"\"{fileName}\"" + GetTrackLine(videoInfo, fileName, i) + GetTrackLine(audioInfo, fileName, i) + GetTrackLine(subtitleInfo, fileName, i); System.Diagnostics.Process process = new System.Diagnostics.Process { StartInfo = new System.Diagnostics.ProcessStartInfo { WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, RedirectStandardOutput = true, UseShellExecute = false, FileName = Properties.Settings.Default.MKVPropeditPath, Arguments = command } }; process.Start(); string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); update(command, output); } } catch (Exception ex) { MessageService.ShowError(ex.Message); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); } } }
using bot_backEnd.DAL.Interfaces; using bot_backEnd.Data; using bot_backEnd.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace bot_backEnd.DAL { public class CityDAL : ICityDAL { private readonly AppDbContext _context; public CityDAL(AppDbContext context) { _context = context; } public async Task<ActionResult<List<City>>> GetAllCities() { return await _context.City.ToListAsync(); } } }
using System; using System.Collections.Generic; using System.Threading; namespace GomokuEngine { public static class EvaluationConstants { public const int max = 1000000; public const int min = -1000000; static public string Score2Text(int evaluation) { string s1; switch (evaluation) { case EvaluationConstants.max: s1 = "Black wins"; break; case EvaluationConstants.min: s1 = "White wins"; break; default: s1 = evaluation.ToString(); break; } return s1; } } public class Engine { public delegate void GenericEvent(); //public delegate void NewGameEvent(); public event GenericEvent BoardChanged; //public delegate void MovesChangedEvent(GameInformation gameInformation); //public event MovesChangedEvent MovesChangedE; public delegate void ThinkingFinishedEvent(SearchInformation info); public event ThinkingFinishedEvent ThinkingFinished; public delegate void ThinkingProgressEvent(SearchInformation info); public event ThinkingProgressEvent ThinkingProgress; GameBoard gameBoard; TranspositionTable transpositionTable; Search search; public GameInformation gameInformation; bool thinking; string _fileName; public event GenericEvent FileNameChanged; string _blackPlayerName; string _whitePlayerName; public event GenericEvent BlackPlayerNameChanged; public event GenericEvent WhitePlayerNameChanged; List<BoardSquare> gameMoveList; public Engine() { } /* public void NewGame(int boardSize) { //while (thinking) ; //initialize all transpositionTable = new TranspositionTable(boardSize); gameBoard = new GameBoard(boardSize,transpositionTable); search = new Search(gameBoard, transpositionTable); search.ThinkingFinished += new Search.ThinkingFinishedEvent(search_ThinkingFinished); search.ThinkingProgress += new Search.ThinkingProgressEvent(search_ThinkingProgress); //copy move list gameInformation = new GameInformation(); gameInformation.gameMoveList = new List<BoardSquare>(); //gameInformation.fileName = "New Game"; //gameInformation.blackPlayerName = "Black Player"; //gameInformation.whitePlayerName = "White Player"; NewGameE(); //MovesChanged(); }*/ public void NewGame(int boardSize, List<BoardSquare> moveList = null) { //while (thinking) ; //initialize all transpositionTable = new TranspositionTable(boardSize); gameBoard = new GameBoard(boardSize, transpositionTable); search = new Search(gameBoard, transpositionTable); search.ThinkingFinished += search_ThinkingFinished; search.ThinkingProgress += search_ThinkingProgress; //copy move list gameMoveList = (moveList == null) ? new List<BoardSquare>() : new List<BoardSquare>(moveList); //play all moves foreach (BoardSquare move in gameMoveList) { //BoardSquare move = gameInformation.gameMoveList[index]; //MakeMove(move); gameBoard.MakeMove(move.Index); } BlackPlayerName = "Black Player"; WhitePlayerName = "White Player"; FileName = "New Game"; BoardChanged(); //MovesChanged(); } public void MakeMove(BoardSquare move) { //while (thinking); //get square //int square = conversions.RowAndColumn2Index(row, column); //if square is occupied, exit if (gameBoard.GetSymbol(move.Index) != Player.None) return; gameBoard.MakeMove(move.Index); BoardChanged(); } // public void Redraw() // { // while (thinking) ; // // MovesChanged(); // } // public BoardSquare GetLastPlayedMove() // { // if (playedMoves.Count > 0) // return playedMoves[playedMoves.Count - 1]; // else // return null; // } public void Redo() { while (thinking) ; bool movesAreEqual = true; //check if moves are equal; for (int index = 0; index < gameBoard.playedSquares.Count && index < gameMoveList.Count; index++) { if (gameBoard.playedSquares[index] != gameMoveList[index].Index) { movesAreEqual = false; break; } } if (movesAreEqual && gameMoveList.Count > gameBoard.playedSquares.Count) { BoardSquare move = gameMoveList[gameBoard.playedSquares.Count]; //make move MakeMove(move); } //MovesChanged(); } public void RedoAll() { while (thinking) ; bool movesAreEqual = true; //check if moves are equal; for (int index = 0; index < gameBoard.playedSquares.Count && index < gameMoveList.Count; index++) { if (gameBoard.playedSquares[index] != gameMoveList[index].Index) { movesAreEqual = false; break; } } while (movesAreEqual && gameMoveList.Count > gameBoard.playedSquares.Count) { BoardSquare move = gameMoveList[gameBoard.playedSquares.Count]; //make move MakeMove(move); } //MovesChanged(); } public void Undo() { while (thinking) ; //undo one move if (gameBoard.playedSquares.Count > 0) { // ABMove move = gameBoard.GetPlayedMoves()[gameBoard.GetPlayedMoves().Count - 1]; gameBoard.UndoMove(); //MovesChanged(); } } public void UndoAll() { while (thinking) ; //undo all moves while (gameBoard.playedSquares.Count > 0) { //ABMove move = gameBoard.GetPlayedMoves()[gameBoard.GetPlayedMoves().Count - 1]; gameBoard.UndoMove(); } //MovesChanged(); } public int BoardSize { get { //exit if no game if (search == null) return 0; return gameBoard.BoardSize; } } public TimeSpan MaxThinkingTime { get { //exit if no game if (search == null) return new TimeSpan(0, 0, 0); return search.MaxThinkingTime; } set { //exit if no game if (search == null) return; search.MaxThinkingTime = value; } } public bool IterativeDeepening { get { //exit if no game if (search == null) return false; return search.IterativeDeepening; } set { //exit if no game if (search == null) return; search.IterativeDeepening = value; } } public int MaxSearchDepth { get { //exit if no game if (search == null) return 0; return search.MaxSearchDepth; } set { //exit if no game if (search == null) return; search.MaxSearchDepth = value; } } public int TranspositionTableSize { get { //exit if no game if (search == null) return 0; return transpositionTable.TableSize; } set { //exit if no game if (search == null) return; transpositionTable.TableSize = value; } } public void StartThinking() { while (thinking) ; //exit if no game if (search == null) throw new NotImplementedException("Engine not yet initialized!"); thinking = true; //create delegate ThreadStart delegate1 = new ThreadStart(search.RootSearch); //create thread Thread thread1 = new Thread(delegate1); thread1.Name = "Search Thread"; //start thread thread1.Start(); } // void MovesChanged() // { // gameInformation.playedMoves = gameBoard.GetPlayedMoves(); // // //determine next move // gameInformation.nextMove = null; // if (gameInformation.gameMoveList.Count > gameInformation.playedMoves.Count) // { // int index1; // for (index1 = 0; index1 < gameInformation.playedMoves.Count; index1++) // { // if (gameInformation.playedMoves[index1].square != gameInformation.gameMoveList[index1].square) break; // } // // if (index1 == gameInformation.playedMoves.Count) // { // gameInformation.nextMove = gameInformation.gameMoveList[index1]; // } // } // // gameInformation.possibleMoves = gameBoard.GeneratePossibleMoves(gameBoard.VctPlayer, gameBoard.VctDepth0); // // gameInformation.Evaluation = (gameBoard.PlayerOnMove == Player.BlackPlayer) ? gameBoard.GetEvaluation():-gameBoard.GetEvaluation(); // gameInformation.GainSquare = new ABMove(gameBoard.GainSquare,gameBoard.PlayerOnMove,gameBoard.BoardSize); // MovesChangedE(gameInformation); // } public void GetSquareInfo(string notification, out SquareInfo squareInfo) { var square = new BoardSquare(gameBoard.BoardSize, notification); gameBoard.GetSquareInfo(square.Index, out squareInfo); } //returns player who has few symbols public Player WhoIsOnMove { get { return gameBoard.PlayerOnMove; } } public string Version { get { string version = this.GetType().Assembly.GetName().Version.ToString(); return version; } } public void ResetTtTable(bool useDictionary) { while (thinking) ; if (search == null) return; transpositionTable.ResetTables(useDictionary); } public Player GetSymbol(int row, int column) { var square = new BoardSquare(gameBoard.BoardSize, row, column); return gameBoard.GetSymbol(square.Index); } public void StopThinking() { search.StopThinking(); } void search_ThinkingProgress(SearchInformation info) { ThinkingProgress(info); } void search_ThinkingFinished(SearchInformation info) { thinking = false; ThinkingFinished(info); } public TuningInfo GetTuningInfo() { return gameBoard.GetTuningInfo(); } public void SetTuningInfo(TuningInfo info) { // while (thinking) ; // // //store number of moves // var playedMoves = new List<int> (gameBoard.playedSquares); // // //undo all moves // for (int i = 0; i<playedMoves.Count; i++) // { // gameBoard.UndoMove(); // } // // // gameBoard.SetTuningInfo(info); // // //redo all moves // for (int i = 0; i < playedMoves.Count; i++) // { // gameBoard.MakeMove(playedMoves[i]); // } // // ResetTtTable(false); } public bool VctActive { set { gameBoard.VctActive = value; //MovesChanged(); } get { return gameBoard.VctActive; } } public bool Thinking { get { return thinking; } } public string FileName { get { return _fileName; } set { _fileName = value; FileNameChanged(); } } public string BlackPlayerName { get { return _blackPlayerName; } set { _blackPlayerName = value; BlackPlayerNameChanged(); } } public string WhitePlayerName { get { return _whitePlayerName; } set { _whitePlayerName = value; WhitePlayerNameChanged(); } } public List<BoardSquare> PlayedMoves { get { var list1 = new List<BoardSquare>(); foreach (int element in gameBoard.playedSquares) { var bs = new BoardSquare(gameBoard.BoardSize, element); list1.Add(bs); } return list1; } } } }
using Microsoft.Xna.Framework.Content.Pipeline; namespace MonoGame.Extended.Content.Pipeline { public class ContentLogger { public static ContentBuildLogger Logger { get; set; } public static void Log(string message) { Logger?.LogMessage(message); } } }
using BPiaoBao.SystemSetting.Domain.Models.Businessmen; using JoveZhao.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.SystemSetting.Domain.Services { public class StationBuyGroupDomainService : BaseDomainService { private const int _errorCode = 200002; private readonly IStationBuyGroupRepository _stationBuyGroupRepository; private readonly IBusinessmanRepository _businessmanRepository; #region ctor public StationBuyGroupDomainService(IStationBuyGroupRepository stationBuyGroupRepository, IBusinessmanRepository businessmanRepository) { _stationBuyGroupRepository = stationBuyGroupRepository; _businessmanRepository = businessmanRepository; } #endregion public IQueryable<StationBuyGroup> QueryStationBuyGroups() { return _stationBuyGroupRepository.FindAll().OrderBy(q => q.GroupName); } public void AddStationBuyGroup(StationBuyGroup group, string userName) { #region 数据验证 //组名不可为空 if (string.IsNullOrWhiteSpace(group.GroupName)) { throw new CustomException(_errorCode, "平台分销商组名不可为空。"); } //组名不可超过100字符 if (group.GroupName.Length > 100) { throw new CustomException(_errorCode, "平台分销商组名不能超过100字。"); } //组名是否已存在 if (_stationBuyGroupRepository.FindAll(q => q.GroupName == group.GroupName).Count() > 0) { throw new CustomException(_errorCode, "组名" + group.GroupName + "已存在。"); } //描述不可超过200字符 if (group.Description.Length > 200) { throw new CustomException(_errorCode, "描述不能超过100字。"); } //颜色不可为空 if (string.IsNullOrWhiteSpace(group.Color)) { throw new CustomException(_errorCode, "颜色不可为空。"); } //颜色不可超过100字符 if (group.Color.Length > 100) { throw new CustomException(_errorCode, "颜色不能超过100字"); } //必须存在操作员 if (string.IsNullOrWhiteSpace(userName)) { throw new CustomException(_errorCode, "操作用户不可为空。"); } #endregion //补充最后操作信息 group.LastOperatorUser = userName; group.LastOperatTime = DateTime.Now; _stationBuyGroupRepository.Create(group); _unitOfWork.Commit(); } public void UpdateStationBuyGroup(StationBuyGroup group, string userName) { #region 数据验证 if (string.IsNullOrWhiteSpace(group.ID)) { throw new CustomException(_errorCode, "分组ID不可为空。"); } //组名不可为空 if (string.IsNullOrWhiteSpace(group.GroupName)) { throw new CustomException(_errorCode, "平台分销商组名不可为空。"); } //组名不可超过100字符 if (group.GroupName.Length > 100) { throw new CustomException(_errorCode, "平台分销商组名不能超过100字。"); } //验证组名是否存在 if (_stationBuyGroupRepository.FindAll(q => q.GroupName == group.GroupName && q.ID != group.ID).Count() > 0) { throw new CustomException(_errorCode, "组名" + group.GroupName + "已存在。"); } //描述不可超过200字符 if (group.Description.Length > 200) { throw new CustomException(_errorCode, "描述不能超过100字。"); } //颜色不可为空 if (string.IsNullOrWhiteSpace(group.Color)) { throw new CustomException(_errorCode, "颜色不可为空。"); } //颜色不可超过100字符 if (group.Color.Length > 100) { throw new CustomException(_errorCode, "颜色不能超过100字"); } //必须存在操作员 if (string.IsNullOrWhiteSpace(userName)) { throw new CustomException(_errorCode, "操作用户不可为空。"); } #endregion var oldGroup = _stationBuyGroupRepository.FindAll(q => q.ID == group.ID).FirstOrDefault(); if (oldGroup == null) { throw new CustomException(_errorCode, "分组ID不存在。"); } oldGroup.GroupName = group.GroupName; oldGroup.Description = group.Description; oldGroup.Color = group.Color; oldGroup.LastOperatorUser = userName; oldGroup.LastOperatTime = DateTime.Now; _stationBuyGroupRepository.Update(oldGroup); _unitOfWork.Commit(); } public void DeleteStationBuyGroup(string groupID) { if (string.IsNullOrWhiteSpace(groupID)) { throw new CustomException(_errorCode, "分组ID不可为空。"); } var oldGroup = _stationBuyGroupRepository.FindAll(q => q.ID == groupID).FirstOrDefault(); if (oldGroup == null) { throw new CustomException(_errorCode, "分组ID不存在。"); } _stationBuyGroupRepository.Delete(oldGroup); _unitOfWork.Commit(); } public void SetBuyerToGroup(IList<string> buyerCodes, string groupID) { #region 数据验证 if (string.IsNullOrWhiteSpace(groupID)) { throw new CustomException(_errorCode, "分组ID不可为空。"); } if (_stationBuyGroupRepository.FindAll(q => q.ID == groupID).Count() == 0) { throw new CustomException(_errorCode, "分组ID不存在。"); } #endregion if (buyerCodes != null) { foreach (string code in buyerCodes) { var buyer=_businessmanRepository.FindAll().Cast<Buyer>().Where(q => q.Code == code).FirstOrDefault(); if (buyer == null) { throw new CustomException(_errorCode, "商户号" + code + "不存在。"); } buyer.StationBuyGroupID = groupID; _businessmanRepository.Update(buyer); } } _unitOfWork.Commit(); } } }
using UnityEngine; using System.Collections; public class CanvasScript : MonoBehaviour { bool m_bIsMoving = false; public RectTransform m_RootPos; public RectTransform m_RightPos; public RectTransform m_LeftPos; public RectTransform m_LeftFar; private float m_MoveDuration = 0.7f; RectTransform rt; float m_MoveTime; Vector3 startPos; Vector3 endPos; private bool m_IsActive = false; private int m_NextID; // Use this for initialization void Start () { rt = gameObject.GetComponent<RectTransform>(); m_RootPos = GameObject.Find("RootPos").GetComponent<RectTransform>(); m_RightPos = GameObject.Find("RightPos").GetComponent<RectTransform>(); m_LeftPos = GameObject.Find("LeftPos").GetComponent<RectTransform>(); m_LeftFar = GameObject.Find("LeftFar").GetComponent<RectTransform>(); } // Update is called once per frame void Update () { if (m_bIsMoving) { m_MoveTime += Time.deltaTime; if (m_MoveTime < m_MoveDuration) { float d = Mathf.SmoothStep(0, 1, m_MoveTime * (1 / m_MoveDuration)); rt.position = startPos + (endPos - startPos) * d; } else { m_bIsMoving = false; rt.position = endPos; if (endPos.Equals(m_LeftPos.position)) { ////Debug.Log("FAK"); rt.position = rt.position - new Vector3(1000, 0, 0); } if (endPos.Equals(m_RootPos.position)) { gameObject.SetActive(true); } else { gameObject.SetActive(false); if (m_NextID != -1) { SceneManager.Instance.GetCanvasByID((CanvasID)m_NextID).SetActive(true); } } //try //{ // SendMessage("OnShowUp"); //} //catch (System.Exception e) //{ // Debug.Log("Exception: " + e.Message); //} } } } public void MoveInFromRight() { gameObject.SetActive(true); SetActive(true); Move(m_RightPos.position, m_RootPos.position, m_MoveDuration); } public void MoveOutToRight(int cid = -1) { Move(m_RootPos.position, m_RightPos.position, m_MoveDuration); m_NextID = cid; } public void MoveInFromLeft() { SetActive(true); gameObject.SetActive(true); Move(m_LeftPos.position, m_RootPos.position, m_MoveDuration); } public void MoveInFromLeftFar() { SetActive(true); gameObject.SetActive(true); Move(m_LeftFar.position, m_RootPos.position, m_MoveDuration); } public void MoveOutToLeft(int cid = -1) { Move(m_RootPos.position, m_LeftPos.position, m_MoveDuration); m_NextID = cid; } public void MoveOutToLeftFar(int cid = -1) { Move(m_RootPos.position, m_LeftFar.position, m_MoveDuration); m_NextID = cid; } public void Move(Vector3 _startPos, Vector3 _endPos, float time) { m_bIsMoving = true; startPos = _startPos; endPos = _endPos; rt.position = startPos; m_MoveTime = 0; } public void Show(int cid = -1) { m_NextID = cid; rt.position = m_RootPos.position; gameObject.SetActive(true); gameObject.SetActive(true); } public void Hide() { Debug.Log("Hide: " + gameObject.name); //SetActive(false); rt.position = m_LeftFar.position; gameObject.SetActive(false); if (m_NextID != -1) { SceneManager.Instance.GetCanvasByID((CanvasID)m_NextID).SetActive(true); } } public void SetActive(bool active) { m_IsActive = active; if (active) { SceneManager.Instance.SetActiveScene(this); } } public bool IsActive() { return m_IsActive; } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyManager : MonoBehaviour { // Private Field [SerializeField] // Holds reference to game object that are considered enemies private List<GameObject> enemyList; // Public Field public event Action ListChangeEvent; public static EnemyManager instance; private void Awake() { // Singleton Pattern if (instance == null) { instance = this; } else { Destroy(gameObject); } enemyList = new List<GameObject>(); } // Adds enemy gameobjects to a list in the script for easy management public void Add(GameObject g) { enemyList.Add(g); if (ListChangeEvent != null) { ListChangeEvent(); } } // Removes enemy gameobjects from list public void Remove(GameObject g) { enemyList.Remove(g); if (ListChangeEvent != null) { ListChangeEvent(); } } // Make the collider passed in ignore collision to all enemies public void IgnoreCollision(Collider2D col) { for (int i = 0; i < enemyList.Count; i++) { Collider2D enemyCol = enemyList[i].GetComponent<EnemyMovement>().mainCollider; Physics2D.IgnoreCollision(col, enemyCol); } } // Remove null instances stored in the enemy list private void RemoveNull() { for (int i = 0; i < enemyList.Count; i++) { if (enemyList[i] == null) { enemyList.RemoveAt(i); } } } public bool IsEnemy(GameObject obj) { return obj.GetComponent<EnemyStatChange>() != null || enemyList.Contains(obj); } }
using System; using System.Runtime.Serialization; namespace PDTech.OA.Model { /// <summary> /// DUTY_RISK_INFO:实体类(属性说明自动提取数据库字段的描述信息) /// </summary> [Serializable] public partial class DUTY_RISK_INFO { public DUTY_RISK_INFO() { } #region Model private decimal _duty_risk_id; private string _duty_name; private string _risk_name; private string _risk_level; private string _avoid_metoh; private decimal _department_id; /// <summary> /// 岗位风险ID /// </summary> public decimal DUTY_RISK_ID { set { _duty_risk_id = value; } get { return _duty_risk_id; } } /// <summary> /// 岗位名称 /// </summary> public string DUTY_NAME { set { _duty_name = value; } get { return _duty_name; } } /// <summary> /// 风险名称 /// </summary> public string RISK_NAME { set { _risk_name = value; } get { return _risk_name; } } /// <summary> /// 风险等级1:一级、2:二级、3:三级 /// </summary> public string RISK_LEVEL { set { _risk_level = value; } get { return _risk_level; } } /// <summary> /// 防范措施 /// </summary> public string AVOID_METOH { set { _avoid_metoh = value; } get { return _avoid_metoh; } } /// <summary> /// 部门ID /// </summary> public decimal DEPARTMENT_ID { set { _department_id = value; } get { return _department_id; } } #endregion Model } /// <summary> /// 岗位风险(Json对象) /// </summary> [DataContract] public partial class DUTY_RISK { /***序号***/ [DataMember(Order = 0)] public string rowno { get; set; } /***风险ID***/ [DataMember(Order = 1)] public string duty_risk_id { get; set; } /***部门名称***/ [DataMember(Order = 2)] public string department_name { get; set; } /***岗位名称***/ [DataMember(Order = 3)] public string duty_name { get; set; } /***风险名称***/ [DataMember(Order = 4)] public string risk_name { get; set; } /***防范措施***/ [DataMember(Order = 5)] public string avoid_metoh { get; set; } /***风险等级(1:一级、2:二级、3:三级)***/ [DataMember(Order = 6)] public string risk_level { get; set; } } }
using Cadastro.API.Interface; using Cadastro.API.Model; using Microsoft.Extensions.Options; using MongoDB.Bson; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Cadastro.API.Data { public class ProdutoRepository : IProdutoRepository { private readonly ProdutoContext _context = null; public ProdutoRepository(IOptions<Settings> settings) { _context = new ProdutoContext(settings); } public async Task AddProduto(Produto produto) { try { await _context.Produtos.InsertOneAsync(produto); } catch (Exception ex) { throw ex; } } public async Task<IEnumerable<Produto>> GetAllProdutos() { try { return await _context.Produtos.Find(_ => true).ToListAsync(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Message); throw ex; } } public async Task<IEnumerable<Produto>> Pagination(int top, int skip, bool ascending) { var query = _context.Produtos.Find(e => true).Skip(skip).Limit(top); if (ascending) return await query.SortBy(p => p.Codigo).ToListAsync(); else return await query.SortByDescending(p => p.Codigo).ToListAsync(); } public async Task<Produto> GetProduto(string codigo) { try { ObjectId internalId = GetInternalId(codigo); return await _context.Produtos .Find(produto => produto.Codigo == codigo || produto.InternalId == internalId) .FirstOrDefaultAsync(); } catch (Exception ex) { throw ex; } } public async Task<bool> RemoveAllProdutos() { try { DeleteResult actionResult = await _context.Produtos.DeleteManyAsync(new BsonDocument()); return actionResult.IsAcknowledged && actionResult.DeletedCount > 0; } catch (Exception ex) { throw ex; } } public async Task<bool> RemoveProduto(string codigo) { try { DeleteResult actionResult = await _context.Produtos.DeleteOneAsync( Builders<Produto>.Filter.Eq("Codigo", codigo)); return actionResult.IsAcknowledged && actionResult.DeletedCount > 0; } catch (Exception ex) { throw ex; } } public async Task<bool> UpdateProduto(string codigo, Produto produto) { var filter = Builders<Produto>.Filter.Eq(s => s.Codigo, codigo); var update = Builders<Produto>.Update .Set(s => s.Nome, produto.Nome) .Set(s => s.Descricao, produto.Descricao) .Set(s => s.URL_Imagem, produto.URL_Imagem) .Set(s => s.Preco, produto.Preco) .Set(s => s.Marca, produto.Marca) .Set(s => s.Categoria, produto.Categoria); try { UpdateResult actionResult = await _context.Produtos.UpdateOneAsync(filter, update); return actionResult.IsAcknowledged && actionResult.ModifiedCount > 0; } catch (Exception ex) { throw ex; } } public async Task<bool> UpdateProdutoObj(string codigo, Produto produto) { var item = await GetProduto(codigo) ?? new Produto(); item.Nome = produto.Nome; item.Descricao = produto.Descricao; item.URL_Imagem = produto.URL_Imagem; item.Preco = produto.Preco; item.Marca = produto.Marca; item.Categoria = produto.Categoria; return await UpdateProduto(codigo, item); } public async Task<string> CreateIndex() { try { return await _context.Produtos.Indexes .CreateOneAsync(Builders<Produto> .IndexKeys .Ascending(produto => produto.Nome) .Ascending(produto => produto.Descricao) .Ascending(produto => produto.URL_Imagem) .Ascending(produto => produto.Preco) .Ascending(produto => produto.Marca) .Ascending(produto => produto.Categoria)); } catch (Exception ex) { throw ex; } } private ObjectId GetInternalId(string id) { ObjectId internalId; if (!ObjectId.TryParse(id, out internalId)) internalId = ObjectId.Empty; return internalId; } } }
using console; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace ConsoleTestProj { /// <summary> ///This is a test class for _019_BuySellStocksTest and is intended ///to contain all _019_BuySellStocksTest Unit Tests ///</summary> [TestClass()] public class _019_BuySellStocksTest { private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //public static void MyClassInitialize(TestContext testContext) //{ //} // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //public static void MyClassCleanup() //{ //} // //Use TestInitialize to run code before running each test //[TestInitialize()] //public void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run //[TestCleanup()] //public void MyTestCleanup() //{ //} // #endregion /// <summary> ///A test for MaxProfileOneTransaction ///</summary> [TestMethod()] public void MaxProfileOneTransactionTest() { _019_BuySellStocks target = new _019_BuySellStocks(); int[] prices =new int[] {1,2,4,2,5,7,2,4,9,0,9}; int expected = 9; int actual; actual = target.MaxProfileOneTransaction(prices); Assert.AreEqual(expected, actual); prices =new int[]{1,2,4,2,5,7,2,4,9,0}; expected = 8; actual = target.MaxProfileOneTransaction(prices); Assert.AreEqual(expected, actual); prices = new int[] { }; expected = 0; actual = target.MaxProfileOneTransaction(prices); Assert.AreEqual(expected, actual); prices = new int[] {1}; expected = 0; actual = target.MaxProfileOneTransaction(prices); Assert.AreEqual(expected, actual); prices = new int[] { 3,3 }; expected = 0; actual = target.MaxProfileOneTransaction(prices); Assert.AreEqual(expected, actual); prices = new int[] { 3, 3,3,3,3,3,3 }; expected = 0; actual = target.MaxProfileOneTransaction(prices); Assert.AreEqual(expected, actual); } /// <summary> ///A test for MaxProfitOneTransactionN2 ///</summary> [TestMethod()] public void MaxProfitOneTransactionN2Test() { _019_BuySellStocks target = new _019_BuySellStocks(); int[] prices = new int[] { 1, 2, 4, 2, 5, 7, 2, 4, 9, 0, 9 }; // TODO: Initialize to an appropriate value int expected = 9; // TODO: Initialize to an appropriate value int actual; actual = target.MaxProfitOneTransactionN2(prices); Assert.AreEqual(expected, actual); prices = new int[] { 1, 2, 4, 2, 5, 7, 2, 4, 9, 0 }; expected = 8; actual = target.MaxProfitOneTransactionN2(prices); Assert.AreEqual(expected, actual); prices = new int[] { }; expected = 0; actual = target.MaxProfitOneTransactionN2(prices); Assert.AreEqual(expected, actual); prices = new int[] { 1 }; expected = 0; actual = target.MaxProfitOneTransactionN2(prices); Assert.AreEqual(expected, actual); prices = new int[] { 3, 3 }; expected = 0; actual = target.MaxProfitOneTransactionN2(prices); Assert.AreEqual(expected, actual); prices = new int[] { 3, 3, 3, 3, 3, 3, 3 }; expected = 0; actual = target.MaxProfitOneTransactionN2(prices); Assert.AreEqual(expected, actual); } /// <summary> ///A test for MaxProfitUnlimitedTransaction ///</summary> [TestMethod()] public void MaxProfitUnlimitedTransactionTest() { _019_BuySellStocks target = new _019_BuySellStocks(); // TODO: Initialize to an appropriate value int[] prices = new int[] { 1, 2, 4, 2, 5, 7, 2, 4, 9, 0, 9 }; int expected = 24; int actual; actual = target.MaxProfitUnlimitedTransaction(prices); Assert.AreEqual(expected, actual); prices = new int[] { 1, 2, 4, 2, 5, 7, 2, 4, 9, 0 }; expected = 15; actual = target.MaxProfitUnlimitedTransaction(prices); Assert.AreEqual(expected, actual); prices = new int[] {}; expected = 0; actual = target.MaxProfitUnlimitedTransaction(prices); Assert.AreEqual(expected, actual); prices = new int[] { 1 }; expected = 0; actual = target.MaxProfitUnlimitedTransaction(prices); Assert.AreEqual(expected, actual); prices = new int[] { 3, 3 }; expected = 0; actual = target.MaxProfitUnlimitedTransaction(prices); Assert.AreEqual(expected, actual); prices = new int[] { 3, 3, 3, 3, 3, 3, 3 }; expected = 0; actual = target.MaxProfitUnlimitedTransaction(prices); Assert.AreEqual(expected, actual); } } }