text
stringlengths
13
6.01M
using UnityEngine; using System.Collections; public class arrowKeys : MonoBehaviour { public GameObject upTrigger; public GameObject downTrigger; public GameObject leftTrigger; public GameObject rightTrigger; public bool isPress = false; public int Timer = 0; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (isPress == true){ Timer ++; if (Timer >= 10){ upTrigger.SetActive(false); downTrigger.SetActive(false); leftTrigger.SetActive(false); rightTrigger.SetActive(false); isPress = false; Timer = 0; } } if (Input.GetKeyDown(KeyCode.UpArrow)){ upTrigger.SetActive(true); isPress = true; } else if (Input.GetKeyDown(KeyCode.DownArrow)){ downTrigger.SetActive(true); isPress = true; } else if (Input.GetKeyDown(KeyCode.LeftArrow)){ leftTrigger.SetActive(true); isPress = true; } else if (Input.GetKeyDown(KeyCode.RightArrow)){ rightTrigger.SetActive(true); isPress = true; } } }
using CRMSecurityProvider.Sources.Attribute; namespace AlphaSolutions.SitecoreCms.ExtendedCRMProvider.Sources.Attribute { internal abstract class CrmAttributeAdapterBase<T> : AdapterBase<T>, ICrmAttribute { protected CrmAttributeAdapterBase(T internalAttribute) : base(internalAttribute) { } public abstract string GetStringifiedValue(); public abstract void SetValue(string value, params string[] data); public override string ToString() { return this.GetStringifiedValue(); } public abstract string Name { get; set; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using PredictiveTextEngine; namespace PredictiveTextEngine.Tests { [TestClass] public class SentenceObjectTests { [TestMethod] public void TestMinimumLength() { // Arrange SentenceObject sentence = new SentenceObject(); sentence.AddWord(new WordObject("HelloMyNameIs")); sentence.AddWord(new WordObject("Slim")); sentence.AddWord(new WordObject("Shady")); // Act string complete = sentence.ReturnSentence(); // Assert Assert.AreEqual("HelloMyNameIs Slim Shady.", complete); // Cleanup } [TestMethod] public void TestInterrogative() { // Arrange SentenceObject sentence = new SentenceObject(); sentence.AddWord(new WordObject("What")); sentence.AddWord(new WordObject("is")); sentence.AddWord(new WordObject("this")); // Act string complete = sentence.ReturnSentence(); // Assert Assert.AreEqual("What is this?", complete); // Cleanup } } }
using UnityEngine; using UnityEngine.AI; [RequireComponent(typeof(Rigidbody))] public class Enemy : MonoBehaviour { // NavMeshAgent agent; GameObject player; new Rigidbody rigidbody; [SerializeField] float speed = 100; void Awake() { // agent = GetComponent<NavMeshAgent>(); rigidbody = GetComponent<Rigidbody>(); } void Start() { player = GameObject.FindGameObjectWithTag("Player"); } void Update() { FollowPlayer(); } void FollowPlayer() { if (player && Vector3.Distance(transform.position, player.transform.position) < 10) { // agent.SetDestination(player.transform.position); var direction = player.transform.position - transform.position; rigidbody.AddForce(direction.normalized * speed * Time.smoothDeltaTime); } } }
using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(CiTest.Web.Startup))] namespace CiTest.Web { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } }
using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Routing; using Moq; using NUnit.Framework; using SFA.DAS.CommitmentsV2.Api.Types.Validation; using SFA.DAS.CommitmentsV2.Shared.Filters; using SFA.DAS.ProviderCommitments.Interfaces; using SFA.DAS.ProviderCommitments.Web.Filters; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Filters { [TestFixture] public class WhenHandlingExceptionsForModelStateValidationUsingTempData { private CacheFriendlyCommitmentsValidationFilter _cacheFriendlyCommitmentsValidationFilter; private Mock<ICacheStorageService> _cacheStorageServiceMock; private Mock<DomainExceptionRedirectGetFilterAttribute> _domainExceptionRedirectGetFilterAttributeMock; private List<IFilterMetadata> _filters; [SetUp] public void SetUp() { _cacheStorageServiceMock = new Mock<ICacheStorageService>(); _domainExceptionRedirectGetFilterAttributeMock = new Mock<DomainExceptionRedirectGetFilterAttribute>(); _cacheFriendlyCommitmentsValidationFilter = new CacheFriendlyCommitmentsValidationFilter(_cacheStorageServiceMock.Object, _domainExceptionRedirectGetFilterAttributeMock.Object); _filters = new List<IFilterMetadata>(); } [Test] public void ThenDomainExceptionFilterAttributeDoesNotRunOnException() { //Arrange var exceptionContext = new ExceptionContext(new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()), _filters); var errors = new List<ErrorDetail> { new ErrorDetail("uln", "bogus") }; exceptionContext.Exception = new CommitmentsApiModelException(errors); //Act _cacheFriendlyCommitmentsValidationFilter.OnException(exceptionContext); //Assert _domainExceptionRedirectGetFilterAttributeMock.Verify(x => x.OnException(exceptionContext), Times.Once); } } }
using System; using System.Collections.Generic; using System.Text; using UnityEngine; class SelfCheckingModalProcessCommon : UniProcessModalEvent { public override ModalProcessType processType { get { return ModalProcessType.Process_SelfChecking; } } public SelfCheckingModalProcessCommon() : base() { } //初始化函数 public override void Initialization() { //首先在启动过程中先查看是否出现了错误,如果出现了错误需要显示错误信息 //然后就不进行下面的过程了 if (ErrMessageBox.IsShowErrMessageBox) { ErrMessageBox.ShowErrMessage("游戏启动发生错误,无法进入游戏!"); return; } //进入游戏待机画面 base.Initialization(); checkedEvent = CheckedEvent.Eve_Start; SelfCheckingProcess(null); } enum CheckedEvent { Eve_Noting, //没有开始 Eve_Start, //开始自检 Eve_ProduceActivateInfo, //汇报产品激活情况 Eve_ProduceVersion, //汇报产品版本情况 Eve_InputDeviceResponse, //输入设备响应 Eve_InputDeviceResponseOver,//输入设备响应完成 Eve_InputDeviceOut, //输入设备输出 Eve_InputDeviceOutOver, //完成 Eve_GameResolution, //调整游戏分辨率 Eve_GameResolution1, //调整游戏分辨率 Eve_IntoControlPanel, //控制界面 Eve_IntoGame, //进入游戏 Eve_IntoGameOk } private CheckedEvent checkedEvent = CheckedEvent.Eve_Noting; private void SelfCheckingProcess(object[] parameters) { switch (checkedEvent) { case CheckedEvent.Eve_Start: { checkedEvent = CheckedEvent.Eve_GameResolution; TimerCall(SelfCheckingProcess, 1, false); } break; case CheckedEvent.Eve_GameResolution: { if (UniGameOptionsDefine.gameResolution != UniGameOptionsFile.GameResolution.Resolution_Default) { UnityEngine.Resolution resolution = UniGameOptionsDefine.gameResolutionUnity; Screen.SetResolution(resolution.width, resolution.height, true); } checkedEvent = CheckedEvent.Eve_IntoGameOk; TimerCall(SelfCheckingProcess, 1, false); } break; case CheckedEvent.Eve_IntoGameOk: { //在这里预载入声音资源 MusicPlayer.LoadAllUnloadAudioClip(); //进入公司LOGO过程 ConsoleCenter.CurrentSceneWorkMode = SceneWorkMode.SCENEWORKMODE_Release; processControl.ActivateProcess(typeof(StandbyProcess)); } break; } } }
using System.Xml.Linq; namespace EngageNet.Data { public class Name : ElementBase { public string Formatted { get { return GetPropertyValue("formatted"); } } public string FamilyName { get { return GetPropertyValue("familyName"); } } public string GivenName { get { return GetPropertyValue("givenName"); } } public string MiddleName { get { return GetPropertyValue("middleName"); } } public string HonorificPrefix { get { return GetPropertyValue("honorificPrefix"); } } public string HonorificSuffix { get { return GetPropertyValue("honorificSuffix"); } } public static Name FromXElement(XElement xElement) { var name = new Name(); foreach (var element in xElement.Elements()) { var elementLocalName = element.Name.LocalName; name.AddProperty(elementLocalName, element.Value); } return name; } } }
using Alabo.App.Share.HuDong.Domain.Entities; using Alabo.App.Share.HuDong.Domain.Services; using Alabo.Domains.Entities; using Alabo.Domains.Query; using Alabo.Extensions; using Alabo.Framework.Core.WebApis.Service; using Alabo.UI; using Alabo.UI.Design.AutoLists; using Alabo.Web.Mvc.Attributes; using System; using System.Collections.Generic; using System.Linq; namespace Alabo.App.Share.HuDong.UI { /// <summary> /// 用户中奖记录 /// </summary> [ClassProperty(Name = "互动中奖记录")] public class UserAwardAutoList : UIBase, IAutoList { public PageResult<AutoListItem> PageList(object query, AutoBaseModel autoModel) { var dic = query.ToObject<Dictionary<string, string>>(); dic.TryGetValue("loginUserId", out var userId); dic.TryGetValue("pageIndex", out var pageIndexStr); var pageIndex = pageIndexStr.ToInt64(); if (pageIndex <= 0) { pageIndex = 1; } var orderQuery = new ExpressionQuery<HudongRecord> { EnablePaging = true, PageIndex = (int)pageIndex, PageSize = 15 }; orderQuery.And(e => e.UserId == userId.ToInt64()); var model = Resolve<IHudongRecordService>().GetPagedList(orderQuery); var list = new List<AutoListItem>(); foreach (var item in model.ToList()) { var apiData = new AutoListItem { Id = item.Id, Image = GetAvator(item.UserId), Title = item.Grade, Intro = "中奖时间:" + item.CreateTime, Value = item.HuDongStatus.Value() == 1 ? "已兑奖" : "未兑奖" //item.CreateTime.ToUniversalTime() }; list.Add(apiData); } return ToPageList(list, model); } public Type SearchType() { throw new NotImplementedException(); } /// <summary> /// </summary> /// <param name="userId"></param> /// <returns></returns> public string GetAvator(long userId) { var avator = Resolve<IApiService>().ApiImageUrl(Resolve<IApiService>().ApiUserAvator(userId)); return avator; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MomTrigger : MonoBehaviour { public GameObject MomStats; public GameObject HospitalScreen; public Button backButton; public bool backBool; public bool canvasBool = false; void OnTriggerEnter(Collider other) { MomStats.gameObject.SetActive(true); Debug.Log ("object enter"); } void OnTriggerStay(Collider other) { //if (!canvasBool) //MomStats.gameObject.SetActive (true); if (Input.GetKeyUp (KeyCode.I)) { MomStats.gameObject.SetActive (false); canvasBool = true; HospitalScreen.SetActive (true); Button btn = backButton.GetComponent<Button> (); btn.onClick.AddListener (TaskOnClick); } else if (!canvasBool) { MomStats.gameObject.SetActive (true); } //MomStats.gameObject.SetActive (true); //Time.timeScale = 1; //canvasBool = false; //backBool = false; Debug.Log ("object stay"); } void TaskOnClick() { MomStats.gameObject.SetActive (true); HospitalScreen.SetActive(false); backBool = true; canvasBool = false; } void OnTriggerExit(Collider other) { MomStats.SetActive(false); Debug.Log ("object exit"); } /*void testing(Collider other) { while(true) { OnTriggerEnter(other); OnTriggerStay(other); OnTriggerExit(other); } }*/ }
using System; using ReactMusicStore.Core.Domain.Interfaces.Specification; namespace ReactMusicStore.Core.Domain.Entities.Specifications.OrderSpecs { public class OrderDateShouldBeLowerThanTodaySpec : ISpecification<Order> { public bool IsSatisfiedBy(Order order) { return order.OrderDate.Date <= DateTime.Today; } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Windows; using System.Windows.Input; using System.Windows.Media; using GymWorkout.Data; using GymWorkout.Entity.General; using WPFCustomMessageBox; namespace GymWorkout.Views { /// <summary> /// Interaction logic for vwStudents.xaml /// </summary> public partial class vwStudents : Window { private readonly GymContext _context = new GymContext(); private Student _student = new Student(); public vwStudents() { var splashScreen = new SplashScreenWindow(); splashScreen.Show(); InitializeComponent(); BindGrid(); CboGender.ItemsSource = _context.Genders.ToList(); GbAddEdit.DataContext = _student; splashScreen.Close(); } #region Commands private void DeleteCommandBinding_OnCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = GrdList.SelectedItem is Student student; } private void DeleteCommandBinding_OnExecuted(object sender, ExecutedRoutedEventArgs e) { if (GrdList.SelectedItem is Student student && CustomMessageBox.ShowYesNo($"جهت حذف رکورد '{student.FullName}' اطمینان دارید ؟", "حذف رکورد", "بله", "خیر", MessageBoxImage.Warning) == MessageBoxResult.Yes) { _context.Students.Attach(student); _context.Entry(student).State = EntityState.Deleted; _context.SaveChanges(); Reset(); CustomMessageBox.ShowOK("اطلاعات شما با موفقیت حذف گردید.", "حذف", "بسیار خوب"); } } private void WorkoutCommandBinding_OnCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = (GrdList.SelectedItem is Student); } private void WorkoutCommandBinding_OnExecuted(object sender, ExecutedRoutedEventArgs e) { if (GrdList.SelectedItem is Student student) { new vwWorkouts(student.Id) { Owner = this, WindowStartupLocation = WindowStartupLocation.CenterOwner }.ShowDialog(); } } #endregion #region Events Methods private void VwStudents_OnLoaded(object sender, RoutedEventArgs e) { CboGender.SelectedIndex = 1; } private void GrdList_OnMouseDoubleClick(object sender, MouseButtonEventArgs e) { if (GrdList.Items.Count > 0) { _student = (Student)GrdList.SelectedItem; GbAddEdit.DataContext = _student; GbAddEdit.Header = $"ویرایش '{_student.FullName}'"; BtnSave.Content = "ویرایش"; BtnSave.Background = new SolidColorBrush(Color.FromRgb(247, 194, 44)); } } private void BtnSearch_OnClick(object sender, RoutedEventArgs e) { BindGrid(TxtSearchFullName.Text, TxtSearchMobile.Text); } private void BtnSave_OnClick(object sender, RoutedEventArgs e) { if (CustomMessageBox.ShowYesNo("جهت ثبت اطلاعات اطمینان دارید ؟", "ثبت اطلاعات", "بله", "خیر", MessageBoxImage.Information) == MessageBoxResult.Yes) { if (_student.Id == 0) { _student.CreateDate = DateTime.Now; _context.Students.Add(_student); } else { _context.Students.Attach(_student); _context.Entry(_student).State = EntityState.Modified; } _context.SaveChanges(); Reset(); CustomMessageBox.ShowOK("اطلاعات شما با موفقیت ثبت گردید.", "موفقیت آمیز", "بسیار خوب"); } } private void BtnCancel_OnClick(object sender, RoutedEventArgs e) { Reset(); } private void BtnClose_OnClick(object sender, RoutedEventArgs e) { this.Close(); } private void BtnSearchCancel_OnClick(object sender, RoutedEventArgs e) { TxtSearchFullName.Text = TxtSearchMobile.Text = ""; BindGrid(); } #endregion #region Methods private void Reset() { _student = new Student(); GbAddEdit.DataContext = _student; BtnSave.Content = GbAddEdit.Header = "افزودن"; BtnSave.Background = new SolidColorBrush(Color.FromRgb(92, 184, 92)); BindGrid(TxtSearchFullName.Text, TxtSearchMobile.Text); } private void BindGrid(string fullname = "", string mobile = "") { IEnumerable<Student> result = _context.Students; if (!string.IsNullOrWhiteSpace(fullname)) result = result.Where(c => c.FullName.Contains(fullname)); if (!string.IsNullOrWhiteSpace(mobile)) result = result.Where(c => c.Mobile.Contains(mobile)); GrdList.ItemsSource = result.ToList(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; namespace PROG1_PROYECTO_FINAL { abstract class Productos { public virtual DataTable Mostrar(DataTable table) { return table; } public virtual void Insertar(string nombre, string marca, double precio, int tipo) { } public virtual void Editar(int id, string nombre, string marca, double precio) { } public virtual void Eliminar(int id) { } } }
using Backend.Model.Manager; namespace GraphicalEditorServerTests.DataFactory { public class CreateEquipmentType { public EquipmentType CreateValidTestObject() { return new EquipmentType("table", true); } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class MenuSlide : MonoBehaviour { private GameObject OpImage; private GameObject ClImage; private Animator MenuSlideState; public static bool Opened; private GameObject NSTR; private GameObject STR; public static bool IsStarted; private GameObject[] search; public static GameObject[] spawed_objects; // Use this for initialization void Start () { MenuSlideState = GameObject.Find ("SelectDevice").GetComponent<Animator> (); Opened = false; MenuSlideState.SetBool ("MenuOpened", false); OpImage = GameObject.Find ("Open"); ClImage = GameObject.Find ("Close"); ClImage.gameObject.SetActive(false); NSTR = GameObject.Find ("NotStarted"); STR = GameObject.Find ("Started"); STR.gameObject.SetActive(false); IsStarted = false; search = new GameObject[BONUS.AllStars]; for (int i = 0; i < BONUS.AllStars; i++) { if (i == 0) { search[i] = GameObject.Find("Star"); search[i].SetActive(true); }else{ search[i] = GameObject.Find("Star " + i); search[i].gameObject.SetActive(true); } } //PlayerAttrib.playerBall = GameObject.Find ("Ball").GetComponent<Rigidbody> (); } // Update is called once per frame void Update () { } public void ClMenu() { MenuSlideState.SetBool ("MenuOpened", false); Opened = false; OpImage.gameObject.SetActive(true); ClImage.gameObject.SetActive(false); } public void OnMenuSlideClick() { if (!Opened) { MenuSlideState.SetBool ("MenuOpened", true); Opened = true; OpImage.gameObject.SetActive(false); ClImage.gameObject.SetActive(true); }else{ MenuSlideState.SetBool ("MenuOpened", false); Opened = false; OpImage.gameObject.SetActive(true); ClImage.gameObject.SetActive(false); } } public void OnStartClick() { if (!IsStarted) { NSTR.gameObject.SetActive(false); STR.gameObject.SetActive(true); IsStarted = true; PlayerAttrib.playerBall.WakeUp (); PlayerAttrib.CollectedStars = 0; }else{ NSTR.gameObject.SetActive(true); STR.gameObject.SetActive(false); IsStarted = false; foreach (GameObject searched in search) { searched.gameObject.SetActive(true); } PlayerAttrib.Player.transform.position = new Vector3 (-1.672f, 4.654f, -8.67f); PlayerAttrib.playerBall.Sleep (); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Escudo_luz_script : MonoBehaviour { // Use this for initialization void Start() { this.gameObject.GetComponent<Light>().color = this.transform.parent.GetComponent<escudo_controller>().colorGeneral; } // Update is called once per frame void Update() { this.transform.position = new Vector3(this.transform.parent.position.x, this.transform.parent.position.y, 40); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using EshopApi.Contracts; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.SqlServer; using EshopApi.Models; using EshopApi.Repositories; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; namespace EshopApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(swagger => { swagger.SwaggerDoc("V1", new OpenApiInfo{Title = "EShopApi"}); swagger.IncludeXmlComments(Path.Combine(Directory.GetCurrentDirectory(), @"bin\Debug\netcoreapp3.1", "EshopApi.xml")); }); services.AddControllers(); services.AddDbContext<EshopApi_DBContext>(options => { options.UseSqlServer(@"Data Source=DESKTOP-MP4JNUP\KAMRAN;Initial Catalog=EshopApi_DB;Integrated Security=True;"); }); services.AddTransient<ICustomerRepository, CustomerRepository>(); services.AddTransient<IProductRepository, ProductRepository>(); services.AddTransient<ISalesPersonRepository, SalesPersonRepository>(); //JWT services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(option => { option.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = false, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "http://localhost:53119", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("OurFirst.NetCore3RestApiForTestWithJwt")) }; }); services.AddCors(options => { options.AddPolicy("Cors", builder => { builder.SetIsOriginAllowed(_=>true) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() .Build(); }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/V1/swagger.json", "Api")); app.UseCors("Cors"); app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
using UnityEngine; using System.Collections; public class Enemy : MonoBehaviour { //controls behaviour of enemies public GameObject explosionPrefab = null; public bool isSpecial = false; private float speed = 8f; Animator anim; Rigidbody2D rigid; void Awake (){ anim = GetComponent <Animator>(); rigid = GetComponent<Rigidbody2D>(); } void Update () { this.transform.Translate(Vector3.left * speed * Time.deltaTime); //sets the trajectory for the enemies } void OnTriggerEnter2D (Collider2D coll){ if (coll.gameObject.tag == "Bullet"){ anim.SetBool ("Dead", true); this.gameObject.tag = "Dead";//change tag to prevent the falling enemy from destroying you if (this.gameObject.tag == "Dead") PlayerData.GetInstance.score++; GameObject explosionObject = Instantiate(this.explosionPrefab) as GameObject; explosionObject.transform.position = this.transform.position; //creates explosion rigid.gravityScale = 3; //sets gravity scale to high to simulate fall } if (coll.gameObject.tag == "Bound" && !isSpecial) Destroy (gameObject); if (isSpecial) StartCoroutine (manualDestroy()); } IEnumerator manualDestroy (){ yield return new WaitForSeconds(7f); Destroy (this.gameObject); } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using OrchardCore.Security.Permissions; namespace DFC.ServiceTaxonomy.ContentApproval.Permissions { public class CanPerformReviewPermissions : IPermissionProvider { public static readonly Permission CanPerformContentDesignReviewPermission = new Permission(nameof(CanPerformContentDesignReviewPermission), "Can perform content design review"); public static readonly Permission CanPerformSMEReviewPermission = new Permission(nameof(CanPerformSMEReviewPermission), "Can perform SME review"); public static readonly Permission CanPerformUXReviewPermission = new Permission(nameof(CanPerformUXReviewPermission), "Can perform UX review"); public static readonly Permission CanPerformReviewPermission = new Permission(nameof(CanPerformUXReviewPermission), "Can perform review", new []{CanPerformUXReviewPermission, CanPerformSMEReviewPermission, CanPerformContentDesignReviewPermission, CanPerformApprovalPermissions.CanPerformStakeholderApprovalPermission}); public Task<IEnumerable<Permission>> GetPermissionsAsync() => Task.FromResult(new[] { CanPerformContentDesignReviewPermission, CanPerformSMEReviewPermission, CanPerformUXReviewPermission } .AsEnumerable()); public IEnumerable<PermissionStereotype> GetDefaultStereotypes() => new[] { new PermissionStereotype { Name = "Administrator", Permissions = GetPermissionsAsync().Result }, }; } }
using ScriptableObjectFramework.Attributes; using System.Linq; using UnityEditor; using UnityEngine; namespace ScriptableObjectFramework.Editor { [CustomPropertyDrawer(typeof(ModifiableProperty))] public class ModifiablePropertyDrawer : PropertyDrawer { public new ModifiableProperty attribute { get { var modifiable = (ModifiableProperty)base.attribute; if (modifiable.Modifiers == null) { modifiable.Modifiers = fieldInfo.GetCustomAttributes(typeof(PropertyModifier), false) .Cast<PropertyModifier>().OrderBy(s => s.order).ToList(); } return modifiable; } } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { ModifiableProperty att = attribute; bool visible = true; foreach (PropertyModifier mod in att.Modifiers) { mod.BeforeGUI(ref position, property, label, ref visible); } if (visible) { EditorGUI.BeginChangeCheck(); att.OnGUI(position, property, label); if (EditorGUI.EndChangeCheck()) { property.serializedObject.ApplyModifiedProperties(); foreach (PropertyModifier mod in att.Modifiers) { mod.OnValueChanged(property, fieldInfo); } } } foreach (PropertyModifier mod in att.Modifiers) { mod.AfterGUI(ref position, property, label, ref visible); } } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { float height = attribute.GetPropertyHeight(property, label); foreach (PropertyModifier mod in attribute.Modifiers) { height = mod.GetPropertyHeight(property, label, height); } return height; } } }
using System.Data.Entity; using UniversitySystemModels; namespace UniversitySystemData { public class UniversitySystemContextTpt : DbContext { public UniversitySystemContextTpt():base("name=UniversitySystemContext") { } public IDbSet<Person> Persons { get; set; } public IDbSet<Course> Courses { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Teacher>().ToTable("Teachers"); modelBuilder.Entity<Student>().ToTable("Students"); base.OnModelCreating(modelBuilder); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Web; using System.Web.Mvc; using WebQLKhoaHoc; using WebQLKhoaHoc.Models; namespace WebQLKhoaHoc.Controllers { [CustomizeAuthorize(Roles = "1")] public class AdminLinhVucController : Controller { private QLKhoaHocEntities db = new QLKhoaHocEntities(); // GET: AdminLinhVuc public async Task<ActionResult> Index() { var linhVucs = db.LinhVucs.Include(l => l.NhomLinhVuc); return View(await linhVucs.ToListAsync()); } // GET: AdminLinhVuc/Create public ActionResult Create() { ViewBag.MaNhomLinhVuc = new SelectList(db.NhomLinhVucs, "MaNhomLinhVuc", "TenNhomLinhVuc"); return View(); } // POST: AdminLinhVuc/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create([Bind(Include = "MaLinhVuc,TenLinhVuc,MaNhomLinhVuc")] LinhVuc linhVuc) { if (ModelState.IsValid) { db.LinhVucs.Add(linhVuc); await db.SaveChangesAsync(); return RedirectToAction("Index"); } ViewBag.MaNhomLinhVuc = new SelectList(db.NhomLinhVucs, "MaNhomLinhVuc", "TenNhomLinhVuc", linhVuc.MaNhomLinhVuc); return View(linhVuc); } // GET: AdminLinhVuc/Edit/5 public async Task<ActionResult> Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } LinhVuc linhVuc = await db.LinhVucs.FindAsync(id); if (linhVuc == null) { return HttpNotFound(); } ViewBag.MaNhomLinhVuc = new SelectList(db.NhomLinhVucs, "MaNhomLinhVuc", "TenNhomLinhVuc", linhVuc.MaNhomLinhVuc); return View(linhVuc); } // POST: AdminLinhVuc/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "MaLinhVuc,TenLinhVuc,MaNhomLinhVuc")] LinhVuc linhVuc) { if (ModelState.IsValid) { db.Entry(linhVuc).State = EntityState.Modified; await db.SaveChangesAsync(); return RedirectToAction("Index"); } ViewBag.MaNhomLinhVuc = new SelectList(db.NhomLinhVucs, "MaNhomLinhVuc", "TenNhomLinhVuc", linhVuc.MaNhomLinhVuc); return View(linhVuc); } // GET: AdminLinhVuc/Delete/5 public async Task<ActionResult> Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } LinhVuc linhVuc = await db.LinhVucs.FindAsync(id); if (linhVuc == null) { return HttpNotFound(); } return View(linhVuc); } // POST: AdminLinhVuc/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<ActionResult> DeleteConfirmed(int id) { LinhVuc linhVuc = await db.LinhVucs.FindAsync(id); db.LinhVucs.Remove(linhVuc); await db.SaveChangesAsync(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using jaytwo.Common.Extensions; using jaytwo.Common.Parse; using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; namespace jaytwo.Common.Test.Parse { [TestFixture] public partial class ParseUtilityTests { [Test] public void ParseUtility_ParseGuid() { Assert.AreEqual(new Guid("be9c3e50-1765-4a24-80f6-53b5944e0c73"), ParseUtility.ParseGuid("be9c3e50-1765-4a24-80f6-53b5944e0c73")); } [Test] [ExpectedException] [TestCase("Foo")] [TestCase("")] [TestCase(null)] public void ParseUtility_ParseGuid_bad_input(string input) { ParseUtility.ParseGuid(input); } [Test] public void ParseUtility_TryParseGuid() { Assert.AreEqual(new Guid("be9c3e50-1765-4a24-80f6-53b5944e0c73"), ParseUtility.TryParseGuid("be9c3e50-1765-4a24-80f6-53b5944e0c73")); } [Test] [TestCase("Foo")] [TestCase("")] [TestCase(null)] public void ParseUtility_TryParseGuid_bad_input(string input) { Assert.IsNull(ParseUtility.TryParseGuid(input)); } [Test] public void StringExtensions_ParseGuid() { Assert.AreEqual(new Guid("be9c3e50-1765-4a24-80f6-53b5944e0c73"), "be9c3e50-1765-4a24-80f6-53b5944e0c73".ParseGuid()); } [Test] [ExpectedException] [TestCase("Foo")] [TestCase("")] [TestCase(null)] public void StringExtensions_ParseGuid_bad_input(string input) { ParseUtility.ParseGuid(input); } [Test] public void StringExtensions_TryParseGuid() { Assert.AreEqual(new Guid("be9c3e50-1765-4a24-80f6-53b5944e0c73"), "be9c3e50-1765-4a24-80f6-53b5944e0c73".TryParseGuid()); } [Test] [TestCase("Foo")] [TestCase("")] [TestCase(null)] public void StringExtensions_TryParseGuid_bad_input(string input) { Assert.IsNull(ParseUtility.TryParseGuid(input)); } } }
namespace Assets.Scripts.Models { public interface IPlacement { string PrefabTemplatePath { get; set; } string PrefabPath { get; set; } } }
using System; using System.ComponentModel.DataAnnotations; using com.Sconit.Entity.SYS; namespace com.Sconit.Entity.SI.SAP { [Serializable] public partial class SAPSDMES0001 : EntityBase { #region O/R Mapping Properties public Int32 Id { get; set; } public string LIFNR { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 10)] [Display(Name = "SAPSDNormal_ZMESGUID", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string ZMESGUID { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 20)] [Display(Name = "SAPSDNormal_ZMESSO", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string ZMESSO { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 30)] [Display(Name = "SAPSDNormal_ZMESSOSEQ", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string ZMESSOSEQ { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 40)] [Display(Name = "SAPSDNormal_DOCTYPE", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string DOCTYPE { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 50)] [Display(Name = "SAPSDNormal_SALESORG", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string SALESORG { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 60)] [Display(Name = "SAPSDNormal_DISTRCHAN", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string DISTRCHAN { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 70)] [Display(Name = "SAPSDNormal_DIVISION", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string DIVISION { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 80)] [Display(Name = "SAPSDNormal_ORDREASON", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string ORDREASON { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 90)] [Display(Name = "SAPSDNormal_PRICEDATE", ResourceType = typeof(Resources.SI.SAPSDNormal))] public DateTime PRICEDATE { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 100)] [Display(Name = "SAPSDNormal_DOCDATE", ResourceType = typeof(Resources.SI.SAPSDNormal))] public DateTime DOCDATE { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 110)] [Display(Name = "SAPSDNormal_PARTNNUMB", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string PARTNNUMB { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 120)] [Display(Name = "SAPSDNormal_WADATIST", ResourceType = typeof(Resources.SI.SAPSDNormal))] public DateTime WADATIST { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 130)] [Display(Name = "SAPSDNormal_LIFEX", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string LIFEX { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 140)] [Display(Name = "SAPSDNormal_ITMNUMBER", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string ITMNUMBER { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 150)] [Display(Name = "SAPSDNormal_MATERIAL", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string MATERIAL { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 160)] [Display(Name = "SAPSDNormal_TARGETQTY", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string TARGETQTY { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 170)] [Display(Name = "SAPSDNormal_VRKME", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string VRKME { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 180)] [Display(Name = "SAPSDNormal_LGORT", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string LGORT { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 190)] [Display(Name = "SAPSDNormal_ZCSRQSJ", ResourceType = typeof(Resources.SI.SAPSDNormal))] public DateTime ZCSRQSJ { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq =200)] [Display(Name = "SAPSDNormal_Status", ResourceType = typeof(Resources.SI.SAPSDNormal))] public Int32 Status { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 210)] [Display(Name = "SAPSDNormal_BatchNo", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string BatchNo { get; set; } [Export(ExportName = "SAPSDNormal", ExportSeq = 220)] [Display(Name = "SAPSDNormal_UniqueCode", ResourceType = typeof(Resources.SI.SAPSDNormal))] public string UniqueCode { get; set; } public string SALEORDNO { get; set; } #endregion public override int GetHashCode() { if (Id != 0) { return Id.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { SAPSDMES0001 another = obj as SAPSDMES0001; if (another == null) { return false; } else { return (this.Id == another.Id); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Player : MonoBehaviour { private Touch dedo1; //Pantalla Táctil private float tiempoDeToque; private float timeElapsed = 0.0f; //Tiempo temblando public Player() { //Constructor } public Quaternion leerGiroscopio() { /* * Lee el cambio en la rotación del giroscopio y lo devuelve de forma que unity lo pueda leer. * Servirá para rotar al personaje */ Quaternion phoneAngles = new Quaternion(); phoneAngles.eulerAngles = Input.gyro.rotationRate; return GyroToUnity(phoneAngles); } public static Quaternion GyroToUnity(Quaternion q) { /* * Corrije la diferencia del plano cartesiano entre unity y el celular */ return new Quaternion(q.x, q.y, -q.z, -q.w); } public void girarCamaraConLaMirada(GameObject camara) { /* * Lee la información del giroscopio del celular y actualiza la información de la cámara. * Sólo funciona en celulares que contengan giroscopio. */ camara.transform.rotation *= leerGiroscopio(); } public void interactuarConLaMirada(GameObject camara) { /* * Manda un rayo hacia donde mira el usuario. Servirá para moverse por el escenario utilizando la mirada */ RaycastHit toque; Ray rayo = new Ray(camara.transform.position, camara.transform.forward); Debug.DrawRay(rayo.origin, 100 * rayo.direction, Color.yellow); } private float gestoUnDedoLateral() { /* * Algoritmo para mover la vista del personaje moviendo la pantalla táctil * La función devuelve un valor flotante correspondiente al movimiento horizontal */ if (Input.touchCount == 1) { const float COMPLEMENTO_PARA_Y = .5f; const float ATENUAR_MOVIMIENTO = .1f; dedo1 = Input.GetTouch(0); if (Mathf.Abs(dedo1.deltaPosition.x) > (Mathf.Abs(dedo1.deltaPosition.y) + COMPLEMENTO_PARA_Y)) { if (Mathf.Abs(dedo1.deltaPosition.x) < 5) return 0; else return dedo1.deltaPosition.x * ATENUAR_MOVIMIENTO; } else { return 0f; } } return 0f; } public void girarCamaraLateral(GameObject camara) { /* * Gira la cámara hacia los lados cuando se arrastra un dedo de forma lateral. * Funciona en celulares sin giroscopio */ camara.transform.rotation *= Quaternion.Euler(0f, gestoUnDedoLateral(), 0f); } public void obtenerNombreDelObjetoTocado(Camera vision) { /* No terminada * El propósito de esta función es tener claro a dónde da click el jugador */ if (huboClick() && Input.touchCount == 0) { RaycastHit toque; Ray rayo = vision.ScreenPointToRay(new Vector3(dedo1.position.x, dedo1.position.y, 0f)); Debug.DrawRay(rayo.origin, 100 * rayo.direction, Color.green); if (Physics.Raycast(rayo, out toque)) { //TODO: Probar esta función //print(toque.collider.name); } else { } } medirTiempoDeToque(); } private bool huboClick() { /* * Determina si el usuario toco un objeto de forma intencional o si * tocó la pantalla táctil con un propósito diferente al de seleccionar algo */ const float TIEMPO_MAXIMO_DE_UN_TOQUE_NORMAL = 0.3f; //Tiempo en tocar const float DISTANCIA_MAXIMA_DE_MOVIMIENTO_DE_UN_TOQUE = 0.5f; //A veces se mueve tantito el dedo return tiempoDeToque < TIEMPO_MAXIMO_DE_UN_TOQUE_NORMAL && tiempoDeToque != 0f && Mathf.Abs(dedo1.deltaPosition.x) < DISTANCIA_MAXIMA_DE_MOVIMIENTO_DE_UN_TOQUE && Mathf.Abs(dedo1.deltaPosition.y) < DISTANCIA_MAXIMA_DE_MOVIMIENTO_DE_UN_TOQUE; } private void medirTiempoDeToque() { /* * Codigo para complementar la función de huboClick() * Mide el tiempo que una persona mantiene un dedo en la pantalla */ if (Input.touchCount == 1) { tiempoDeToque += Time.deltaTime; } else { tiempoDeToque = 0f; } } public void shakeObject(float duration, float magnitude, GameObject objectToShake, float atenuacionSismo) { /* * Algoritmo para crear el efecto de terremoto en el escenario * Se agregó la función de atenuar el sismo con el tiempo */ Vector3 originalPos = objectToShake.transform.position; float x = Random.Range(-atenuacionSismo, atenuacionSismo) * magnitude; float y = Random.Range(-atenuacionSismo, atenuacionSismo) * magnitude; float z = Random.Range(-atenuacionSismo, atenuacionSismo) * magnitude; timeElapsed += Time.deltaTime; if (timeElapsed < duration) { objectToShake.transform.position += new Vector3(x, y, z); objectToShake.transform.rotation = Quaternion.EulerAngles(x*2f, 0f, z*2f); } } }
// ----------------------------------------------------------------------- // <copyright file="CultureManager.cs"> // Copyright (c) Michal Pokorný. All Rights Reserved. // </copyright> // ----------------------------------------------------------------------- namespace Pentagon.Extensions.Localization.Json { using System.Collections.Generic; using IO.Json; using Newtonsoft.Json; public class RootObjectJson { [JsonProperty("culture")] public string Culture { get; set; } [JsonProperty("format")] [JsonConverter(typeof(EnumJsonConverter<JsonFormat>))] public JsonFormat Format { get; set; } = JsonFormat.KeyValue; [JsonProperty("resources")] public List<ResourceJson> Resources { get; set; } } }
public struct EntityStats { public float hp; public int atk, trt, cmp, intl, wis; public EntityStats(int hp, int atk, int trt, int cmp, int intl, int wis) { this.hp = hp; this.atk = atk; this.trt = trt; this.cmp = cmp; this.intl = intl; this.wis = wis; } public static EntityStats operator+(EntityStats a, EntityStats b) { EntityStats stats = new EntityStats(); stats.hp = a.hp + b.hp; stats.atk = a.atk + b.atk; stats.trt = a.trt + b.trt; stats.cmp = a.cmp + b.cmp; stats.intl = a.intl + b.intl; return stats; } }
namespace ChatServer.Messaging.Commands { using System; using System.Collections.Concurrent; using System.Linq; using System.Threading.Tasks; using ChatProtos.Networking; using ChatProtos.Networking.Messages; using Google.Protobuf; using HServer; using HServer.Networking; /// <inheritdoc /> /// <summary> /// The create channel command. /// </summary> public class CreateChannelCommand : IChatServerCommand { /// <inheritdoc /> public async Task ExecuteTaskAsync(HChatClient client, RequestMessage message) { var parsed = ProtobufHelper.TryParse(CreateChannelRequest.Parser, message.Message, out var request); if (!parsed || !Guid.TryParse(request.CommunityId, out _)) { await client.SendResponseTaskAsync(ResponseStatus.BadRequest, ByteString.Empty, message) .ConfigureAwait(false); return; } var community = client.GetCommunities() .FirstOrDefault(clientCommunity => clientCommunity.Id == Guid.Parse(request.CommunityId)); if (community == null || !community.HasClient(client.Id)) { await client.SendResponseTaskAsync( ResponseStatus.NotFound, RequestType.CreateChannel, ByteString.Empty, message.Nonce).ConfigureAwait(false); return; } var channel = new HChannel( Guid.NewGuid(), request.ChannelName, community, new ConcurrentDictionary<Guid, HChatClient>(), DateTime.UtcNow); if (!community.ChannelManager.AddItem(channel) || !channel.AddItem(client)) { await client.SendResponseTaskAsync(ResponseStatus.Error, ByteString.Empty, message) .ConfigureAwait(false); return; } var response = new CreateChannelResponse { ChannelId = channel.Id.ToString(), ChannelName = channel.Name } .ToByteString(); await community.SendToAllTask(ResponseStatus.Created, RequestType.CreateChannel, response) .ConfigureAwait(false); } } }
using Presenter.Core.ConfigurationManager; using Presenter.Core.ScreeenManager; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace Presenter.ControlPanel { /// <summary> /// Lógica de interacción para App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); ScreenManager.Instance.Run(); } private void Application_Exit(object sender, ExitEventArgs e) { if (ScreenManager.Instance.Presentations == null) return; foreach (var process in ScreenManager.Instance.Presentations.Values) if(!process.HasExited) process.Kill(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using TMPro; public class TimerClass : MonoBehaviour//, IPointerClickHandler { public const int TIMER_MAX = 60; public float time; private float _timer; // public float targetTime = 60.0f; private bool isRunning = false; private Image timerImage; private TextMeshProUGUI textMeshPro; int interval = 1; float nextTime = 0; float targetTime; float endTime; bool midPointReached = false; // Start is called before the first frame update void Start() { Debug.Log("<color=yellow>== TimerClass.Start ==</color>"); timerImage = gameObject.GetComponent<Image>(); textMeshPro = GameObject.FindWithTag("TurnCounterText").GetComponent<TextMeshProUGUI>(); // targetTime = turnTimer; // StartTimer(TIMER_MAX); } public void StartTimer(float t = TIMER_MAX) { targetTime = t; endTime = Time.time + t; isRunning = true; } // Update is called once per frame void Update() { // only check in 1 second intervals if (isRunning && Time.time >= nextTime) { if (Time.time >= endTime) { isRunning = false; timerEnded(); } else if (midPointReached == false && Time.time >= (endTime / 2)) { midPointReached = true; hitMidPoint(); } timerImage.fillAmount = (Mathf.Round(endTime - Time.time) / targetTime); textMeshPro.text = Mathf.Round(endTime - Time.time).ToString(); nextTime += interval; } } void timerEnded() { Debug.Log("* timer ended!"); midPointReached = false; EventParam eventParam = new EventParam(); // eventParam.data = characterView.model; eventParam.name = "turnCounterComplete"; EventManager.TriggerEvent("combatEvent", eventParam); // for now, just restart timer // StartTimer(TIMER_MAX); } void hitMidPoint() { Debug.Log("* midpoint reached"); EventParam eventParam = new EventParam(); eventParam.name = "turnCounterMidpoint"; EventManager.TriggerEvent("combatEvent", eventParam); } // public void OnPointerClick(PointerEventData e) // { // Debug.Log("click!"); // if (isRunning == true) // isRunning = false; // else isRunning = true; // } }
using gView.Framework.Data; namespace gView.Framework.FDB { public interface IFeatureImportEvents { void BeforeInsertFeaturesEvent(IFeatureClass sourceFc, IFeatureClass destFc); void AfterInsertFeaturesEvent(IFeatureClass sourceFc, IFeatureClass destFc); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Foundry.Domain; namespace Foundry.Website.Models.Dashboard { public class IndexViewModel : ViewModel { public IEnumerable<NewsItem> NewsItems { get; set; } public IEnumerable<Domain.Project> WritableProjects { get; set; } } }
using UnityEngine; public class GazeRaycast : MonoBehaviour { public RaycastHit Hit; public Ray Ray; private int _layer_mask; // Use this for initialization void Awake () { _layer_mask = LayerMask.GetMask("Buttons"); } // Update is called once per frame void Update () { Ray = new Ray(transform.position, transform.forward); if (Physics.Raycast(Ray, out Hit, _layer_mask)) { } } }
using System.Web; using System.Web.Optimization; namespace CYT.Web { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); bundles.Add(new ScriptBundle("~/bundles/angular/library").Include( "~/Scripts/angular.js", "~/Scripts/angular-file-upload.min.js", "~/Scripts/angular-img-cropper.js", "~/Scripts/angular-sanitize.js", "~/Scripts/angular-resource.js", "~/Scripts/angular-route.js", "~/Scripts/angular-signalr-hub.js", "~/Scripts/angular-animate.js", "~/Scripts/angular-touch.js", "~/Scripts/ckeditor/ckeditor.js", "~/Scripts/angular-ckeditor/angular-ckeditor.js", "~/Scripts/lodash.js", "~/Scripts/angular-google-maps.js", "~/Scripts/bower_components/angular-ui-router/release/angular-ui-router.js", "~/Scripts/bower_components/angular-bootstrap/ui-bootstrap-tpls.js", "~/Scripts/bower_components/angular-bootstrap-lightbox/dist/angular-bootstrap-lightbox.js", "~/Scripts/bower_components/angular-ellipsis/src/angular-ellipsis.js" )); bundles.Add(new ScriptBundle("~/bundles/angular/app").Include( "~/App/App.js", "~/App/Core/*.module.js", "~/App/Core/config.js", /// DataServices "~/App/DataServices/app.data.module.js", "~/App/DataServices/*.data.js", /// Main "~/App/Main/*.module.js", "~/App/Main/*.controller.js", /// Filter "~/App/SearchRecipes/*.module.js", "~/App/SearchRecipes/*.controller.js", /// User "~/App/User/*.module.js", "~/App/User/*.controller.js", /// Recipe "~/App/Recipe/*.module.js", "~/App/Recipe/*.controller.js", /// User Admin "~/App/UserAdmin/*.module.js", "~/App/UserAdmin/*.controller.js", /// User Administrator "~/App/Administrator/*.module.js", "~/App/Administrator/*.controller.js", /// Directives "~/App/Directives/*.module.js", "~/App/Directives/*.directive.js" )); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js" )); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css", "~/Content/user-admin.css", "~/Scripts/bower_components/angular-bootstrap-lightbox/dist/angular-bootstrap-lightbox.css" )); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MoveLightCube : MonoBehaviour { float time; // Use this for initialization void Start () { } // Update is called once per frame void Update () { time += Time.deltaTime; transform.rotation = Quaternion.Euler(0, time*16,0); } }
using UsersLib.DbContextSettings; using UsersLib.Entity; namespace UsersLib.DbControllers { public class DbLogController : IDbLogController { public void Log(AccessLog logEntity) { using (UsersLibDbContext dbContext = new UsersLibDbContext()) { dbContext.AccessLog.Add(logEntity); dbContext.SaveChanges(); } } } }
using System; using System.Collections.Generic; namespace DynamicNPCSprites { public class ConditionalTexture { public string Name { get; set; } public string Type { get; set; } public string[] Weather { get; set; } public string[] Season { get; set; } public string Sprite { get; set; } public string Portrait { get; set; } } }
using System.Linq; using System.Web.Mvc; using LINQ101MVC.Models; using System.Data.Entity; using System.Net; using System.Threading.Tasks; using LINQ101MVC.ViewModels; namespace LINQ101MVC.Controllers { public class ProductSubCategoryController : Controller { private readonly ApplicationDbContext _db = ApplicationDbContext.Create(); // GET: ProductSubCategoryViewModel public ActionResult Index() { var subCategories = _db.ProductSubcategories .Include(s => s.ProductCategory) .Include(s => s.Products) .OrderBy(s => s.ProductCategory.Name) .ThenBy(s => s.Name); return View(subCategories); } [HttpGet] public ActionResult AddOrEdit(int? id) { var subCategory = new ProductSubcategory(); if(id.HasValue) subCategory = _db.ProductSubcategories.FirstOrDefault(s => s.ProductSubcategoryID == id); if (subCategory == null) return HttpNotFound(); return View(new ProductSubCategoryViewModel(subCategory)); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Save([Bind(Prefix = "ProductSubcategory")]ProductSubcategory subCategory) { if (!ModelState.IsValid) return View("AddOrEdit", new ProductSubCategoryViewModel(subCategory)); if (subCategory.ProductSubcategoryID != 0) { var subCategoryInDb = _db.ProductSubcategories.FirstOrDefault( s => s.ProductSubcategoryID == subCategory.ProductSubcategoryID); if (subCategoryInDb == null) return HttpNotFound(); ModelMapper.Map<IProductSubCategory>(subCategory, subCategoryInDb); } else { var newSubCategory = new ProductSubcategory(); ModelMapper.Map<IProductSubCategory>(subCategory, newSubCategory); _db.ProductSubcategories.Add(newSubCategory); } await _db.SaveChangesAsync(); return RedirectToAction("Index"); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Delete(int? id) { var subCategory = _db.ProductSubcategories.Include(s => s.Products).FirstOrDefault(s => s.ProductSubcategoryID == id); if (subCategory == null) return HttpNotFound(); if (subCategory.Products.Count > 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); _db.ProductSubcategories.Remove(subCategory); await _db.SaveChangesAsync(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { _db?.Dispose(); } } }
using System; using Boxofon.Web.Model; namespace Boxofon.Web.MailCommands { public interface IMailCommand { Guid UserId { get; set; } string BoxofonNumber { get; set; } } }
using System; using System.Diagnostics; using System.Linq; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Windows; using NLog; namespace Simple.Wpf.Composition.Services { public sealed class MemoryService : IMemoryService, IDisposable { private const int Kilo = 1024; private const int Mega = 1024 * 1000; private const int Giga = 1024 * 1000 * 1000; private readonly IConnectableObservable<Counters> _countersObservable; private readonly IScheduler _dispatcherScheduler; private readonly IDisposable _disposable; private readonly Logger _logger; private readonly IScheduler _taskPoolScheduler; public MemoryService(IScheduler taskPoolScheduler = null, IScheduler dispatcherScheduler = null) { _taskPoolScheduler = taskPoolScheduler ?? TaskPoolScheduler.Default; _dispatcherScheduler = dispatcherScheduler ?? DispatcherScheduler.Current; _logger = LogManager.GetCurrentClassLogger(); _countersObservable = Observable.Create<Counters>(x => CreateCounters(x)) .SubscribeOn(_taskPoolScheduler) .CombineLatest(BufferedDispatcherIdle(TimeSpan.FromSeconds(1)), (x, y) => x) .Replay(1); _disposable = _countersObservable.Connect(); } public void Dispose() { _disposable.Dispose(); } public IObservable<decimal> MemoryInBytes => Create(1); public IObservable<decimal> MemoryInKiloBytes => Create(Kilo); public IObservable<decimal> MemoryInMegaBytes => Create(Mega); public IObservable<decimal> MemoryInGigaBytes => Create(Giga); private IObservable<Unit> BufferedDispatcherIdle(TimeSpan timeSpan) { var mainWindow = Application.Current.MainWindow; return Observable.FromEventPattern( h => mainWindow.Dispatcher.Hooks.DispatcherInactive += h, h => mainWindow.Dispatcher.Hooks.DispatcherInactive -= h, _dispatcherScheduler) .Buffer(timeSpan, _taskPoolScheduler) .Where(x => x.Any()) .Select(x => Unit.Default); } private IDisposable CreateCounters(IObserver<Counters> observer) { var disposable = new CompositeDisposable(); try { var processName = Process.GetCurrentProcess().ProcessName; var memoryCounter = new PerformanceCounter("Process", "Working Set - Private", processName); var cpuCounter = new PerformanceCounter("Process", "% Processor Time", processName); var counters = new Counters(memoryCounter, cpuCounter); observer.OnNext(counters); disposable.Add(counters); } catch (Exception exn) { observer.OnError(exn); } return disposable; } private IObservable<decimal> Create(int divisor) { return _countersObservable.Select(x => decimal.Round(WorkingSetPrivate(x.MemoryCounter) / divisor, 2)) .DistinctUntilChanged(); } private decimal WorkingSetPrivate(PerformanceCounter memoryCounter) { try { return Convert.ToDecimal(memoryCounter.NextValue()); } catch (Exception exn) { _logger.Warn("Failed to calculate working set (private), exception message - '{0}'", exn.Message); return 0; } } internal sealed class Counters : IDisposable { public Counters(PerformanceCounter memoryCounter, PerformanceCounter cpuCounter) { MemoryCounter = memoryCounter; CpuCounter = cpuCounter; } public PerformanceCounter MemoryCounter { get; } public PerformanceCounter CpuCounter { get; } public void Dispose() { MemoryCounter.Dispose(); CpuCounter.Dispose(); } } } }
using System; using System.IO; using YamlDotNet.Serialization; namespace PopulationFitness.Output { public static class ConfigWriter { /** * Writes a YAML encoding of the config to the file * * @param config * @param filename * @throws IOException */ public static void Write(Tuning config, String filename) { var serialized = ToString(config); File.WriteAllText(filename, serialized); } /** * Generates a string YAML encoding of the configuration * * @param config * @return */ public static string ToString(Tuning config) { var serializer = new Serializer(); return serializer.Serialize(new { Id = config.Id, Function = config.Function, HistoricFit = config.HistoricFit, DiseaseFit = config.DiseaseFit, ModernFit = config.ModernFit, ModernBreeding = config.ModernBreeding.ToString(), NumberOfGenes = config.NumberOfGenes, SizeOfGenes = config.SizeOfGenes, MutationsPerGene = config.MutationsPerGene.ToString(), SeriesRuns = config.SeriesRuns, ParallelRuns = config.ParallelRuns }); } } }
namespace Booking.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddLunch : DbMigration { public override void Up() { AddColumn("dbo.Hotels", "BreakfastPrice", c => c.Decimal(nullable: false, precision: 18, scale: 2)); AddColumn("dbo.Hotels", "LunchPrice", c => c.Decimal(nullable: false, precision: 18, scale: 2)); AddColumn("dbo.Hotels", "DinnerPrice", c => c.Decimal(nullable: false, precision: 18, scale: 2)); } public override void Down() { DropColumn("dbo.Hotels", "DinnerPrice"); DropColumn("dbo.Hotels", "LunchPrice"); DropColumn("dbo.Hotels", "BreakfastPrice"); } } }
using UnityEngine; [CreateAssetMenu(fileName = "Weapon", menuName = "Inventory/Weapon", order = 1)] public class ScriptableWeapon : ScriptableItem { [Header("Type")] public WeaponType weaponType; [Header("Stats")] public float damage = 10f; public float range = 35f; public float fireRate = 10f; [Header("Ammunition")] public ScriptableBullet bullet; public int magazineCapacity = 12; [Header("Sound")] public AudioClip fireSFX; public AudioClip emptySFX; public AudioClip reloadSFX; [Header("Reload")] public bool autoReload; } public enum WeaponType { None, Pistol, Rifle, Sniper, Shotgun, Missile_Launcher, Melee }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Shapes; namespace FontAwesome5.Extensions { public static class EFontAwesomeIconsExtensions { /// <summary> /// Creates a new System.Windows.Media.ImageSource of a specified FontAwesomeIcon and foreground System.Windows.Media.Brush. /// </summary> /// <param name="icon">The FontAwesome icon to be drawn.</param> /// <param name="foregroundBrush">The System.Windows.Media.Brush to be used as the foreground.</param> /// <param name="emSize">The font size in em.</param> /// <returns>A new System.Windows.Media.ImageSource</returns> public static ImageSource CreateImageSource(this EFontAwesomeIcon icon, Brush foregroundBrush, double emSize = 100) { return new DrawingImage(icon.CreateDrawing(foregroundBrush, emSize)); } /// <summary> /// Creates a new System.Windows.Media.ImageSource of a specified FontAwesomeIcon and foreground System.Windows.Media.Brush. /// </summary> /// <param name="icon">The FontAwesome icon to be drawn.</param> /// <param name="foregroundBrush">The System.Windows.Media.Brush to be used as the foreground.</param> /// <returns>A new System.Windows.Media.ImageSource</returns> public static ImageSource CreateImageSource(this EFontAwesomeIcon icon, Brush foregroundBrush, Pen pen) { return new DrawingImage(icon.CreateDrawing(foregroundBrush, pen)); } /// <summary> /// Creates a new System.Windows.Media.Drawing of a specified FontAwesomeIcon and foreground System.Windows.Media.Brush. /// This will use the Font for the Drawing creation. /// </summary> /// <param name="icon">The FontAwesome icon to be drawn.</param> /// <param name="foregroundBrush">The System.Windows.Media.Brush to be used as the foreground.</param> /// <param name="emSize">The font size in em.</param> /// <returns>A new System.Windows.Media.Drawing</returns> public static Drawing CreateDrawing(this EFontAwesomeIcon icon, Brush foregroundBrush, double emSize = 100) { var visual = new DrawingVisual(); using (var drawingContext = visual.RenderOpen()) { drawingContext.DrawText(icon.CreateFormattedText(foregroundBrush, emSize), new Point(0, 0)); } return visual.Drawing; } /// <summary> /// Creates a new System.Windows.Media.Drawing of a specified FontAwesomeIcon. /// This will use the SVG for the Drawing creation. /// </summary> /// <param name="icon">The FontAwesome icon to be drawn.</param> /// <param name="brush">The Brush with which to fill the Geometry. This is optional, and can be null. If the brush is null, no fill is drawn.</param> /// <param name="pen">The Pen with which to stroke the Geometry. This is optional, and can be null. If the pen is null, no stroke is drawn.</param> /// <returns>A new System.Windows.Media.Drawing</returns> public static Drawing CreateDrawing(this EFontAwesomeIcon icon, Brush brush, Pen pen) { var visual = new DrawingVisual(); using (var drawingContext = visual.RenderOpen()) { if (icon.GetSvg(out var strPath, out var width, out var height)) { drawingContext.DrawGeometry(brush, pen, Geometry.Parse(strPath)); } } return visual.Drawing; } /// <summary> /// Creates a new System.Windows.Media.FormattedText of a specified FontAwesomeIcon and foreground System.Windows.Media.Brush. /// </summary> /// <param name="icon">The FontAwesome icon to be drawn.</param> /// <param name="foregroundBrush">The System.Windows.Media.Brush to be used as the foreground.</param> /// <param name="emSize">The font size in em.</param> /// <returns>A new System.Windows.Media.FormattedText</returns> public static FormattedText CreateFormattedText(this EFontAwesomeIcon icon, Brush foregroundBrush, double emSize = 100) { return new FormattedText(icon.GetUnicode(), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, icon.GetTypeFace(), emSize, foregroundBrush) { TextAlignment = TextAlignment.Center, }; } /// <summary> /// Creates a new System.Windows.Media.FormattedText of a specified FontAwesomeIcon and foreground System.Windows.Media.Brush. /// </summary> /// <param name="icon">The FontAwesome icon to be drawn.</param> /// <param name="foregroundBrush">The System.Windows.Media.Brush to be used as the foreground.</param> /// <param name="emSize">The font size in em.</param> /// <param name="flowDirection">The flow direction of the font</param> /// <param name="textFormattingMode">The text formatting mode of the font</param> /// <param name="numberSubstitution">The number substitution of the font.</param> /// <returns>A new System.Windows.Media.FormattedText</returns> public static FormattedText CreateFormattedText(this EFontAwesomeIcon icon, Brush foregroundBrush, double emSize, FlowDirection flowDirection, TextFormattingMode textFormattingMode, NumberSubstitution numberSubstitution) { return new FormattedText(icon.GetUnicode(), CultureInfo.InvariantCulture, flowDirection, icon.GetTypeFace(), emSize, foregroundBrush, numberSubstitution, textFormattingMode); } /// <summary> /// Creates a new System.Windows.Shapes.Path of a specified FontAwesomeIcon and foreground System.Windows.Media.Brush. /// </summary> /// <param name="icon">The FontAwesome icon to be drawn.</param> /// <param name="foregroundBrush">The System.Windows.Media.Brush to be used as the foreground.</param> /// <param name="emSize">The font size in em.</param> /// <returns>A new System.Windows.Shapes.Path</returns> public static Path CreatePath(this EFontAwesomeIcon icon, Brush foregroundBrush, double emSize = 100) { if (icon.GetSvg(out var strPath, out var width, out var height)) { return new Path { Data = Geometry.Parse(strPath), Width = width, Height = height, Fill = foregroundBrush }; } return null; } /// <summary> /// Creates a new System.Windows.Media.Geometry of a specified FontAwesomeIcon. /// </summary> /// <param name="icon">The FontAwesome icon to be drawn.</param> /// <param name="width">The width of the SVG.</param> /// <param name="height">The height of the SVG</param> /// <returns>A new System.Windows.Media.Geometry</returns> public static Geometry CreateGeometry(this EFontAwesomeIcon icon, out int width, out int height) { if (icon.GetSvg(out var strPath, out width, out height)) { return Geometry.Parse(strPath); } return null; } } }
using System; using System.Collections.Generic; using System.Text; namespace Bucket_Opdracht_Version2.Structs { class EmptyStructs { } }
using System.Collections.Generic; using UnityEngine; public class PlayerRankCtrl : MonoBehaviourIgnoreGui { public List<IParkourPlayer_Xiong> m_ListPlayer; float mTimeLastRank = 0f; // Update is called once per frame void Update () { CheckPlayerRank(); } /// <summary> /// 排序比较器. /// </summary> int CompareRankDt(IParkourPlayer_Xiong x, IParkourPlayer_Xiong y)//排序器 { if (x == null) { if (y == null) { return 0; } return 1; } if (y == null) { return -1; } int retval = 0; Vector3 forward_X = x.transform.right; Vector3 pos_X = x.transform.position; Vector3 pos_Y = y.transform.position; Vector3 vecXY = pos_Y - pos_X; float dotVal = Vector3.Dot(forward_X, vecXY); if (dotVal > 0f) { //x在y的后面. retval = 1; } else if (dotVal < 0f) { //x在y的前面. retval = -1; } //Debug.Log("rv == " + retval + ", x == " + x.name + ", y == " + y.name); return retval; } /// <summary> /// 检测玩家排名状态. /// </summary> void CheckPlayerRank() { if (Time.time - mTimeLastRank < 0.3f) { return; } mTimeLastRank = Time.time; if (m_ListPlayer.Count < 2) { return; } m_ListPlayer.Sort(CompareRankDt); for (int i = 0; i < m_ListPlayer.Count; i++) { if (m_ListPlayer[i].PlayerRankObj == null) { continue; } if (i == 0) { if (!m_ListPlayer[i].PlayerRankObj.activeInHierarchy) { m_ListPlayer[i].PlayerRankObj.SetActive(true); } } else { if (m_ListPlayer[i].PlayerRankObj.activeInHierarchy) { m_ListPlayer[i].PlayerRankObj.SetActive(false); } } } } }
using System; using System.Collections.Generic; using CurrencyLibs.Interfaces; using CurrencyLibs.US; namespace CurrencyLibs { public class CurrencyRepo : ICurrencyRepo { public List<ICoin> Coins { get; set; } public CurrencyRepo() { this.Coins = new List<ICoin>(); } public string About() { return $"{this.ToString()}"; } public void AddCoin(ICoin c) { if (c == null) throw new ArgumentNullException(); this.Coins.Add(c); } public ICurrencyRepo CreateChange(double Amount) { CurrencyRepo retCurrencyRepo = new CurrencyRepo(); // for every whole number we return a dollarCoin if (Amount >= 1.0) { int times = (int)Amount / (int)1.0; InsertInto(new DollarCoin(), times, retCurrencyRepo); Amount -= times; } // for every .25, we return quarter if (Amount >= 0.25) { int times = (int) (Amount / .25); InsertInto(new Quarter(), times, retCurrencyRepo); Amount -= (times * .25); } // for every .10, we return dime if (Amount >= 0.10) { int times = (int)Math.Floor(Amount / .10); InsertInto(new Dime(), times, retCurrencyRepo); Amount = RemoveFrom((decimal)Amount, times, 0.10m); } // for every .05, we return a dime if (Amount >= 0.05) { int times = (int)Math.Floor(Amount / .05); InsertInto(new Nickel(), times, retCurrencyRepo); Amount = RemoveFrom((decimal)Amount, times, 0.05m); } // for everything else we return a penny if (Amount >= 0.01) { int times = (int)Math.Floor(Amount / .01); InsertInto(new Penny(), times, retCurrencyRepo); Amount = RemoveFrom((decimal)Amount, times, 0.01m); } return retCurrencyRepo; } private void InsertInto(USCoin coin, int times, ICurrencyRepo repo) { for (int i = 0; i < times; i++) { repo.Coins.Add(coin); } } private double RemoveFrom(decimal src, int times, decimal toRemove) { for (int i = 0; i < times; i++) { src -= toRemove; } return (double)src; } public ICurrencyRepo CreateChange(double AmountTendered, double TotalCost) { throw new NotImplementedException(); } public int GetCoinCount() { int totalCoins = 0; this.Coins.ForEach(coin => totalCoins += 1); return totalCoins; } public ICurrencyRepo MakeChange(double Amount) { return MakeChange(Amount, 0); } public ICurrencyRepo MakeChange(double AmountTendered, double TotalCost) { throw new System.NotImplementedException(); } public ICoin RemoveCoin(ICoin c) { if (c == null) throw new ArgumentNullException(); bool didRemove = this.Coins.Remove(c); return didRemove ? c : null; } public double TotalValue() { double totalval = 0.0; this.Coins.ForEach(coin => totalval += coin.MonetaryValue); return totalval; } public List<ICurrency> getCurrencyList() { throw new NotImplementedException(); } } }
using System.Collections.Generic; using UnityEngine; using UnityEngine.InputSystem; [RequireComponent(typeof(PlayerController))] public class Manipulate : MonoBehaviour { public static Color debugColor = Color.cyan; public static Vector2 debugOffset = Vector2.right; public float radius = 5; public LayerMask manipulableLayer; public LayerMask obstacleLayer; public bool isManipulating; PlayerController player; public Manipulable[] manipulables; // Manager for all actions for Creation private void Start() { player = GetComponent<PlayerController>(); } public void OnManipulate(InputAction.CallbackContext context) { switch (context.phase) { case InputActionPhase.Started: isManipulating = true; break; case InputActionPhase.Canceled: isManipulating = false; break; } } private void FixedUpdate() { manipulables = FindManipulables(); } //Finds all Manipulables (Rigidbody2D) in its manipulateRadius. public Manipulable[] FindManipulables() { List<Manipulable> manipulables = new List<Manipulable>(); Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, radius, manipulableLayer); foreach(Collider2D c in colliders) { if (c.attachedRigidbody) { Manipulable manipulable = c.GetComponent<Manipulable>(); if (manipulable) manipulables.Add(manipulable); } } return manipulables.ToArray(); } public RaycastHit2D HitManipulable(Vector2 playerPosition, Manipulable manipulable) { Vector2 direction = manipulable.rigid.position - playerPosition; RaycastHit2D hit = Physics2D.Raycast(playerPosition, direction, direction.magnitude, manipulableLayer); return hit; } //Finds closest manipulables relative to an direction public Manipulable FindManipulateable(Vector2 dir, float maxMass = 1000) { Vector2 myPosition = (Vector2)transform.position + dir * radius; myPosition = transform.position; Manipulable closest = null; float closestDistance = float.MaxValue; foreach (Manipulable m in manipulables) { if(!m || !m.rigid) continue; float distance = (myPosition - m.rigid.position).magnitude; distance += ((Vector2)transform.position - m.rigid.position).magnitude * 2; if (distance < closestDistance && m.rigid.mass < maxMass) { // Check if obstacles are in the way Vector2 manipulableDir = (m.rigid.position - (Vector2) player.myRigid.position)*1.1f; //Debug.DrawRay(player.myRigid.position, manipulableDir,Color.red,5); RaycastHit2D[] hits = Physics2D.RaycastAll(player.myRigid.position, manipulableDir,manipulableDir.magnitude, obstacleLayer); bool isObstacleInWay = false; foreach (var hit in hits) { if (hit && hit.collider != m.collider) { //Debug.DrawRay(transform.position, manipulableDir,Color.red,1); DebugPlus.DrawWireCube(hit.collider.transform.position, hit.collider.bounds.size).Color(Color.red).Duration(1); isObstacleInWay = true; } } if(isObstacleInWay) continue; closest = m; closestDistance = distance; } } return closest; } public Manipulable FindClosestManipulable(float maxMass = 1000) { if (!isManipulating) return null; Manipulable closest = null; float closestDistance = radius+10; foreach(Manipulable m in manipulables) { float distance = ((Vector2)transform.position - m.rigid.position).magnitude; if(distance < closestDistance && m.rigid.mass < maxMass) { closest = m; closestDistance = distance; } } return closest; } private void OnDrawGizmosSelected() { Gizmos.color = debugColor; Gizmos.DrawWireSphere(transform.position, radius); if(manipulables != null) foreach (Manipulable m in manipulables) if(m) Gizmos.DrawWireSphere(m.rigid.position, 0.1f); } }
using System; using SharpArch.Domain.DomainModel; namespace Profiling2.Domain.Scr.PersonRecommendation { public class AdminScreeningRequestPersonRecommendationImport : Entity { public virtual ScreeningRequestPersonRecommendation ScreeningRequestPersonRecommendation { get; set; } public virtual DateTime ImportDate { get; set; } public virtual int PreviousID { get; set; } public virtual string Notes { get; set; } public virtual bool Archive { get; set; } } }
namespace com.Sconit.WebService.SI { using System.Web.Services; using com.Sconit.Entity; using com.Sconit.Service.SI; [WebService(Namespace = "http://com.Sconit.WebService.SI.LeanEngineService/")] public class LeanEngineService : BaseWebService { #region public properties private ILeanEngineMgr leanEngineMgr { get { return GetService<ILeanEngineMgr>(); } } #endregion [WebMethod] public void RunLeanEngine(string userCode) { SecurityContextHolder.Set(securityMgr.GetUser(userCode)); leanEngineMgr.RunLeanEngine(); } [WebMethod] public void RunJIT_EX(string userCode) { SecurityContextHolder.Set(securityMgr.GetUser(userCode)); leanEngineMgr.RunJIT_EX(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Wee.Common.Contracts { public interface IMenuService { Dictionary<IMenuCategory, List<IMenuItem>> RegisteredMenus { get; } void RegisterMenu(int categoryOrder, string categoryName, IMenuItem menu); void RegisterMenu(IMenuCategory category, IMenuItem menu); Dictionary<string, List<IMenuItem>> BuildMenu(); } }
using UnityEngine; using System.Collections; public class ConeOfViewRenderer : MonoBehaviour { private Mesh viewMesh; public Material viewMaterial; public int numTriangles = 20; bool initialized = false; // Use this for initialization void Start () { EnsureInitialized (); } void EnsureInitialized() { if (initialized) { return; } initialized = true; viewMesh = new Mesh (); gameObject.AddComponent<MeshRenderer>(); gameObject.AddComponent<MeshFilter>().mesh=viewMesh; MeshRenderer renderer = gameObject.GetComponent<MeshRenderer> (); renderer.material = viewMaterial; } public void CreateMeshForAngleRange (float minAngle, float maxAngle) { EnsureInitialized (); Utilities.MakeFanWithAngleRange (ref viewMesh, minAngle, maxAngle, TweakableParams.swipeRadius, numTriangles); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using CRUD_Razor_2_1.Models; using Xunit; namespace CRUD_Tests.Models { public class BookTest { [Fact] public void BookModel_Instantiates() { string book = "Harry Potter"; string author = "JK Rowling"; string isbn = "123234345"; Book bookInst = new Book() { Name = book, Author = author, ISBN = isbn }; Assert.Matches(bookInst.Name, book); Assert.Matches(bookInst.Author, author); Assert.Matches(bookInst.ISBN, isbn); // Check no validation errors Assert.False(ValidateModel(bookInst).Count > 0); } [Fact] public void BookModel_RequiresNameField() { string author = "JK Rowling"; string isbn = "123234345"; Book bookInst = new Book() { Author = author, ISBN = isbn }; var invalidFields = ValidateModel(bookInst); // Validation errors should return Assert.True(invalidFields.Count > 0); } [Fact] public void BookModel_DoesNotRequireOtherFields() { string book = "Harry Potter"; Book bookInst = new Book() { Name = book }; var invalidFields = ValidateModel(bookInst); Assert.False(invalidFields.Count > 0); } // Validation Helper private IList<ValidationResult> ValidateModel(object model) { var validationResults = new List<ValidationResult>(); var ctx = new ValidationContext(model, null, null); Validator.TryValidateObject(model, ctx, validationResults, true); if (model is IValidatableObject) (model as IValidatableObject).Validate(ctx); return validationResults; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.IO; namespace BluetoothDevicesLocator { class Program { static void Main(string[] args) { System.Diagnostics.Process.Start(@"..\..\BlueToothApp.BAT"); Console.ReadLine(); } } }
using Cake.Core; using Cake.Core.IO; using Cake.Core.Tooling; namespace Cake.Markdown_Pdf { public class MarkdownPdfRunnerSettings : ToolSettings { internal void Evaluate(ProcessArgumentBuilder args) { if (Help) args.Append(MarkdownPdfOptions.Help); if (Version) args.Append($"{MarkdownPdfOptions.Version}"); if (!string.IsNullOrWhiteSpace(PhantomPath)) args.Append($"{MarkdownPdfOptions.PhantomPath} {PhantomPath}"); if (!string.IsNullOrWhiteSpace(RunningsPath)) args.Append($"{MarkdownPdfOptions.RunningsPath} {RunningsPath}"); if (!string.IsNullOrWhiteSpace(CssPath)) args.Append($"{MarkdownPdfOptions.CssPath} {CssPath}"); if (!string.IsNullOrWhiteSpace(HighlightCssPath)) args.Append($"{MarkdownPdfOptions.HighlightCssPath} {HighlightCssPath}"); if (!string.IsNullOrWhiteSpace(RemarkableOptions)) args.Append($"{MarkdownPdfOptions.RemarkableOptions} {RemarkableOptions}"); if (PaperFormat != MarkdownPdfPaperFormat.None) args.Append($"{MarkdownPdfOptions.PaperFormat} {PaperFormat}"); if (Orientation != MarkdownPdfOrientation.None) args.Append($"{MarkdownPdfOptions.Orientation} {Orientation}"); if (!string.IsNullOrWhiteSpace(PaperBorder)) args.Append($"{MarkdownPdfOptions.PaperBorder} {PaperBorder}"); if (RenderDelay > 0) args.Append($"{MarkdownPdfOptions.RenderDelay} {RenderDelay}"); if (LoadTimeout > 0) args.Append($"{MarkdownPdfOptions.LoadTimeout} {LoadTimeout}"); if (!string.IsNullOrWhiteSpace(OutFilePath)) args.Append($"{MarkdownPdfOptions.OutFilePath} {OutFilePath}"); if (!string.IsNullOrWhiteSpace(FilePath)) args.Append(FilePath); } public bool Help { get; set; } public bool Version { get; set; } public string FilePath { get; set; } public string PhantomPath { get; set; } public string RunningsPath { get; set; } public string CssPath { get; set; } public string HighlightCssPath { get; set; } public string RemarkableOptions { get; set; } public MarkdownPdfPaperFormat PaperFormat { get; set; } public MarkdownPdfOrientation Orientation { get; set; } public string PaperBorder { get; set; } public int RenderDelay { get; set; } public int LoadTimeout { get; set; } public string OutFilePath { get; set; } } }
using Autofac; using EmberKernel.Services.EventBus; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Text; namespace EmberMemory.Components.Collector { public class CollectorManagerBuilder { public ContainerBuilder Builder { get; } internal const string RegisteredTypesType = "RegisteredTypes"; private readonly HashSet<Type> RegisteredCollector = new HashSet<Type>(); public CollectorManagerBuilder(ContainerBuilder builder) { this.Builder = builder; Builder .RegisterInstance(RegisteredCollector) .Named<HashSet<Type>>(RegisteredTypesType); } public CollectorManagerBuilder Collect<TCollector>() where TCollector : ICollector { this.Builder.RegisterType<TCollector>().As<TCollector>(); RegisteredCollector.Add(typeof(TCollector)); return this; } } }
using Android.Graphics; using Android.Graphics.Drawables; using Android.OS; using AsNum.XFControls; using AsNum.XFControls.Droid; using System.ComponentModel; using System.Linq; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(Border), typeof(BorderRender))] namespace AsNum.XFControls.Droid { public class BorderRender : VisualElementRenderer<Border> { private bool IsDisposed = false; private GradientDrawable Dab; private InsetDrawable InsetDab; private Path ClipPath; protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); this.UpdateBackground(this); } protected override void OnElementChanged(ElementChangedEventArgs<Border> e) { base.OnElementChanged(e); this.UpdateBackground(this); } protected override void DispatchDraw(Canvas canvas) { if (Element.IsClippedToBorder) { canvas.Save(SaveFlags.Clip); this.SetClipPath(canvas); base.DispatchDraw(canvas); canvas.Restore(); } else { base.DispatchDraw(canvas); } } //protected override void UpdateBackgroundColor() { // //base.UpdateBackgroundColor(); //} private void UpdateBackground(Android.Views.View view) { var border = this.Element; var stroke = border.StrokeThickness; var corner = border.CornerRadius; var padding = border.Padding; var context = view.Context; if (this.Dab == null) { this.Dab = new GradientDrawable(); this.Dab.SetShape(ShapeType.Rectangle); } var maxWidth = (int)context.ToPixels(Max(stroke)); if (maxWidth > 0) { this.Dab.SetStroke(maxWidth, border.Stroke.ToAndroid(), 0, 0); } if ((int)Build.VERSION.SdkInt < 21) { //Android 4.4 SetCornerRadii »áºÚһƬ this.Dab.SetCornerRadius(context.ToPixels(Max(corner))); } else { var ctl = context.ToPixels(corner.TopLeft); var ctr = context.ToPixels(corner.TopRight); var cbr = context.ToPixels(corner.BottomRight); var cbl = context.ToPixels(corner.BottomLeft); var corners = new float[] { ctl, ctl, ctr, ctr, cbr, cbr, cbl, cbl }; this.Dab.SetCornerRadii(corners); } this.Dab.SetColor(border.BackgroundColor.ToAndroid()); var left = -(int)(maxWidth - context.ToPixels(stroke.Left)); var top = -(int)(maxWidth - context.ToPixels(stroke.Top)); var right = -(int)(maxWidth - context.ToPixels(stroke.Right)); var bottom = -(int)(maxWidth - context.ToPixels(stroke.Bottom)); if (this.InsetDab == null) { this.InsetDab = new InsetDrawable(this.Dab, left, top, right, bottom); } view.Background = InsetDab; view.SetPadding( (int)context.ToPixels(stroke.Left + padding.Left), (int)context.ToPixels(stroke.Top + padding.Top), (int)context.ToPixels(stroke.Right + padding.Right), (int)context.ToPixels(stroke.Bottom + padding.Bottom)); } private double Max(Thickness t) { return new double[] { t.Left, t.Top, t.Right, t.Bottom }.Max(); } private double Max(CornerRadius t) { return new double[] { t.TopLeft, t.TopRight, t.BottomLeft, t.BottomRight }.Max(); } private void SetClipPath(Canvas canvas) { var br = this; this.ClipPath = new Path(); var corner = br.Element.CornerRadius; var tl = (float)corner.TopLeft; var tr = (float)corner.TopRight; var bbr = (float)corner.BottomRight; var bl = (float)corner.BottomLeft; //Array of 8 values, 4 pairs of [X,Y] radii float[] radius = new float[] { tl, tl, tr, tr, bbr, bbr, bl, bl }; int w = (int)br.Width; int h = (int)br.Height; this.ClipPath.AddRoundRect(new RectF( br.ViewGroup.PaddingLeft, br.ViewGroup.PaddingTop, w - br.ViewGroup.PaddingRight, h - br.ViewGroup.PaddingBottom), radius, Path.Direction.Cw); canvas.ClipPath(this.ClipPath); } protected override void Dispose(bool disposing) { if (disposing && !this.IsDisposed) { this.IsDisposed = true; if (this.Dab != null) { this.Dab.Dispose(); this.Dab = null; } if (this.InsetDab != null) { this.InsetDab.Dispose(); this.InsetDab = null; } if (this.ClipPath != null) { this.ClipPath.Dispose(); this.ClipPath = null; } } base.Dispose(disposing); } } }
using System.Collections.Generic; using System.Web.Http; using FaunaNet.Subscription; namespace AccountManager.Controllers.Api { /// <summary> /// Information about subscriptions. It includes limits, configurations, etc /// It does not include any financial information like prices or costs. /// </summary> [Route("api/subscription")] public class SubscriptionController : ApiController { /// <summary> /// Enterprise subscription data for a specific user order. /// </summary> /// <param name="orderId">Order Id</param> /// <returns>Subscription of the enterprise</returns> public Subscription Get(int orderId) { var s = new Subscription { ServerAndDesktopLicenses = 2, TotalFemaleLimit = 1000, Databases = new List<FarmDatabase> { new FarmDatabase{Id=5,Females = 400, Groups = 100, Name="Farm A"}, new FarmDatabase{Id=6,Females = 600, Groups = 23, Name="Farm B"} }, }; return s; } // PUT: api/Default/5 public void Put(int orderId, [FromBody]Subscription value) { } } }
using System.Collections.Generic; namespace Train.TicketServices.Interfaces.Repositories { public interface ITicketRepository { IEnumerable<string> GetStations(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CityInfo.API.Entities; using CityInfo.API.Models; namespace CityInfo.API { public static class CityInfoExtensions { public static void EnsureSeedDataForContext(this CityInfoContext context) { if (context.Cities.Any()) { return; } var cities = new List<City>() { new City() { Name = "Ankara", Description = "bla", PointsOfInterest=new List<PointOfInterest>() { new PointOfInterest() { Name="Yenimahalle", Description="bla" }, new PointOfInterest() { Name="Batıkent", Description="bla" } } }, new City() { Name = "Malatya", Description = "bla bla", PointsOfInterest=new List<PointOfInterest>() { new PointOfInterest() { Name="Battalgazi", Description="bla bla" }, new PointOfInterest() { Name="Darende", Description="bla bla" } } }, new City() { Name = "Mersin", Description = "bla bla bla", PointsOfInterest=new List<PointOfInterest>() { new PointOfInterest() { Name="Anamur", Description="bla bla bla" }, new PointOfInterest() { Name="Akdeniz", Description="bla bla bla" } } } }; context.Cities.AddRange(cities); context.SaveChanges(); } } }
using System; using System.Collections.Generic; using RimWorld; using Verse; using Random = UnityEngine.Random; namespace Kyrun.Reunion { class GameComponent : Verse.GameComponent { public static List<Pawn> ListAllyAvailable = new List<Pawn>(); public static List<string> ListAllySpawned = new List<string>(); // Variables public static int NextEventTick = 0; // Trait-related public const string TRAIT_DEF_CHARACTER = "ReunionCharacter"; public const string TRAIT_ALLY = "Ally"; public const int TRAIT_DEGREE_ALLY = 3; public static TraitDef TraitDef_Character { get; private set; } public static Trait Trait_Ally { get; private set; } // Save key const string SAVE_NEXT_EVENT_TICK = "Reunion_NextEventTick"; const string SAVE_KEY_LIST_ALLY_SPAWNED = "Reunion_AllySpawned"; const string SAVE_KEY_LIST_ALLY_AVAILABLE = "Reunion_AllyAvailable"; public static Settings Settings { get; private set; } public GameComponent(Game game) : base() { Settings = LoadedModManager.GetMod<Mod>().GetSettings<Settings>(); } public static void PreInit() { TraitDef_Character = TraitDef.Named(TRAIT_DEF_CHARACTER); Trait_Ally = new Trait(TraitDef_Character, TRAIT_DEGREE_ALLY, true); } public static void InitOnNewGame() { ListAllyAvailable.Clear(); ListAllySpawned.Clear(); #if TESTING /* */ const int TOTAL = 5; for (int i = 0; i < TOTAL; ++i) { var pgr = new PawnGenerationRequest(PawnKindDef.Named("SpaceRefugee"), null, PawnGenerationContext.NonPlayer, -1, true); var newPawn = PawnGenerator.GeneratePawn(pgr); newPawn.Name = NameTriple.FromString("ReunionPawn" + i); ListAllyAvailable.Add(newPawn); } /* */ #endif } public static void InitOnLoad() { if (ListAllyAvailable == null) ListAllyAvailable = new List<Pawn>(); if (ListAllySpawned == null) ListAllySpawned = new List<string>(); var diff = NextEventTick - Find.TickManager.TicksGame; if (NextEventTick <= 0) Util.Msg("No events scheduled"); else Util.PrintNextEventTimeRemaining(); } public static void PostInit() { // Check player's existing colonists with traits and put into list for saving. // This means that "Prepare Carefully" starting colonists with the Ally trait will be "found" again // if they are somehow lost to the World pool. RegisterReunionPawnsFromList(PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Alive_OfPlayerFaction, (pawn) => { if (!ListAllySpawned.Contains(pawn.GetUniqueLoadID())) { ListAllySpawned.Add(pawn.GetUniqueLoadID()); Util.Msg("Saving Player's pawn with Ally trait to Reunion list: " + pawn.Name); } }, TRAIT_ALLY); // Check all World Pawns with trait and put into list for saving. Also remove trait. // Use case 1: New game with "Prepare Carefully" creates World pawns. // Use case 2: Backwards compatibility for loading existing saves from older version of this mod. RegisterReunionPawnsFromList(Current.Game.World.worldPawns.AllPawnsAlive, (pawn) => { if (!ListAllyAvailable.Contains(pawn)) { ListAllyAvailable.Add(pawn); Util.Msg("Saving World pawn with Ally trait to Reunion list: " + pawn.Name); } Find.WorldPawns.RemovePawn(pawn); }, TRAIT_ALLY); if (Prefs.DevMode) Util.PrintAllyList(); TryScheduleNextEvent(); } static void RegisterReunionPawnsFromList(List<Pawn> listPawns, Action<Pawn> doToPawn, string traitKey) { foreach (var pawn in listPawns) { if (pawn == null || pawn.story == null || pawn.story.traits == null) continue; var traits = pawn.story.traits; if (traits.HasTrait(TraitDef_Character)) { var trait = traits.GetTrait(TraitDef_Character); if (trait != null && trait.Label.Contains(traitKey)) { doToPawn?.Invoke(pawn); TryRemoveTrait(pawn); } } } } public static Pawn GetRandomAllyForSpawning() { var randomIndex = Random.Range(0, ListAllyAvailable.Count); var pawn = ListAllyAvailable[randomIndex]; SetupSpawn(pawn, ListAllyAvailable, ListAllySpawned); return pawn; } public static bool TryRemoveTrait(Pawn pawn) { var trait = pawn.story.traits.GetTrait(TraitDef_Character); if (trait != null) { pawn.story.traits.allTraits.Remove(trait); return true; } return false; } public static void SetupSpawn(Pawn pawn, List<Pawn> listSource, List<string> listDest) { listSource.Remove(pawn); listDest.Add(pawn.GetUniqueLoadID()); pawn.SetFactionDirect(null); // remove faction, if any pawn.workSettings.EnableAndInitializeIfNotAlreadyInitialized(); // prevent some error which I don't yet understand } public static void ReturnToAvailable(Pawn pawn, List<string> listJoined, List<Pawn> listAvailable) { listJoined.Remove(pawn.GetUniqueLoadID()); listAvailable.Add(pawn); Util.Msg(pawn.Name + " was lost by the player and made available for Reunion to spawn again."); TryScheduleNextEvent(); } public static void FlagNextEventReadyForScheduling() { NextEventTick = 0; } public static void TryScheduleNextEvent(bool forceReschedule = false) { if (ListAllyAvailable.Count == 0) { Util.Msg("No available Reunion pawns, Reunion events will not fire from now on."); return; } if (!forceReschedule && NextEventTick == -1) { // another event is currently happening if (Prefs.DevMode) { Util.Msg("Tried to schedule an event but is in the middle of an event."); } return; } if (!forceReschedule && NextEventTick > Find.TickManager.TicksGame) { // another event is already scheduled if (Prefs.DevMode) { Util.Msg("Tried to schedule an event but another event has already been scheduled."); } return; } var min = Settings.minDaysBetweenEvents * GenDate.TicksPerDay; if (min == 0) min = 1; // limit it to at least 1 tick var max = Settings.maxDaysBetweenEvents * GenDate.TicksPerDay; NextEventTick = Find.TickManager.TicksGame + Random.Range(min, max); #if TESTING NextEventTick = Find.TickManager.TicksGame + 1000; #endif Util.PrintNextEventTimeRemaining(); } public static void DecideAndDoEvent() { NextEventTick = -1; // stop next event from happening if (ListAllyAvailable.Count <= 0) // no more allies { Util.Warn("No available Ally pawns, event should not have fired!"); return; } if (Current.Game.AnyPlayerHomeMap == null) // no map { Util.Msg("Player does not have any home map, event timer restarted."); TryScheduleNextEvent(); return; } List<Settings.Event> listAllowedEvents = new List<Settings.Event>(); // special case where there's only one colonist if (PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Alive_OfPlayerFaction.Count <= 1) { if (Settings.EventAllow[Settings.Event.WandererJoins]) listAllowedEvents.Add(Settings.Event.WandererJoins); if (Settings.EventAllow[Settings.Event.RefugeePodCrash]) listAllowedEvents.Add(Settings.Event.RefugeePodCrash); } // add the rest of the allowed events if more than 1 Colonist if (PawnsFinder.AllMapsCaravansAndTravelingTransportPods_Alive_OfPlayerFaction.Count > 1) { foreach (Settings.Event eventType in Enum.GetValues(typeof(Settings.Event))) { if (Settings.EventAllow[eventType] && !listAllowedEvents.Contains(eventType)) { listAllowedEvents.Add(eventType); } } } if (listAllowedEvents.Count > 0) { var eventToDo = listAllowedEvents[Random.Range(0, listAllowedEvents.Count)]; Settings.EventAction[eventToDo].Invoke(); } else { Util.Warn("No suitable event found, event timer restarted."); TryScheduleNextEvent(true); } } public override void ExposeData() { Scribe_Values.Look(ref NextEventTick, SAVE_NEXT_EVENT_TICK, 0); Scribe_Collections.Look(ref ListAllyAvailable, SAVE_KEY_LIST_ALLY_AVAILABLE, LookMode.Deep); Scribe_Collections.Look(ref ListAllySpawned, SAVE_KEY_LIST_ALLY_SPAWNED, LookMode.Value); base.ExposeData(); } } }
using Crossroads.Web.Common.MinistryPlatform; using log4net; using MinistryPlatform.Translation.Models.DTO; using MinistryPlatform.Translation.Repositories.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace MinistryPlatform.Translation.Repositories { public class EventRepository : IEventRepository { private readonly IApiUserRepository _apiUserRepository; private readonly IMinistryPlatformRestRepository _ministryPlatformRestRepository; private readonly List<string> _eventGroupsColumns; private readonly List<string> _eventColumns; protected readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const string ResetEventStoredProcedureName = "api_crds_ResetEcheckEvent"; private const string ImportEventStoredProcedureName = "api_crds_ImportEcheckEvent"; private const string nonEventTemplatesQueryString = "([Template]=0 OR [Template] IS NULL)"; public EventRepository(IApiUserRepository apiUserRepository, IMinistryPlatformRestRepository ministryPlatformRestRepository) { _apiUserRepository = apiUserRepository; _ministryPlatformRestRepository = ministryPlatformRestRepository; _eventGroupsColumns = new List<string> { "Event_Groups.[Event_Group_ID]", "Event_ID_Table.[Event_ID]", "Group_ID_Table.[Group_ID]", "Event_Room_ID_Table.[Event_Room_ID]", "Event_Room_ID_Table_Room_ID_Table.[Room_ID]", "Event_Room_ID_Table.[Capacity]", "Event_Room_ID_Table.[Label]", "Event_Room_ID_Table.[Allow_Checkin]", "Event_Room_ID_Table.[Volunteers]", "[dbo].crds_getEventParticipantStatusCount(Event_ID_Table.[Event_ID], Event_Room_ID_Table_Room_ID_Table.[Room_ID], 3) AS Signed_In", "[dbo].crds_getEventParticipantStatusCount(Event_ID_Table.[Event_ID], Event_Room_ID_Table_Room_ID_Table.[Room_ID], 4) AS Checked_In" }; _eventColumns = new List<string> { "Event_ID", "Parent_Event_ID", "Template", "Event_Title", "Program_ID", "Primary_Contact", "Event_Start_Date", "Event_End_Date", "[Early_Check-in_Period]", "[Late_Check-in_Period]", "Event_Type_ID_Table.Event_Type", "Events.Event_Type_ID", "Congregation_ID_Table.Congregation_Name", "Events.Congregation_ID", "Congregation_ID_Table.Location_ID", "[Allow_Check-in]" }; } /// <summary> /// The end date parameter is automatically cast to the end of the day for that date /// </summary> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <param name="site"></param> /// <param name="includeSubevents"></param> /// <returns></returns> public List<MpEventDto> GetEvents(DateTime startDate, DateTime endDate, int site, bool? includeSubevents = false, List<int> eventTypeIds = null, bool excludeIds = true) { var apiUserToken = _apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn"); var startTimeString = startDate.ToString(); // make sure end time is end of day var endTimeString = new DateTime(endDate.Year, endDate.Month, endDate.Day, 23, 59, 59).ToString(); var queryString = $"[Allow_Check-in]=1 AND [Cancelled]=0 AND [Event_Start_Date] >= '{startTimeString}' AND [Event_Start_Date] <= '{endTimeString}' AND Events.[Congregation_ID] = {site}"; // only pull non-template events queryString = $"{queryString} AND {nonEventTemplatesQueryString}"; if (excludeIds == true && eventTypeIds != null) { queryString += $" AND Events.[Event_Type_ID] NOT IN ({string.Join(",", eventTypeIds)})"; } else if (eventTypeIds != null) { queryString += $" AND Events.[Event_Type_ID] IN ({string.Join(",", eventTypeIds)})"; } if (includeSubevents != true) { // do not include subevents queryString = $"{queryString} AND [Parent_Event_ID] IS NULL"; } var events = _ministryPlatformRestRepository.UsingAuthenticationToken(apiUserToken) .Search<MpEventDto>(queryString, _eventColumns); if (!events.Any()) { // log query when no events are returned for debugging purposes Logger.Info($"No events found at {DateTime.Now} for query: ${queryString}"); } return events; } public List<MpEventDto> GetEventTemplates(int site) { var apiUserToken = _apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn"); var queryString = $"[Allow_Check-in]=1 AND [Cancelled]=0 AND [Template]=1 AND Events.[Congregation_ID] = {site}"; return _ministryPlatformRestRepository.UsingAuthenticationToken(apiUserToken) .Search<MpEventDto>(queryString, _eventColumns); } public MpEventDto GetEventById(int eventId) { var apiUserToken = _apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn"); return _ministryPlatformRestRepository.UsingAuthenticationToken(apiUserToken) .Get<MpEventDto>(eventId, _eventColumns); } public MpEventDto CreateSubEvent(MpEventDto mpEventDto) { var token = _apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn"); return _ministryPlatformRestRepository.UsingAuthenticationToken(token).Create(mpEventDto, _eventColumns); } public MpEventDto UpdateEvent(MpEventDto mpEventDto) { var token = _apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn"); return _ministryPlatformRestRepository.UsingAuthenticationToken(token).Update(mpEventDto, _eventColumns); } public List<MpEventGroupDto> GetEventGroupsForEvent(int eventId) { var eventIds = new List<int> { eventId }; return GetEventGroupsForEvent(eventIds); } public List<MpEventGroupDto> GetEventGroupsForEventByGroupTypeId(int eventId, int groupTypeId) { return _ministryPlatformRestRepository.UsingAuthenticationToken(_apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn")) .Search<MpEventGroupDto>($"Event_Groups.Event_ID = {eventId} AND Group_ID_Table.[Group_Type_ID] = {groupTypeId}", _eventGroupsColumns); } public List<MpEventGroupDto> GetEventGroupsForEvent(List<int> eventIds) { return _ministryPlatformRestRepository.UsingAuthenticationToken(_apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn")) .Search<MpEventGroupDto>($"Event_Groups.Event_ID IN ({string.Join(",", eventIds)})", _eventGroupsColumns); } public List<MpEventGroupDto> GetEventGroupsForEventRoom(int eventId, int roomId) { return _ministryPlatformRestRepository.UsingAuthenticationToken(_apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn")) .Search<MpEventGroupDto>($"Event_Groups.Event_ID = {eventId} AND Event_Room_ID_Table_Room_ID_Table.Room_ID = {roomId}", _eventGroupsColumns); } public void DeleteEventGroups(string authenticationToken, IEnumerable<int> eventGroupIds) { var token = authenticationToken ?? _apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn"); _ministryPlatformRestRepository.UsingAuthenticationToken(token).Delete<MpEventGroupDto>(eventGroupIds); } public List<MpEventGroupDto> CreateEventGroups(string authenticationToken, List<MpEventGroupDto> eventGroups) { var token = authenticationToken ?? _apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn"); return _ministryPlatformRestRepository.UsingAuthenticationToken(token).Create(eventGroups, _eventGroupsColumns); } public void ResetEventSetup(int eventId) { var authenticationToken = _apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn"); _ministryPlatformRestRepository.UsingAuthenticationToken(authenticationToken) .PostStoredProc(ResetEventStoredProcedureName, new Dictionary<string, object> { { "@EventId", eventId } }); } public void ImportEventSetup(int destinationEventId, int sourceEventId) { var authenticationToken = _apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn"); _ministryPlatformRestRepository.UsingAuthenticationToken(authenticationToken) .PostStoredProc(ImportEventStoredProcedureName, new Dictionary<string, object> { { "@DestinationEventId", destinationEventId }, { "@SourceEventId", sourceEventId } }); } public List<MpEventDto> GetEventAndCheckinSubevents(int eventId, bool includeTemplates = false) { var token = _apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn"); var query = $"(Events.Event_ID = {eventId} OR Events.Parent_Event_ID = {eventId}) AND Events.[Allow_Check-in] = 1"; if (includeTemplates == false) { query = $"{query} AND {nonEventTemplatesQueryString}"; } return _ministryPlatformRestRepository.UsingAuthenticationToken(token) .Search<MpEventDto>(query, _eventColumns); } public MpEventDto GetSubeventByParentEventId(int serviceEventId, int eventTypeId) { var token = _apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn"); var events = _ministryPlatformRestRepository.UsingAuthenticationToken(token) .Search<MpEventDto>($"Events.Parent_Event_ID = {serviceEventId} AND Events.[Event_Type_ID] = {eventTypeId}", _eventColumns); return events.FirstOrDefault(); } public List<MpEventDto> GetSubeventsForEvents(List<int> eventIds, int? eventTypeId) { var apiUserToken = _apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn"); var queryString = eventIds.Aggregate("(", (current, id) => current + (id + ",")); queryString = queryString.TrimEnd(','); queryString += ")"; // search on the event type if it's not a null param var typeQueryString = (eventTypeId != null) ? " AND Events.[Event_Type_ID] = " + eventTypeId : ""; return _ministryPlatformRestRepository.UsingAuthenticationToken(apiUserToken) .Search<MpEventDto>($"Events.[Parent_Event_ID] IN {queryString} AND Events.[Allow_Check-in] = 1 {typeQueryString}", _eventColumns); } public List<MpEventGroupDto> GetEventGroupsByGroupIdAndEventIds(int groupId, List<int> eventIds) { return _ministryPlatformRestRepository.UsingAuthenticationToken(_apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn")) .Search<MpEventGroupDto>($"Event_Groups.Group_ID ={groupId} AND Event_Groups.Event_ID IN ({string.Join(",", eventIds)})", _eventGroupsColumns); } public List<MpCapacityDto> GetCapacitiesForEvent(int eventId) { var parms = new Dictionary<string, object> { {"EventID", eventId}, }; var result = _ministryPlatformRestRepository.UsingAuthenticationToken(_apiUserRepository.GetApiClientToken("CRDS.Service.SignCheckIn")).GetFromStoredProc<MpCapacityDto>("api_crds_Capacity_App_Data", parms); return result[0]; } } }
namespace TPMDocs.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("spravoh.Справочник гофропродукции")] public partial class Справочник_гофропродукции { [Key] [Column("Код комплекта")] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Код_комплекта { get; set; } [Column("Код комплектующего")] public int? Код_комплектующего { get; set; } [Column("Вид гофропродукции")] public int? Вид_гофропродукции { get; set; } [Column("Код ГОСТа")] public int? Код_ГОСТа { get; set; } [StringLength(100)] public string ГОСТ_чертеж { get; set; } public short? Длина { get; set; } public short? Ширина { get; set; } public short? Высота { get; set; } public double? Площадь { get; set; } [Column("Группа сложности")] public double? Группа_сложности { get; set; } [Column("Вид оборудования")] public int? Вид_оборудования { get; set; } [Column("Тип оборудования")] public int? Тип_оборудования { get; set; } public int? КартаНомер { get; set; } [StringLength(6)] public string КодОтрасли { get; set; } public string ДопИнф { get; set; } [StringLength(2)] public string КодГруппа { get; set; } [StringLength(4)] public string КодНазнач { get; set; } public bool? InUse { get; set; } public DateTime? CrDate { get; set; } [StringLength(50)] public string CrPC { get; set; } [Column(TypeName = "timestamp")] [MaxLength(8)] [Timestamp] public byte[] SSMA_TimeStamp { get; set; } } }
using UnityEngine; using System.Collections; /* GameObject ob = Instantiate (GameHostPrefab, new Vector3 (0, 0, 0), Quaternion.identity) as GameObject; ob.GetComponent<GameHost>().Initialize(5); ob = Instantiate (GameHostPrefab, new Vector3 (0, 0, 0), Quaternion.identity) as GameObject; ob.GetComponent<GameHost>().Initialize(9); ob.transform.position = new Vector3 (20, 20, 0); ob.transform.localScale = new Vector3(2.5f, 2.5f, 1f); */ public class JoinLobbyMenue : MonoBehaviour { GuiHelper guiHelper; NetworkHelper networkHelper; //For "low-level" network tasks Vector2 hostListScrollPosition; private string directConnectLobbyName = ""; /*~~ STATUS ~~*/ /*~~ ---- ~~*/ void Start () { guiHelper = GameObject.Find ("Menue").GetComponent<GuiHelper>(); if (guiHelper == null) { throw new MissingComponentException ("Unable to find GuiHelper."); } //Initialize the network helper for hardcore lowlevel-commands (not really, but sounds better) networkHelper = (NetworkHelper)gameObject.AddComponent(typeof(NetworkHelper)); networkHelper.SetNetworkingErrorHandler (NetworkingError); networkHelper.SetOnDisconnectedHandler (OnDisconnected); StartCoroutine("PollHostList"); } //Coroutine, to poll the hostList every x seconds private IEnumerator PollHostList(){ for(;;){ networkHelper.RefreshHostList(); yield return new WaitForSeconds(Settings.LOBBY_REFRESH_RATE); //wait some time, before we poll again } } void OnGUI () { guiHelper.Prepare(); //int fontSize = (int)GuiHelper.X(GuiHelper.Y(45, 10, 15), 2.5f, 5f); int fontSize = (int)GuiHelper.Y(GuiHelper.X(45, 2.5f, 5f), 1.8f, 10f); GUI.skin.label.fontSize = fontSize/2; GUI.skin.textField.fontSize = fontSize/2; GUI.skin.button.fontSize = fontSize/2; guiHelper.TitleText ("Join Game"); if (guiHelper.ExitButton("Back") || Input.GetKeyDown(KeyCode.Escape)) { networkHelper.Disconnect(); ApplicationModel.EnterMainMenue(); } HostData[] hostList = networkHelper.GetHostList(); GUI.Label(new Rect(guiHelper.GetWindowPadding(), guiHelper.GetTitleSpace(), GuiHelper.XtoPx(30), guiHelper.SmallElemHeight), "Direct connect:"); directConnectLobbyName = GUI.TextField(new Rect(GuiHelper.XtoPx(30), guiHelper.GetTitleSpace()-4, GuiHelper.XtoPx(25), guiHelper.SmallElemHeight+8), directConnectLobbyName, 6).ToUpper(); HostData direct = null; if (hostList != null && directConnectLobbyName.Length >= 6) { for (int i = 0; i < hostList.Length; i++) { if (hostList[i].gameName == directConnectLobbyName || hostList[i].gameName == "priv_" + directConnectLobbyName) { direct = hostList[i]; break; } } if (direct != null && GUI.Button(new Rect(GuiHelper.XtoPx(60), guiHelper.GetTitleSpace(), GuiHelper.XtoPx(20), guiHelper.SmallElemHeight), "Join")) { ApplicationModel.EnterLobbyAsClient(direct); } } GUI.skin.label.fontSize *= 2; GUI.skin.button.fontSize *= 2; GUILayout.BeginArea(new Rect(0, guiHelper.GetTitleSpace() + guiHelper.SmallElemHeight + guiHelper.BigElemSpacing, Screen.width, Screen.height - guiHelper.GetTitleSpace() - guiHelper.GetExitButtonSpace() - guiHelper.SmallElemHeight - guiHelper.BigElemSpacing)); int onlinePlayers = 0; if (hostList != null){ hostListScrollPosition = GUILayout.BeginScrollView(hostListScrollPosition); for (int i = 0; i < hostList.Length; i++) { onlinePlayers += hostList[i].connectedPlayers; if (hostList[i].gameName.StartsWith("priv_")){ continue; } GUILayout.BeginHorizontal(); GUILayout.Space(GuiHelper.XtoPx(20)); GUILayout.Label(hostList[i].comment.Substring(1)); GUILayout.EndHorizontal(); Rect region = GUILayoutUtility.GetLastRect(); Rect smallRegion = new Rect(region); smallRegion.width /= 3.5f; GUI.Label(smallRegion, hostList[i].gameName); smallRegion.width = region.width / 5; smallRegion.x = region.x + smallRegion.width * 1.35f; GUI.Label(smallRegion, hostList[i].connectedPlayers + "/" + hostList[i].playerLimit); smallRegion.x = region.x + smallRegion.width * 4f; if (GUI.Button(smallRegion, "Join")){ ApplicationModel.EnterLobbyAsClient(hostList[i]); } GUILayout.Space(10); } GUILayout.EndScrollView(); } GUILayout.EndArea(); GUI.skin.label.fontSize /= 2; GUI.Label(new Rect((Screen.width - GuiHelper.XtoPx(50)) / 2, Screen.height - guiHelper.SmallElemHeight - GuiHelper.YtoPx(4), GuiHelper.XtoPx(50), guiHelper.SmallElemHeight), onlinePlayers + " players ingame"); GUI.skin.label.fontSize *= 2; } //Is called, when a networking issue appears void NetworkingError(string errorMessage){ networkHelper.Disconnect(); ApplicationModel.EnterMainMenue("Networking Error \n"+errorMessage); } void OnDisconnected(string message){ ApplicationModel.EnterMainMenue(message); } }
using System.Linq; using System.Linq.Expressions; using SpatialEye.Framework.Client; using SpatialEye.Framework.Features.Expressions; using SpatialEye.Framework.Parameters; using Lite.Resources.Localization; using glf = SpatialEye.Framework.Features.Expressions.GeoLinqExpressionFactory; using SpatialEye.Framework.Features; using System.Collections.Generic; namespace Lite { /// <summary> /// A viewModel that handles setting up a New Client Query using an Expression Builder. /// </summary> internal class LiteNewUserQueryViewModelBuilderMode : LiteNewUserQueryViewModelMode { #region Static Behavior /// <summary> /// A flag indicating whether the like should be interpreted case independent /// </summary> public static bool LikeIsCaseIndependent = true; #endregion #region Fields /// <summary> /// The parameter definitions /// </summary> private ParameterDefinitionCollection _parameters; #endregion #region Constructor /// <summary> /// Constructs the lot using /// </summary> internal LiteNewUserQueryViewModelBuilderMode() : base(ApplicationResources.QueryViaExpressionBuilder) { IsEnabled = true; this.ExpressionBuilder = new ExpressionBuilderViewModel(); } #endregion #region API /// <summary> /// The Expression Builder to set up an expression with /// </summary> internal ExpressionBuilderViewModel ExpressionBuilder { get; private set; } /// <summary> /// The table descriptor has changed /// </summary> internal override void OnTableDescriptorChanged() { this.ExpressionBuilder.Setup(TableDescriptor); } /// <summary> /// Returns the expression for the new query /// </summary> /// <returns></returns> internal override Expression NewQueryExpression() { var expression = ExpressionBuilder.Expression; // Set up default parameters _parameters = new ParameterDefinitionCollection(); if (expression != null) { expression = expression.GeoLinqParameterizeFields(out _parameters, includeSystemParameters: true, includeLookupsForEnumeratedFields: true); if (LikeIsCaseIndependent) { // Use a visitor to replace the individual bits of the expression expression = expression.GeoLinqReplace((e) => { if (e != null && e.GeoLinqNodeType() == GeoLinqExpressionType.TextLike) { // This is a: // <Field>.Like(<datum>) expression // morph this expression into // <Field>.Like(<datum>, true) expression to make case independent var function = (GeoLinqFunctionExpression)e; return glf.Text.Like(function.ParameterExpressions[0], function.ParameterExpressions[1], true); } // Default visitor behavior - returning the expression itself return e; }); } } return expression; } /// <summary> /// The parameter definitions that are required for running the query /// </summary> /// <returns></returns> internal override ParameterDefinitionCollection NewQueryParameterDefinitions() { return _parameters; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Factorial { class Factorial { static void Main(string[] args) { Console.WriteLine(ItterativeFactorial(5)); Console.ReadKey(); } public static int RecursiveFactorial(int num) { if(num == 0) { return 1; } return num * RecursiveFactorial(num - 1); } public static int ItterativeFactorial(int num) { int fact = 1; for(int i = 1; i <=num; i++) { fact *= i; } return fact; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Update the in game text to display the amount of time the current game has lasted for. /// </summary> public class DisplayTime : DisplayText { /// <summary> /// As long as the game isn't over (meaning not gamestate 6). /// Show the current time since the start of this run. /// </summary> protected override void Update () { if (GameMaster.state != 6) { //totalTime is the time as of the last reset. Taking this away from Time.fixedTime allows us to get the time for the current attempt. textObject.text = ("Time: " + (Time.fixedTime - GameMaster.totalTime).ToString("F2")); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml.Serialization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Microsoft.VisualBasic.FileIO; using Test.Data; using Test.Models; using Test.ViewModels; namespace Test.Controllers { public class PaymentsController : Controller { private readonly DataContext _context; private readonly CultureInfo cultureinfoTH = new CultureInfo("th-TH"); private readonly CultureInfo cultureinfoEN = new CultureInfo("en-US"); public PaymentsController(DataContext context) { _context = context; } [HttpGet] public async Task<IActionResult> GetPayments(string currency, string start, string end, string statusCode) { var paymentsDb = _context.Payment.AsQueryable(); if (!string.IsNullOrEmpty(currency)) { paymentsDb = paymentsDb.Where(x => x.CurrencyCode == currency); } if (!string.IsNullOrEmpty(start) && !string.IsNullOrEmpty(end)) { paymentsDb = paymentsDb.Where(x => x.TransactionDate >= DateTime.Parse(start) && x.TransactionDate <= DateTime.Parse(end)); } var payments = await paymentsDb.ToListAsync(); List<PaymentsToReturn> Payments = new List<PaymentsToReturn>(); foreach(var item in paymentsDb) { PaymentsToReturn Payment = new PaymentsToReturn { TransactionId = item.TransactionId, Payment = $"{item.Amonnt} {item.CurrencyCode}", Status = item.Status }; Payments.Add(Payment); } IEnumerable<PaymentsToReturn> result = Payments; if (!string.IsNullOrEmpty(statusCode)) { result = Payments.Where(x => x.StatusCode == statusCode); } return Ok(result); } [HttpGet] public async Task<IActionResult> GetCurrency() { var currency = await _context.Payment.Select(x => x.CurrencyCode).Distinct().ToListAsync(); return Ok(currency); } [HttpPost] public async Task<IActionResult> Uploadfile() { var file = Request.Form.Files[0]; if (file.Length > 0) { if (file.FileName.EndsWith(".csv")) { try { using (var sreader = new StreamReader(file.OpenReadStream())) { while (!sreader.EndOfStream) { string[] rows = sreader.ReadLine().Split(','); Payment payment = new Payment { TransactionId = rows[0].ToString().Replace("\"", string.Empty), Amonnt = decimal.Parse(rows[1].ToString().Replace("\"", string.Empty)), CurrencyCode = rows[2].ToString().Replace("\"", string.Empty), TransactionDate = DateTime.Parse(rows[3].ToString().Replace("\"", string.Empty), cultureinfoTH), Status = rows[4].ToString().Replace("\"", string.Empty), }; _context.Add(payment); } await _context.SaveChangesAsync(); } } catch (Exception ex) { return BadRequest(ex.Message); } } else if (file.FileName.EndsWith(".xml")) { try { var mySerializer = new XmlSerializer(typeof(Transactions)); var myObject = new Transactions(); using (var reader = new StreamReader(file.OpenReadStream())) { myObject = (Transactions)mySerializer.Deserialize(reader); } foreach(var item in myObject.Transaction) { Payment payment = new Payment { TransactionId = item.Id, Amonnt = decimal.Parse(item.PaymentDetails.Amount), CurrencyCode = item.PaymentDetails.CurrencyCode, TransactionDate = DateTime.Parse(item.TransactionDate), Status = item.Status, }; _context.Add(payment); } await _context.SaveChangesAsync(); } catch(Exception ex) { return BadRequest(ex.Message); } } else { return BadRequest("Unknown format"); } } return Ok(); } } }
using System; namespace ProgrammingCourseWork.Display { public static class SellsDisplay { public static void Display() { Console.Clear(); SingletonRestoraunt.Instance.PrintSells(); Console.ReadKey(); } } }
using System.Collections; using System.Collections.Generic; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine; using UnityEngine.SceneManagement; public class LaunchController : MonoBehaviour { string StaticIPString; string SaveFileName; //public InputField FilaNameInput; public Text IpInput_field; public Text FileName_field; public Text SessionLength_field; bool HostComputer = true; string SessionLengthString; float SessionLength; // Use this for initialization void Start () { Cursor.visible = true; //Loading parameters from the playerrefs. if (PlayerPrefs.HasKey ("SaveFileNameStored")) { SaveFileName = PlayerPrefs.GetString ("SaveFileNameStored"); GameObject.Find ("FileNamePlaceholderText").gameObject.GetComponent<Text> ().text = SaveFileName; Debug.Log("FileNameStored: " + SaveFileName); //if (SingleUserSession) { Debug.Log( "single user session"); //} else { Debug.Log ("multi user session"); } if (PlayerPrefs.HasKey ("StaticIPStored")) { StaticIPString = PlayerPrefs.GetString ("StaticIPStored"); GameObject.Find ("IP_PlaceholderText").gameObject.GetComponent<Text> ().text = StaticIPString; Debug.Log("StaticIPStored: " + StaticIPString); //if (SingleUserSession) { Debug.Log( "single user session"); //} else { Debug.Log ("multi user session"); } if (PlayerPrefs.HasKey ("Param_HostOrNot")) { //HostComputer = PlayerPrefsX.GetBool ("Param_HostOrNot"); } else { bool b = HostComputer; PlayerPrefsX.SetBool ("Param_HostOrNot", b); } GameObject.Find("HostClientToggle").GetComponent<Toggle>().isOn = HostComputer; if (PlayerPrefs.HasKey ("SessionLengthStored")) { float b = PlayerPrefs.GetFloat("SessionLengthStored"); SessionLengthString = b.ToString(); GameObject.Find ("SessionLengthPlaceholderText").gameObject.GetComponent<Text> ().text = SessionLengthString; Debug.Log("SessionLengthStored: " + SessionLengthString); //if (SingleUserSession) { Debug.Log( "single user session"); //} else { Debug.Log ("multi user session"); } } // Update is called once per frame void FixedUpdate () { /* if (Input.GetKeyDown(KeyCode.Alpha1)) { SceneManager.LoadScene (0); } if (Input.GetKeyDown(KeyCode.Alpha2)) { SceneManager.LoadScene (1); } if (Input.GetKeyDown(KeyCode.Alpha3)) { SceneManager.LoadScene (2); } if (Input.GetKeyDown (KeyCode.Alpha4)) { SceneManager.LoadScene (3);}*/ } public void LaunchSession0(){ if (PlayerPrefs.HasKey ("Param_SessionID")) { PlayerPrefs.SetString ("Param_SessionID", "Session0"); } else { string b = "Session0"; PlayerPrefs.SetString ("Param_SessionID", b); } Debug.Log ("Session0 parameters loaded - long baseline"); SceneManager.LoadScene (1); } public void LaunchSession1(){ SetSession1 (); SceneManager.LoadScene (1); } public void LaunchSession1Questions(){ SetSession1 (); SceneManager.LoadScene (3); } public void LaunchSession1Meditation(){ SetSession1 (); SceneManager.LoadScene (2); } // session 1, one user, no adaptations. public void SetSession1(){ if (PlayerPrefs.HasKey ("Param_SingleUserSession")) { PlayerPrefsX.SetBool ("Param_SingleUserSession", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_SingleUserSession", b); } if (PlayerPrefs.HasKey ("Param_RespSelf")) { PlayerPrefsX.SetBool ("Param_RespSelf", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_RespSelf", b); } if (PlayerPrefs.HasKey ("Param_EegSelf")) { PlayerPrefsX.SetBool ("Param_EegSelf", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_EegSelf", b); } if (PlayerPrefs.HasKey ("Param_RespOther")) { PlayerPrefsX.SetBool ("Param_RespOther", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_RespOther", b); } if (PlayerPrefs.HasKey ("Param_EegOther")) { PlayerPrefsX.SetBool ("Param_EegOther", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_EegOther", b); } if (PlayerPrefs.HasKey ("Param_SessionID")) { PlayerPrefs.SetString ("Param_SessionID", "Session1"); } else { string b = "Session1"; PlayerPrefs.SetString ("Param_SessionID", b); } Debug.Log ("Session1 parameters loaded - one user, no adaptations"); } public void LaunchSession2(){ SetSession2 (); SceneManager.LoadScene (1); } public void LaunchSession2Questions(){ SetSession2 (); SceneManager.LoadScene (3); } public void LaunchSession2Meditation(){ SetSession2 (); SceneManager.LoadScene (2); } // session 2, one user, respiration only public void SetSession2(){ if (PlayerPrefs.HasKey ("Param_SingleUserSession")) { PlayerPrefsX.SetBool ("Param_SingleUserSession", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_SingleUserSession", b); } if (PlayerPrefs.HasKey ("Param_RespSelf")) { PlayerPrefsX.SetBool ("Param_RespSelf", true); } else { bool b = true; PlayerPrefsX.SetBool ("Param_RespSelf", b); } if (PlayerPrefs.HasKey ("Param_EegSelf")) { PlayerPrefsX.SetBool ("Param_EegSelf", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_EegSelf", b); } if (PlayerPrefs.HasKey ("Param_RespOther")) { PlayerPrefsX.SetBool ("Param_RespOther", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_RespOther", b); } if (PlayerPrefs.HasKey ("Param_EegOther")) { PlayerPrefsX.SetBool ("Param_EegOther", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_EegOther", b); } if (PlayerPrefs.HasKey ("Param_SessionID")) { PlayerPrefs.SetString ("Param_SessionID", "Session2"); } else { string b = "Session2"; PlayerPrefs.SetString ("Param_SessionID", b); } Debug.Log ("Session2 parameters loaded - one user, respiration only"); } public void LaunchSession3(){ SetSession3 (); SceneManager.LoadScene (1); } public void LaunchSession3Questions(){ SetSession3 (); SceneManager.LoadScene (3); } public void LaunchSession3Meditation(){ SetSession3 (); SceneManager.LoadScene (2); } // session 3, one user, eeg only public void SetSession3(){ if (PlayerPrefs.HasKey ("Param_SingleUserSession")) { PlayerPrefsX.SetBool ("Param_SingleUserSession", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_SingleUserSession", b); } if (PlayerPrefs.HasKey ("Param_RespSelf")) { PlayerPrefsX.SetBool ("Param_RespSelf", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_RespSelf", b); } if (PlayerPrefs.HasKey ("Param_EegSelf")) { PlayerPrefsX.SetBool ("Param_EegSelf", true); } else { bool b = false; PlayerPrefsX.SetBool ("Param_EegSelf", b); } if (PlayerPrefs.HasKey ("Param_RespOther")) { PlayerPrefsX.SetBool ("Param_RespOther", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_RespOther", b); } if (PlayerPrefs.HasKey ("Param_EegOther")) { PlayerPrefsX.SetBool ("Param_EegOther", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_EegOther", b); } if (PlayerPrefs.HasKey ("Param_SessionID")) { PlayerPrefs.SetString ("Param_SessionID", "Session3"); } else { string b = "Session3"; PlayerPrefs.SetString ("Param_SessionID", b); } Debug.Log ("Session3 parameters loaded - one user, eeg only"); } public void LaunchSession4(){ SetSession4 (); SceneManager.LoadScene (1); } public void LaunchSession4Questions(){ SetSession4 (); SceneManager.LoadScene (3); } public void LaunchSession4Meditation(){ SetSession4 (); SceneManager.LoadScene (2); } // session 4 - two users, no adaptations. public void SetSession4(){ if (PlayerPrefs.HasKey ("Param_SingleUserSession")) { PlayerPrefsX.SetBool ("Param_SingleUserSession", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_SingleUserSession", b); } if (PlayerPrefs.HasKey ("Param_RespSelf")) { PlayerPrefsX.SetBool ("Param_RespSelf", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_RespSelf", b); } if (PlayerPrefs.HasKey ("Param_EegSelf")) { PlayerPrefsX.SetBool ("Param_EegSelf", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_EegSelf", b); } if (PlayerPrefs.HasKey ("Param_RespOther")) { PlayerPrefsX.SetBool ("Param_RespOther", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_RespOther", b); } if (PlayerPrefs.HasKey ("Param_EegOther")) { PlayerPrefsX.SetBool ("Param_EegOther", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_EegOther", b); } if (PlayerPrefs.HasKey ("Param_SessionID")) { PlayerPrefs.SetString ("Param_SessionID", "Session4"); } else { string b = "Session4"; PlayerPrefs.SetString ("Param_SessionID", b); } Debug.Log ("Sessio4 parameters loaded - two users, no adaptations."); } public void LaunchSession5(){ SetSession5 (); SceneManager.LoadScene (1); } public void LaunchSession5Questions(){ SetSession5 (); SceneManager.LoadScene (3); } public void LaunchSession5Meditation(){ SetSession5 (); SceneManager.LoadScene (2); } // session 5, two users, respiration only public void SetSession5(){ if (PlayerPrefs.HasKey ("Param_SingleUserSession")) { PlayerPrefsX.SetBool ("Param_SingleUserSession", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_SingleUserSession", b); } if (PlayerPrefs.HasKey ("Param_RespSelf")) { PlayerPrefsX.SetBool ("Param_RespSelf", true); } else { bool b = true; PlayerPrefsX.SetBool ("Param_RespSelf", b); } if (PlayerPrefs.HasKey ("Param_EegSelf")) { PlayerPrefsX.SetBool ("Param_EegSelf", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_EegSelf", b); } if (PlayerPrefs.HasKey ("Param_RespOther")) { PlayerPrefsX.SetBool ("Param_RespOther", true); } else { bool b = true; PlayerPrefsX.SetBool ("Param_RespOther", b); } if (PlayerPrefs.HasKey ("Param_EegOther")) { PlayerPrefsX.SetBool ("Param_EegOther", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_EegOther", b); } if (PlayerPrefs.HasKey ("Param_SessionID")) { PlayerPrefs.SetString ("Param_SessionID", "Session5"); } else { string b = "Session5"; PlayerPrefs.SetString ("Param_SessionID", b); } Debug.Log ("Session5 parameters loaded - two users, respiration only"); } public void LaunchSession6(){ SetSession6 (); SceneManager.LoadScene (1); } public void LaunchSession6Questions(){ SetSession6 (); SceneManager.LoadScene (3); } public void LaunchSession6Meditation(){ SetSession6 (); SceneManager.LoadScene (2); } //session 6 - two users, eeg only public void SetSession6(){ if (PlayerPrefs.HasKey ("Param_SingleUserSession")) { PlayerPrefsX.SetBool ("Param_SingleUserSession", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_SingleUserSession", b); } if (PlayerPrefs.HasKey ("Param_RespSelf")) { PlayerPrefsX.SetBool ("Param_RespSelf", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_RespSelf", b); } if (PlayerPrefs.HasKey ("Param_EegSelf")) { PlayerPrefsX.SetBool ("Param_EegSelf", true); } else { bool b = true; PlayerPrefsX.SetBool ("Param_EegSelf", b); } if (PlayerPrefs.HasKey ("Param_RespOther")) { PlayerPrefsX.SetBool ("Param_RespOther", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_RespOther", b); } if (PlayerPrefs.HasKey ("Param_EegOther")) { PlayerPrefsX.SetBool ("Param_EegOther", true); } else { bool b = true; PlayerPrefsX.SetBool ("Param_EegOther", b); } if (PlayerPrefs.HasKey ("Param_SessionID")) { PlayerPrefs.SetString ("Param_SessionID", "Session6"); } else { string b = "Session6"; PlayerPrefs.SetString ("Param_SessionID", b); } Debug.Log ("Session6 parameters loaded -two users, eeg only"); } public void LaunchSession7(){ SetSession7 (); SceneManager.LoadScene (1); } public void LaunchSession7Questions(){ SetSession7 (); SceneManager.LoadScene (3); } public void LaunchSession7Meditation(){ SetSession7 (); SceneManager.LoadScene (2); } //session 7 - solo, both resp and eeg public void SetSession7(){ if (PlayerPrefs.HasKey ("Param_SingleUserSession")) { PlayerPrefsX.SetBool ("Param_SingleUserSession", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_SingleUserSession", b); } if (PlayerPrefs.HasKey ("Param_RespSelf")) { PlayerPrefsX.SetBool ("Param_RespSelf", true); } else { bool b = true; PlayerPrefsX.SetBool ("Param_RespSelf", b); } if (PlayerPrefs.HasKey ("Param_EegSelf")) { PlayerPrefsX.SetBool ("Param_EegSelf", true); } else { bool b = true; PlayerPrefsX.SetBool ("Param_EegSelf", b); } if (PlayerPrefs.HasKey ("Param_RespOther")) { PlayerPrefsX.SetBool ("Param_RespOther", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_RespOther", b); } if (PlayerPrefs.HasKey ("Param_EegOther")) { PlayerPrefsX.SetBool ("Param_EegOther", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_EegOther", b); } if (PlayerPrefs.HasKey ("Param_SessionID")) { PlayerPrefs.SetString ("Param_SessionID", "Session7"); } else { string b = "Session7"; PlayerPrefs.SetString ("Param_SessionID", b); } Debug.Log ("Session7 parameters loaded -one user, eeg & respiration"); } // session 8 - dyad, bot resp and eeg public void LaunchSession8(){ SetSession8 (); SceneManager.LoadScene (1); } public void LaunchSession8Questions(){ SetSession8 (); SceneManager.LoadScene (3); } public void LaunchSession8Meditation(){ SetSession8 (); SceneManager.LoadScene (2); } public void SetSession8(){ if (PlayerPrefs.HasKey ("Param_SingleUserSession")) { PlayerPrefsX.SetBool ("Param_SingleUserSession", false); } else { bool b = false; PlayerPrefsX.SetBool ("Param_SingleUserSession", b); } if (PlayerPrefs.HasKey ("Param_RespSelf")) { PlayerPrefsX.SetBool ("Param_RespSelf", true); } else { bool b = true; PlayerPrefsX.SetBool ("Param_RespSelf", b); } if (PlayerPrefs.HasKey ("Param_EegSelf")) { PlayerPrefsX.SetBool ("Param_EegSelf", true); } else { bool b = true; PlayerPrefsX.SetBool ("Param_EegSelf", b); } if (PlayerPrefs.HasKey ("Param_RespOther")) { PlayerPrefsX.SetBool ("Param_RespOther", true); } else { bool b = true; PlayerPrefsX.SetBool ("Param_RespOther", b); } if (PlayerPrefs.HasKey ("Param_EegOther")) { PlayerPrefsX.SetBool ("Param_EegOther", true); } else { bool b = true; PlayerPrefsX.SetBool ("Param_EegOther", b); } if (PlayerPrefs.HasKey ("Param_SessionID")) { PlayerPrefs.SetString ("Param_SessionID", "Session8"); } else { string b = "Session8"; PlayerPrefs.SetString ("Param_SessionID", b); } Debug.Log ("Session8 parameters loaded - two users, eeg & respiration"); } public void SetStaticIP(string value7) { StaticIPString = IpInput_field.text.ToString(); if (PlayerPrefs.HasKey ("StaticIPStored")) { PlayerPrefs.SetString ("StaticIPStored", StaticIPString); Debug.Log ("IP saved as: " + StaticIPString); } else { string arvo1 = "127.0.0.1"; PlayerPrefs.SetString ("StaticIPStored", arvo1); PlayerPrefs.SetString ("StaticIPStored", StaticIPString); Debug.Log ("Static IP: " + StaticIPString); } } public void SetSaveFileName(string saveFieldInput) { SaveFileName = FileName_field.text.ToString(); if (PlayerPrefs.HasKey ("SaveFileNameStored")) { PlayerPrefs.SetString ("SaveFileNameStored", SaveFileName); Debug.Log ("Data file saved as: " + SaveFileName); } else { string arvo1 = "DynaEmpData001.txt"; PlayerPrefs.SetString ("SaveFileNameStored", arvo1); PlayerPrefs.SetString ("SaveFileNameStored", SaveFileName); Debug.Log ("Data file saved as: " + SaveFileName); } } public void SetHostComputer() { HostComputer = !HostComputer; Debug.Log("This computer is a host: "+ HostComputer); if (PlayerPrefs.HasKey ("Param_HostOrNot")) { PlayerPrefsX.SetBool ("Param_HostOrNot", HostComputer); } else { bool b = HostComputer; PlayerPrefsX.SetBool ("Param_HostOrNot", b); } } public void SetSessionLength(string value2) { SessionLengthString = SessionLength_field.text.ToString(); SessionLength = float.Parse(SessionLengthString); if (PlayerPrefs.HasKey ("SessionLengthStored")) { PlayerPrefs.SetFloat ("SessionLengthStored", SessionLength ); Debug.Log ("Session Length set to " + SessionLength); } else { float arvo = 600f; PlayerPrefs.SetFloat ("SessionLengthStored", arvo); PlayerPrefs.SetFloat ("SessionLengthStored", arvo); Debug.Log ("Session Length set to " + arvo); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Uintra.Features.Comments.Models; namespace Uintra.Features.Comments.Services { public interface ICommentsService { Task<CommentModel> GetAsync(Guid id); Task<IEnumerable<CommentModel>> GetManyAsync(Guid activityId); Task<int> GetCountAsync(Guid activityId); bool CanEdit(CommentModel comment, Guid editorId); bool CanDelete(CommentModel comment, Guid editorId); bool WasChanged(CommentModel comment); bool IsReply(CommentModel comment); Task<CommentModel> CreateAsync(CommentCreateDto dto); Task<CommentModel> UpdateAsync(CommentEditDto dto); Task DeleteAsync(Guid id); Task FillCommentsAsync(ICommentable entity); string GetCommentViewId(Guid commentId); Task<bool> IsExistsUserCommentAsync(Guid activityId, Guid userId); CommentModel Get(Guid id); IEnumerable<CommentModel> GetMany(Guid activityId); int GetCount(Guid activityId); CommentModel Create(CommentCreateDto dto); CommentModel Update(CommentEditDto dto); void Delete(Guid id); void FillComments(ICommentable entity); bool IsExistsUserComment(Guid activityId, Guid userId); } }
using JMusic.Helper; using SQLitePCL; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JMusic.Models { class TPlayList { public int Id { get; set; } public string Name { get; set; } public string Link { get; set; } public string Singer { get; set; } public bool Save() { var sqlConnection = SQLiteHelper.CreateInstance().SQLiteConnection; var sqlCommandString = "insert into Members (Name, Link, Singer) values (?,?,?)"; using (var stt = sqlConnection.Prepare(sqlCommandString)) { stt.Bind(1, this.Name); stt.Bind(2, this.Link); stt.Bind(3, this.Singer); var result = stt.Step(); return result == SQLiteResult.OK; } } public List<TPlayList> GetList() { List<TPlayList> list = new List<TPlayList>(); var sqlConnection = SQLiteHelper.CreateInstance().SQLiteConnection; var sqlCommandString = "select * from ?"; using (var stt = sqlConnection.Prepare(sqlCommandString)) { stt.Bind(1, Constants.SQLITE_TABLE_PLAY_LIST); while (SQLiteResult.ROW == stt.Step()) { var id = stt[0].ToString(); var name = (string)stt[1]; var link = (string)stt[2]; var singer = (string)stt["Singer"]; var playList = new TPlayList() { Id = Int32.Parse(id), Name = name, Link = link, Singer = singer }; list.Add(playList); } } return list; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; namespace TraceWizard.TwApp { public partial class ProgressWindow : Window, INotifyPropertyChanged { private IProgressOperation _operation; public ProgressWindow(IProgressOperation operation) { this._operation = operation; this._operation.ProgressChanged += new EventHandler(_operation_ProgressChanged); this._operation.ProgressTotalChanged += new EventHandler(_operation_TotalChanged); this._operation.Complete += new EventHandler(_operation_Complete); InitializeComponent(); this.Loaded += new RoutedEventHandler(ProgressWindow_Loaded); } void ProgressWindow_Loaded(object sender, RoutedEventArgs e) { this._operation.Start(); } void _operation_Complete(object sender, EventArgs e) { Close(); } void _operation_ProgressChanged(object sender, EventArgs e) { OnPropertyChanged("Current"); OnPropertyChanged("KeyCode"); } void _operation_TotalChanged(object sender, EventArgs e) { OnPropertyChanged("Total"); } private void CancelClick(object sender, RoutedEventArgs e) { this._operation.CancelAsync(); } public int Current { get { return this._operation.Current; } } public int Total { get { return this._operation.Total; } } public string KeyCode { get { return this._operation.KeyCode; } } protected void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; } }
namespace BettingSystem.Infrastructure.Common.Persistence { public interface IDbInitializer { void Initialize(); } }
using System; using System.Collections.Generic; using System.Text; namespace CommonLib { /// <summary> /// 随机数帮助类 /// </summary> public class RandomHelper { /// <summary> /// 获取指定长度的随机密码-由数字大小写字母组成 /// </summary> /// <param name="PasswordLen"></param> /// <returns></returns> public static string GetRndPassword(int PasswordLen) { //创建一个StringBuilder对象存储密码 StringBuilder sb = new StringBuilder(); //使用for循环把单个字符填充进StringBuilder对象里面变成PasswordLen位密码字符串 for (int i = 0; i < PasswordLen; i++) { Random random = new Random(); //随机选择里面其中的一种字符生成 switch (random.Next(3)) { case 0: //调用生成生成随机数字的方法 sb.Append(createNum()); break; case 1: //调用生成生成随机小写字母的方法 sb.Append(createSmallAbc()); break; case 2: //调用生成生成随机大写字母的方法 sb.Append(createBigAbc()); break; } } return sb.ToString(); } /// <summary> /// 获取指定长度的随机数字码-纯数字 /// </summary> /// <param name="PasswordLen"></param> /// <returns></returns> public static string GetRndNum(int PasswordLen) { //创建一个StringBuilder对象存储密码 StringBuilder sb = new StringBuilder(); for (int i = 0; i < PasswordLen; i++) { Random random = new Random(); //调用生成生成随机数字的方法 sb.Append(createNum()); } return sb.ToString(); } // <summary> /// 生成单个随机数字 /// </summary> public static int createNum() { Random random = new Random(); int num = random.Next(10); return num; } /// <summary> /// 生成单个大写随机字母 /// </summary> public static string createBigAbc() { //A-Z的 ASCII值为65-90 Random random = new Random(); int num = random.Next(65, 91); string abc = Convert.ToChar(num).ToString(); return abc; } /// <summary> /// 生成单个小写随机字母 /// </summary> public static string createSmallAbc() { //a-z的 ASCII值为97-122 Random random = new Random(); int num = random.Next(97, 123); string abc = Convert.ToChar(num).ToString(); return abc; } } }
using NBitcoin; using Stratis.Bitcoin.Base; using Stratis.Bitcoin.Consensus; using Stratis.Bitcoin.Features.BlockStore; using Stratis.Bitcoin.Features.Consensus; using Stratis.Bitcoin.Features.Consensus.CoinViews; using Stratis.Bitcoin.Features.Consensus.Interfaces; using Stratis.Bitcoin.Features.MemoryPool; using Stratis.Bitcoin.Features.Wallet; using Stratis.Bitcoin.Features.Wallet.Interfaces; using Stratis.Bitcoin.Interfaces; namespace Stratis.Bitcoin.IntegrationTests.Common { public static class FullNodeExtensions { public static WalletManager WalletManager(this FullNode fullNode) { return fullNode.NodeService<IWalletManager>() as WalletManager; } public static WalletTransactionHandler WalletTransactionHandler(this FullNode fullNode) { return fullNode.NodeService<IWalletTransactionHandler>() as WalletTransactionHandler; } public static IConsensusManager ConsensusManager(this FullNode fullNode) { return fullNode.NodeService<IConsensusManager>() as IConsensusManager; } public static ICoinView CoinView(this FullNode fullNode) { return fullNode.NodeService<ICoinView>(); } public static MempoolManager MempoolManager(this FullNode fullNode) { return fullNode.NodeService<MempoolManager>(); } public static IBlockStore BlockStore(this FullNode fullNode) { return fullNode.NodeService<IBlockStore>(); } public static ChainedHeader GetBlockStoreTip(this FullNode fullNode) { return fullNode.NodeService<IChainState>().BlockStoreTip; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03.SortStudents { public class Program { static void Main() { var studentsArr = new Student[] { new Student("Mihail","Malamov",21), new Student("Asen","Zaimov",33), new Student("Boayan","Popov",20), new Student("Zlatimir","Boyadziev",19), new Student("Dimiter","Stoimenov",22), new Student("Jeff","Ivanov",18), new Student("Stefan","Terziev",16), new Student("Jivko","Sirakov",26) }; studentsArr.CheckNames(); studentsArr.CheckAge(); studentsArr.SortByLinq(); studentsArr.SortByLambda(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MaterialSkin.Controls; namespace Parking_Lot_Project { public partial class addManagerForm : MaterialForm { public addManagerForm() { InitializeComponent(); } void loadData(string data) { textBox_id.Text = ""; textBox_id.Text = data; } private void materialButton_select_Click(object sender, EventArgs e) { interfaceWorkerForm frm = new interfaceWorkerForm(); frm.label_dark.Text = "s"; frm.sendToData = new interfaceWorkerForm.sendData(loadData); frm.Show(); } private void textBox_id_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { if (textBox_id.Text != "") { panel_infor.Visible = true; DataTable table = Worker.Instance.getEmp(textBox_id.Text); textBox_fullName.Text = table.Rows[0][1].ToString() + " " + table.Rows[0][2].ToString(); textBox_cmnd.Text = table.Rows[0][3].ToString(); textBox_bdate.Text = table.Rows[0][4].ToString(); textBox_phone.Text = table.Rows[0][5].ToString(); textBox_addr.Text = table.Rows[0][6].ToString(); textBox_gender.Text = table.Rows[0][7].ToString(); byte[] data = (byte[])table.Rows[0][8]; MemoryStream stream = new MemoryStream(data); pictureBox_image.Image = Image.FromStream(stream); } } } private void addManagerForm_Load(object sender, EventArgs e) { comboBox_work.DataSource = Work.Instance.getAllWork(); comboBox_work.DisplayMember = "NAME_WORK"; comboBox_work.ValueMember = "ID"; panel_infor.Visible = false; } private void materialButton_ok_Click(object sender, EventArgs e) { string id_user = textBox_id.Text; string id_work = comboBox_work.SelectedValue.ToString(); if (Manager.Instance.insertManager(id_user, id_work) == true) { string fullName = textBox_fullName.Text; string userName = "Admin" + textBox_id.Text; string pass = "1"; MemoryStream pic = new MemoryStream(); string access = "Manager"; pictureBox_image.Image.Save(pic, pictureBox_image.Image.RawFormat); if (Admin.Instance.insertAdmin(fullName, userName, pass, access, pic) == true) { MessageBox.Show("Thêm quản lý thành công\n Username: " + userName + "\nPassword: " + pass); } else MessageBox.Show("Tạo tài khoản không thành công"); } else { MessageBox.Show("Thêm quản lý thất bại"); } panel_infor.Visible = false; } } }
using Northwind; using Northwind.Model; using Microsoft.Spatial; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web.Http; using System.Web.OData; using Microsoft.OData.Core; using Microsoft.OData.Core.UriParser; using System.Net.Http; using System.Web.Http.Routing; using System.Web.OData.Extensions; using System.Web.OData.Routing; using System.Reflection; namespace Northwind.Controllers { public class NewsBaseODataController<TElement> : ODataController where TElement : class { protected NorthwindContext db = new NorthwindContext(); #region References [AcceptVerbs("POST", "PUT")] public async Task<IHttpActionResult> CreateRef([FromODataUri] int key, string navigationProperty, [FromBody] Uri link) { var target = await db.Set<TElement>().FindAsync(key); if (target == null) { return NotFound(); } var prop = target.GetType().GetProperty(navigationProperty); if (prop != null) { prop.SetValue(target, await GetValueUri(Request, link, prop)); } await db.SaveChangesAsync(); return StatusCode(HttpStatusCode.NoContent); } [AcceptVerbs("DELETE")] public async Task<IHttpActionResult> DeleteRef([FromODataUri] int key, string navigationProperty, [FromBody] Uri link) { var target = await db.Set<TElement>().FindAsync(key); if (target == null) { return NotFound(); } var prop = target.GetType().GetProperty(navigationProperty); if (prop != null) { var values = prop.GetValue(target); prop.SetValue(target, null); } await db.SaveChangesAsync(); return StatusCode(HttpStatusCode.NoContent); } public async Task<object> GetValueUri(HttpRequestMessage request, Uri uri, PropertyInfo prop) { if (uri == null) { throw new ArgumentNullException("uri"); } var urlHelper = request.GetUrlHelper() ?? new UrlHelper(request); string serviceRoot = urlHelper.CreateODataLink( request.ODataProperties().RouteName, request.ODataProperties().PathHandler, new List<ODataPathSegment>()); var odataPath = request.ODataProperties().PathHandler.Parse( request.ODataProperties().Model, serviceRoot, uri.LocalPath); var setSegment = odataPath.Segments.OfType<EntitySetPathSegment>().FirstOrDefault(); if (setSegment == null) { throw new InvalidOperationException("The link does not contain an entityset."); } var keySegment = odataPath.Segments.OfType<KeyValuePathSegment>().FirstOrDefault(); if (keySegment == null) { throw new InvalidOperationException("The link does not contain a key."); } var key = ODataUriUtils.ConvertFromUriLiteral(keySegment.Value, ODataVersion.V4); var element = await db.Set(prop.PropertyType).FindAsync(key); return element; } #endregion protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace _2_Worm_Ipsum { public class _2_Worm_Ipsum { public static void Main() { var pattern = new Regex(@"([A-Z].*?[.])"); var input = Console.ReadLine(); while (input != "Worm Ipsum") { var line = pattern.Matches(input); if (line.Count == 1) { var validLine = pattern.Match(input).Value.TrimEnd('.'); var words = validLine.Split().ToArray(); var newLine = ""; foreach (var word in words) { var newWord = ConvertLetters(word); newLine += newWord + " "; } Console.WriteLine($"{newLine.Trim()}."); } input = Console.ReadLine(); } } private static string ConvertLetters(string word) { var wordWithSigh = word; if (word.EndsWith(",")) { word = word.TrimEnd(','); } var count = 0; char letter = char.MinValue; var newWord = ""; for (int i = 0; i < word.Length; i++) { var symbol = word[i]; var currentCount = 0; for (int j = 0; j < word.Length; j++) { if (symbol == word[j]) { currentCount++; } } if (currentCount > count) { count = currentCount; letter = symbol; } } if (count > 1) { newWord = new string(letter, word.Length); if (wordWithSigh.EndsWith(",")) { newWord += ','; } } else { newWord = word; if (wordWithSigh.EndsWith(",")) { newWord += ','; } } return newWord; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Labb4 { class Car { string brand; byte gears; string colour; string type; public string Brand { get { return brand; } set { if (value.Length > 4) brand = value; } } public byte Gears { get { return gears; } set { if (value > 0 && value < 10) gears = value; } } public string Colour { get { return colour; } set { if (value.Length > 2) colour = value; } } public string Type { get { return type; } set { if (value.ToLower() == "kombi" || value.ToLower() == "kupe") type = value.ToLower(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Windows.Forms; using TY.SPIMS.Client.Approval; using TY.SPIMS.Client.Helper; using TY.SPIMS.Controllers; using TY.SPIMS.Entities; using TY.SPIMS.POCOs; using TY.SPIMS.Utilities; using TY.SPIMS.Client.Helper.CodeGenerator; using TY.SPIMS.Client.Helper.Export; using TY.SPIMS.Controllers.Interfaces; namespace TY.SPIMS.Client.Returns { public partial class AddSalesReturnForm : InputDetailsForm { private readonly ISaleController saleController; private readonly ISalesReturnController salesReturnController; private readonly ICustomerController customerController; public int ReturnId { get; set; } #region Props private int QtyLimit = 0; //for storing the total qty of an invoice item #endregion #region Event public event SalesReturnUpdatedEventHandler SalesReturnUpdated; protected void OnSalesReturnUpdated(EventArgs e) { SalesReturnUpdatedEventHandler handler = SalesReturnUpdated; if (handler != null) { handler(this, e); } } #endregion BackgroundWorker worker = new BackgroundWorker(); BackgroundWorker exportWorker = new BackgroundWorker(); public AddSalesReturnForm() { this.customerController = IOC.Container.GetInstance<CustomerController>(); this.saleController = IOC.Container.GetInstance<SaleController>(); this.salesReturnController = IOC.Container.GetInstance<SalesReturnController>(); InitializeComponent(); this.AutoValidate = AutoValidate.Disable; worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); exportWorker.DoWork += new DoWorkEventHandler(exportWorker_DoWork); exportWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(exportWorker_RunWorkerCompleted); } void exportWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { ToggleButtons(true); LoadImage.Visible = false; ClientHelper.ShowSuccessMessage("Export complete."); } void exportWorker_DoWork(object sender, DoWorkEventArgs e) { try { SalesReturnExportObject exportObject = (SalesReturnExportObject)e.Argument; IExportStrategy strategy = new SalesReturnExportStrategy(exportObject); var exporter = new ReportExporter(strategy); exporter.ExportReport(); } catch (Exception ex) { ClientHelper.LogException(ex); ClientHelper.ShowErrorMessage("An error occurred while exporting. Please try again."); } } #region Worker void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (ReturnId == 0) ClientHelper.ShowSuccessMessage(string.Format("Memo number {0} successfully added.", MemoTextbox.Text)); else ClientHelper.ShowSuccessMessage(string.Format("Memo number {0} successfully updated.", MemoTextbox.Text)); PrepareForm(); if (SalesReturnUpdated != null) SalesReturnUpdated(new object(), new EventArgs()); ToggleButtons(true); LoadImage.Visible = false; } void worker_DoWork(object sender, DoWorkEventArgs e) { if (e.Argument != null) { SalesReturnColumnModel model = (SalesReturnColumnModel)e.Argument; if (model.Id == 0) this.salesReturnController.InsertSalesReturn(model); else this.salesReturnController.UpdateSalesReturn(model); } } #endregion #region Load private void AddSalesReturnForm_Load(object sender, EventArgs e) { LoadCustomerDropdown(); PrepareForm(); } private void PrepareForm() { if (ReturnId != 0) { LoadSalesReturnDetails(); MemoTextbox.ReadOnly = true; CustomerDropdown.Enabled = false; } else { ClearAll(); LoadMemoNumber(); MemoTextbox.ReadOnly = false; CustomerDropdown.Enabled = true; } CheckIfEditAllowed(); } private void LoadMemoNumber() { var generator = new CodeGenerator(new SalesReturnCodeGenerator()); string memoNumber = generator.GenerateCode(); MemoTextbox.Text = memoNumber; } private void CheckIfEditAllowed() { //CustomerCredit c = CustomerCreditController.Instance.FetchCustomerCreditByReference(MemoTextbox.Text); bool editAllowed = true; //if (c != null) //{ // if (c.Credited.Value) // editAllowed = false; //} if (!editAllowed) { SaveButton.Visible = false; ClearButton.Visible = false; AddDetailsPanel.Visible = false; ErrorPanel.Visible = true; } else { SaveButton.Visible = true; ClearButton.Visible = true; AddDetailsPanel.Visible = true; ErrorPanel.Visible = false; } } private void CustomerDropdown_SelectedIndexChanged(object sender, EventArgs e) { ClearList(); LoadInvoiceNumbers(); } private void ClearList() { list.Clear(); salesReturnDetailModelBindingSource.DataSource = null; } public void LoadSalesReturnDetails() { SalesReturn sReturn = this.salesReturnController.FetchSalesReturnById(ReturnId); if (sReturn != null) { MemoTextbox.Text = sReturn.MemoNumber; ReturnDatePicker.Value = sReturn.ReturnDate.HasValue ? sReturn.ReturnDate.Value : DateTime.Today; CustomerDropdown.SelectedValue = sReturn.CustomerId; RemarksTextbox.Text = sReturn.Remarks; list = this.salesReturnController.FetchSalesReturnDetails(ReturnId).ToList(); if (list.Any()) { BindDetails(); ComputeTotalCredit(); } } else PrepareForm(); } private void LoadInvoiceNumbers() { if (CustomerDropdown.SelectedIndex != -1) { int customerId = (int)CustomerDropdown.SelectedValue; saleDisplayModelBindingSource.DataSource = this.saleController.FetchAllInvoiceNumbersByCustomer(customerId); InvoiceDropdown.SelectedIndex = -1; } else saleDisplayModelBindingSource.DataSource = null; } private void LoadCustomerDropdown() { customerDisplayModelBindingSource.DataSource = this.customerController.FetchAllCustomers(); CustomerDropdown.SelectedIndex = -1; } List<SalesDetailViewModel> saleDetails = null; private void InvoiceDropdown_SelectedIndexChanged(object sender, EventArgs e) { saleDetails = null; if (InvoiceDropdown.SelectedIndex != -1) { string invNumber = InvoiceDropdown.SelectedItem.ToString(); saleDetails = this.saleController.FetchSaleDetailsPerInvoice(invNumber); } salesDetailViewModelBindingSource.DataSource = saleDetails; PartNumberDropdown.SelectedIndex = -1; ClearItem(); } private decimal _oldUnitPrice; private void PartNumberDropdown_SelectedIndexChanged(object sender, EventArgs e) { if (PartNumberDropdown.SelectedIndex != -1 && saleDetails != null) { _oldUnitPrice = 0m; int id = (int)PartNumberDropdown.SelectedValue; SalesDetailViewModel details = saleDetails.FirstOrDefault(a => a.AutoPartDetailId == id); if (details != null) { //Get Previously returned value of this invoice number int customerId = (int)CustomerDropdown.SelectedValue; string invNumber = InvoiceDropdown.SelectedItem.ToString(); int qtyReturned = this.salesReturnController.FetchQuantityReturned(customerId, invNumber, id, ReturnId); //Get quantities in grid int qtyInGrid = 0; if (list.Any()) { qtyInGrid = list.Where(a => a.PartDetailId == id && a.InvoiceNumber == invNumber).Sum(a => a.Quantity); } AutoPartTextbox.Text = details.AutoPartName; //Qty that can be returned int qtyLimit = details.Quantity - qtyReturned - qtyInGrid; QtyTextbox.Text = qtyLimit.ToString(); QtyLimit = qtyLimit; _oldUnitPrice = details.DiscountedPrice; UnitPriceTextbox.Text = _oldUnitPrice.ToString("N2"); } QtyTextbox.Focus(); } } #endregion #region Details #region Add List<SalesReturnDetailModel> list = new List<SalesReturnDetailModel>(); private void AddButton_Click(object sender, EventArgs e) { if (InvoiceDropdown.SelectedIndex == -1 || PartNumberDropdown.SelectedIndex == -1 || string.IsNullOrWhiteSpace(UnitPriceTextbox.Text)) return; else if (QtyTextbox.Text == "0") { ClientHelper.ShowErrorMessage("No quantity to return."); return; } else if (int.Parse(QtyTextbox.Text) > QtyLimit) { QtyTextbox.Text = QtyLimit.ToString(); ClientHelper.ShowErrorMessage("Return quantity is greater than original quantity."); QtyTextbox.Focus(); return; } else if (!UserInfo.IsAdmin && !string.IsNullOrWhiteSpace(UnitPriceTextbox.Text) && _oldUnitPrice != UnitPriceTextbox.Text.ToDecimal()) { ApprovalForm f = new ApprovalForm(); f.ApprovalDone += new ApprovalDoneEventHandler(f_ApprovalDone); f.Show(); } else { AddSalesReturn(); } } private void AddSalesReturn() { ComputeTotalDetailAmount(); SalesReturnDetailModel model = new SalesReturnDetailModel() { AutoPart = AutoPartTextbox.Text, PartDetailId = (int)PartNumberDropdown.SelectedValue, Id = 0, InvoiceNumber = InvoiceDropdown.SelectedItem.ToString(), PartNumber = PartNumberDropdown.Text, Quantity = int.Parse(QtyTextbox.Text), UnitPrice = UnitPriceTextbox.Text.ToDecimal(), TotalAmount = TotalAmountTextbox.Text.ToDecimal() }; list.Insert(0, model); BindDetails(); ClearDetails(); ComputeTotalCredit(); InvoiceDropdown.Focus(); } void f_ApprovalDone(object sender, ApprovalEventArgs e) { if (e.ApproverId == 0) ClientHelper.ShowErrorMessage("Invalid approver."); else AddSalesReturn(); } private void BindDetails() { salesReturnDetailModelBindingSource.DataSource = null; salesReturnDetailModelBindingSource.DataSource = list; } #endregion #region Clear private void ClearDetailButton_Click(object sender, EventArgs e) { ClearDetails(); } private void ClearDetails() { InvoiceDropdown.SelectedIndex = -1; InvoiceDropdown.ComboBox.SelectedIndex = -1; PartNumberDropdown.SelectedIndex = -1; PartNumberDropdown.ComboBox.SelectedIndex = -1; ClearItem(); } //Clears inputable item in details private void ClearItem() { AutoPartTextbox.Clear(); QtyTextbox.Text = "0"; QtyLimit = 0; UnitPriceTextbox.Text = "0.00"; TotalAmountTextbox.Text = "0.00"; } #endregion #region Compute private void QtyTextbox_Leave(object sender, EventArgs e) { ComputeTotalDetailAmount(); } private void UnitPriceTextbox_Leave(object sender, EventArgs e) { ComputeTotalDetailAmount(); } private void ComputeTotalDetailAmount() { int qty = int.Parse(QtyTextbox.Text); decimal price = decimal.Parse(UnitPriceTextbox.Text); decimal total = qty * price; TotalAmountTextbox.Text = total.ToString("N2"); } private void ComputeTotalCredit() { decimal total = list.Sum(a => a.TotalAmount); TotalTextbox.Text = total.ToString("N2"); } #endregion #region Delete private void dataGridView1_UserDeletedRow(object sender, DataGridViewRowEventArgs e) { ComputeTotalCredit(); ClearDetails(); } #endregion #endregion #region Save int? approver = null; private void SaveButton_Click(object sender, EventArgs e) { if (!this.ValidateChildren()) ClientHelper.ShowRequiredMessage("Memo number, Return Items"); else if (hasDuplicate) ClientHelper.ShowDuplicateMessage("Memo number"); else { SaveReturn(); } } private void SaveReturn() { ToggleButtons(false); LoadImage.Visible = true; SalesReturnColumnModel model = new SalesReturnColumnModel() { Id = ReturnId, MemoNumber = MemoTextbox.Text, CustomerId = (int)CustomerDropdown.SelectedValue, IsDeleted = false, ReturnDate = ReturnDatePicker.Value, TotalCreditAmount = list.Sum(a => a.TotalAmount), Remarks = RemarksTextbox.Text, Details = list, RecordedByUser = UserInfo.UserId, ApprovedByUser = approver }; worker.RunWorkerAsync(model); } private void ToggleButtons(bool enabled) { ExportButton.Enabled = enabled; SaveButton.Enabled = enabled; ClearButton.Enabled = enabled; } #endregion #region Clear private void ClearAll() { if (ReturnId == 0) { //MemoTextbox.Clear(); ReturnDatePicker.Value = DateTime.Now; CustomerDropdown.SelectedIndex = -1; CustomerDropdown.ComboBox.SelectedIndex = -1; RemarksTextbox.Clear(); ClearList(); TotalTextbox.Text = "0.00"; MemoTextbox.Focus(); } else LoadSalesReturnDetails(); ClearDetails(); } private void ClearButton_Click(object sender, EventArgs e) { ClearAll(); } #endregion #region Validation private void MemoTextbox_Validating(object sender, CancelEventArgs e) { if (string.IsNullOrWhiteSpace(MemoTextbox.Text)) e.Cancel = true; } private void TotalTextbox_Validating(object sender, CancelEventArgs e) { if (TotalTextbox.Text == "0.00") e.Cancel = true; } #region Check Duplicate private bool hasDuplicate = false; private void MemoTextbox_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(MemoTextbox.Text)) hasDuplicate = DuplicateChecker.CodeHasDuplicate(CodeType.SalesReturn, MemoTextbox.Text.Trim(), ReturnId); if (hasDuplicate) MemoTextbox.StateCommon.Content.Color1 = Color.Red; else MemoTextbox.StateCommon.Content.Color1 = Color.Black; } #endregion #endregion private SalesReturnExportObject CreateExportObject() { SalesReturnExportObject obj = new SalesReturnExportObject() { Code = MemoTextbox.Text, Customer = CustomerDropdown.Text, Items = list }; return obj; } private void ExportButton_Click(object sender, EventArgs e) { if (list.Count > 0) { ToggleButtons(false); LoadImage.Visible = true; SalesReturnExportObject exportObject = CreateExportObject(); exportWorker.RunWorkerAsync(exportObject); } else ClientHelper.ShowErrorMessage("No items to export."); } } public delegate void SalesReturnUpdatedEventHandler(object sender, EventArgs e); }
using System; using Work.HTTP; namespace Work.MVC { public class HttpPostAttribute : HttpMethodAttribute { public HttpPostAttribute() { } public HttpPostAttribute(string url) : base(url) { } public override HttpMethodType Type => HttpMethodType.Post; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.SqlClient; using SSISTeam9.Models; namespace SSISTeam9.DAO { public class StockDAO { public static void UpdateInventoryStock(Dictionary<long, int> itemAndNewStock) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); foreach (KeyValuePair<long, int> item in itemAndNewStock) { string q = @"UPDATE Inventory SET stockLevel = '" + item.Value + "' WHERE itemId = '" + item.Key + "'"; SqlCommand cmd = new SqlCommand(q, conn); cmd.ExecuteNonQuery(); } } } public static void UpdateInventoryStockById(long itemId, int stock) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"UPDATE Inventory SET stockLevel = '" + stock + "' WHERE itemId = '" + itemId+ "'"; SqlCommand cmd = new SqlCommand(q, conn); cmd.ExecuteNonQuery(); } } public static void UpdateWithReduceInventoryStockById(long itemId, int stock) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"UPDATE Inventory SET stockLevel=stockLevel-@qty WHERE itemId=@itemId"; SqlCommand cmd = new SqlCommand(q, conn); cmd.Parameters.AddWithValue("qty", stock); cmd.Parameters.AddWithValue("@itemId", itemId); cmd.ExecuteNonQuery(); } } public static List<Inventory> GetAllItemsOrdered() { List<Inventory> items = new List<Inventory>(); using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"SELECT * from Inventory WHERE flag = 0 ORDER BY (stockLevel - reorderLevel)"; SqlCommand cmd = new SqlCommand(q, conn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Inventory item = new Inventory() { ItemId = (long)reader["itemId"], ItemCode = (string)reader["itemCode"], BinNo = (reader["binNo"] == DBNull.Value) ? "Nil" : (string)reader["binNo"], StockLevel = (int)reader["stockLevel"], ReorderLevel = (int)reader["reorderLevel"], ReorderQty = (int)reader["reorderQty"], Category = (string)reader["category"], Description = (string)reader["description"], UnitOfMeasure = (string)reader["unitOfMeasure"], ImageUrl = (reader["imageUrl"] == DBNull.Value) ? "Nil" : (string)reader["imageUrl"] }; items.Add(item); } } return items; } public static List<Inventory> GetPendingOrderQuantities(List<Inventory> items) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); foreach(var item in items) { string sub = @" (SELECT orderId from PurchaseOrder WHERE status IN ('Pending Supplier Confirmation','Pending Delivery'))"; string q = @"SELECT SUM(quantity) from PurchaseOrderDetails WHERE orderId in" + sub + "and itemId = '" + item.ItemId + "' GROUP BY itemId"; SqlCommand cmd = new SqlCommand(q, conn); if (cmd.ExecuteScalar() == null) { item.PendingOrderQuantity = 0; } else { item.PendingOrderQuantity = (int)cmd.ExecuteScalar(); } } return items; } } public static List<long> GetItemsFirstSupplierIds(List<long> itemIds) { List<long> itemsFirstSupplierIds = new List<long>(); using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = null; foreach (var itemId in itemIds) { q = @"SELECT supplier1Id from PriceList WHERE itemId = '" + itemId + "'"; SqlCommand cmd = new SqlCommand(q, conn); itemsFirstSupplierIds.Add((long)cmd.ExecuteScalar()); } return itemsFirstSupplierIds; } } public static long GetItemId(string itemCode) { long itemId = 0; using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = @"SELECT itemId from Inventory WHERE itemCode = '" + itemCode + "'"; SqlCommand cmd = new SqlCommand(q, conn); itemId = (long)cmd.ExecuteScalar(); } return itemId; } public static void CreatePurchaseOrder(long supplierId, List<Tuple<long, int>> itemsQuantities, string newOrderNumber, long empId) { using (SqlConnection conn = new SqlConnection(Data.db_cfg)) { conn.Open(); string q = null; //Set rule for deliveryBy as one week from submitted/order date q = "INSERT INTO PurchaseOrder (supplierId,empId,orderNumber,status,submittedDate,orderDate,deliverTo,deliverBy)" + "VALUES ('" + supplierId + "','" + empId + "','" + newOrderNumber + "','" + "Pending Supplier Confirmation" + "','" + DateTime.Now.Date + "','" + DateTime.Now.Date + "','" + "Logic University 29 Heng Mui Keng Terrace Singapore 123456" + "','" + DateTime.Now.AddDays(7).Date + "')"; SqlCommand cmd = new SqlCommand(q, conn); cmd.ExecuteNonQuery(); q = @"SELECT orderId from PurchaseOrder where orderNumber = '" + newOrderNumber + "'"; cmd = new SqlCommand(q, conn); long orderId = (long)cmd.ExecuteScalar(); foreach (var c in itemsQuantities) { q = "INSERT INTO PurchaseOrderDetails (orderId,itemId,quantity)" + "VALUES ('" + orderId + "','" + c.Item1 + "','" + c.Item2 + "')"; cmd = new SqlCommand(q, conn); cmd.ExecuteNonQuery(); } } } } }
using WebAPIService.Controllers; using Microsoft.VisualStudio.TestTools.UnitTesting; using CA2_Azure.Controllers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; using CA2_Azure.Models; using CA2_AzureTests; using System.ComponentModel.DataAnnotations; using CA2_Azure.ServiceLayer; namespace CA2_Azure.Controllers.Tests { [TestClass()] public class TeasControllerTests { MockDB testdb = new MockDB(); [TestMethod()] //test data get from DB versus mock DB with same data public void DetailsTest() { TeasController controller = new TeasController(); var result = controller.Details(1) as ViewResult; var data = (Tea)result.ViewData.Model; Assert.AreEqual(testdb.getTea(1).Name, data.Name); } [TestMethod()] // Validation fails if quantity or price are less than zero or year has more(or less) than 4 numbers) public void validatationTest() { List<TeaMetaData> testlist = new List<TeaMetaData> { new TeaMetaData {Id=3, Type="Black Tea", Name="Jinjumei", Qty=-100, Price=8.5, Year="2016"}, new TeaMetaData {Id=3, Type="Black Tea", Name="Jinjumei", Qty=3000, Price=-10, Year="2016"}, new TeaMetaData {Id=3, Type="Black Tea", Name="Jinjumei", Qty=3000, Price=8.5, Year="201617"} }; foreach (TeaMetaData tea in testlist) { var model = tea; var context = new ValidationContext(model, null, null); var result = new List<ValidationResult>(); var valid = Validator.TryValidateObject(model, context, result, true); Assert.IsFalse(valid); } } } }
using CG.MovieAppEntity.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Text; namespace CG.MovieApp.DataAccess.Concrate.EntityFrameworkCore.DatabaseFluentApi { public class FilmActorConfiguration : IEntityTypeConfiguration<FilmActor> { public void Configure(EntityTypeBuilder<FilmActor> builder) { builder.HasKey(i => new { i.ActorId, i.FilmId }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpaceShipMovement : MonoBehaviour { // Scoping too broad: lots of class variables for no reason // Constrain scope of your variables. // Don't leak out data where it doesn't need to be. // Don't keep data around longer than it needs to be. RaycastHit hit; Vector3 frontPos, midPos, backPos; public float frontHeight, midHeight; [SerializeField] float minDistance; public float yRotation = 0.0F; public float xRotation = 0.0f; void Update() { midPos = transform.position; // use more expressive naming, e.g. shipPos. // Good: storing in local variable limits engine calls frontPos = midPos + transform.forward; // this only takes the position and adds 1,0,0 to it? // if anything, it should be relative to ship's length backPos = midPos - transform.forward; // this takes the position and subtracts 1,0,0 from it? // if anything, it should be relative to ship's length // use distance for raycast (we now compare it later). also limit by layermask if (Physics.Raycast(midPos, -transform.up, out hit)) { midHeight = hit.distance; } // use distance for raycast (we now compare it later). also limit by layermask if (Physics.Raycast(frontPos, -transform.up, out hit)) { // another expensive raycast? frontHeight = hit.distance; } // Notes(gb): why hardcoded 0.02? this should be relative if (midHeight - frontHeight > 0.02) { RotateSpaceShip(1.0f); // rotate how? this should not be a seperate function } else if (midHeight - frontHeight < -0.02) { RotateSpaceShip(-1.0f); // rotate how? this should not be a seperate function } if (midHeight < minDistance - 0.02f) { MoveSpaceShip(1); // move ship how? this should not be a seperate function } else if (midHeight > minDistance + 0.02f) { MoveSpaceShip(-1); // move ship how? this should not be a seperate function } } // are we calling these functions somewhere else? // dont make functions for naming sake... // Prefer commenting sections over extracting them. // Whenever you have a function, it implicitly says it can be called from anywhere inside the class. // Never have a function do something that happens in only one place. void RotateSpaceShip(float a) { // better naming for 'a' xRotation -= 90.0f * a * Time.deltaTime; transform.eulerAngles = new Vector3(xRotation, yRotation, 0); } void MoveSpaceShip(float a) { // better naming for 'a' Vector3 position = transform.position; // we already grabbed this as midPos. position.y += 5.0f * a * Time.deltaTime; // hardcoded 5.0f transform.position = position; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ParkingGarageManagement.Models { /// <summary> /// restricted ticket type with time limit, and allowed dimensions. /// </summary> public class RestrictedTicket : TicketType { public RestrictedTicket(int minLotRange, int maxLotRange, int price, TicketRank rank,int allowedMaxHight , int alloweMaxWidth, int allowedMaxLength, int timeLimit): base(minLotRange,maxLotRange,price,rank) { AllowedMaxHight = allowedMaxHight; AlloweMaxWidth = alloweMaxWidth; AllowedMaxLength = allowedMaxLength; TimeLimit = timeLimit; } //properties. public int AllowedMaxHight { get; set; } public int AlloweMaxWidth { get; set; } public int AllowedMaxLength { get; set; } public int TimeLimit { get; set; } /// <summary> /// validate the vehicles according to the allowed dimensions. /// </summary> /// <param name="vehicle"></param> /// <returns></returns> public override bool IsVehicleSuitable(Vehicle vehicle) { if(vehicle.Width>AlloweMaxWidth || vehicle.Height > AllowedMaxHight || vehicle.Length > AllowedMaxLength) { return false; } return true; } } }
// The MIT License (MIT) // // Copyright (c) 2014-2018, Institute for Software & Systems Engineering // Copyright (c) 2018, Pascal Pfeil // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using ISSE.SafetyChecking.ExecutableModel; using ISSE.SafetyChecking.Utilities; using System; using System.IO; using System.Linq; using System.Text; namespace SafetyLustre { public class LustreExecutableModelCounterExampleSerialization : CounterExampleSerialization<LustreExecutableModel> { public override void WriteInternalStateStructure(ExecutableCounterExample<LustreExecutableModel> counterExample, BinaryWriter writer) { } /// <summary> /// Loads a counter example from the <paramref name="file" />. /// </summary> /// <param name="file">The path to the file the counter example should be loaded from.</param> public override ExecutableCounterExample<LustreExecutableModel> Load(string file) { Requires.NotNullOrWhitespace(file, nameof(file)); using (var reader = new BinaryReader(File.OpenRead(file), Encoding.UTF8)) { if (reader.ReadInt32() != FileHeader) throw new InvalidOperationException("The file does not contain a counter example that is compatible with this version of S#."); var endsWithException = reader.ReadBoolean(); var serializedRuntimeModel = reader.ReadBytes(reader.ReadInt32()); var runtimeModel = new LustreExecutableModel(serializedRuntimeModel); runtimeModel.UpdateFaultSets(); var faultsLength = reader.ReadInt32(); var counterExample = new byte[reader.ReadInt32()][]; var slotCount = reader.ReadInt32(); if (slotCount != runtimeModel.StateVectorSize) { throw new InvalidOperationException( $"State slot count mismatch; the instantiated model requires {runtimeModel.StateVectorSize} state slots, " + $"whereas the counter example uses {slotCount} state slots."); } for (var i = 0; i < counterExample.Length; ++i) { counterExample[i] = new byte[runtimeModel.StateVectorSize]; for (var j = 0; j < runtimeModel.StateVectorSize; ++j) counterExample[i][j] = reader.ReadByte(); } var replayInfo = new int[reader.ReadInt32()][]; for (var i = 0; i < replayInfo.Length; ++i) { replayInfo[i] = new int[reader.ReadInt32()]; for (var j = 0; j < replayInfo[i].Length; ++j) replayInfo[i][j] = reader.ReadInt32(); } var faultActivations = runtimeModel.Faults.Select(fault => fault.Activation).ToArray(); return new ExecutableCounterExample<LustreExecutableModel>(runtimeModel, counterExample, replayInfo, endsWithException, faultActivations); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CRL.Business.TradeType { /// <summary> /// 交易方向 /// </summary> public enum TradeDirection { 收入 = 1, 支出 = 2 } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ScriptDeLasBoxes : MonoBehaviour { private Vector3 v_rot; public float speed_rot = 1.0f; private bool moving_up = false; public float speed_move = 1.0f; private float initial_pos; public float range = 0.5f; // Start is called before the first frame update void Start() { v_rot = new Vector3(0, 1, 0); initial_pos = transform.position.y; } // Update is called once per frame void Update() { transform.Rotate(v_rot, speed_rot); if (moving_up) { transform.Translate(Vector3.up * speed_move * Time.deltaTime); if (transform.position.y >= initial_pos + range) { moving_up = !moving_up; } } else { transform.Translate(-Vector3.up * speed_move * Time.deltaTime); if (transform.position.y <= initial_pos - range) { moving_up = !moving_up; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChessShi : ChessEntity { public override void ShowChessPath() { base.ShowChessPath(); int index_x = (int)chessObj.chess_index_x; int index_z = (int)chessObj.chess_index_z; // 自己的士 if (chessObj.chess_owner_player == 1) { if(index_x == 4) { SetIndexPath(3, 0); SetIndexPath(3, 2); SetIndexPath(5, 0); SetIndexPath(5, 2); } if(index_x == 3 || index_x == 5) { SetIndexPath(4, 1); } } else { if (index_x == 4) { SetIndexPath(3, 9); SetIndexPath(3, 7); SetIndexPath(5, 9); SetIndexPath(5, 7); } if (index_x == 3 || index_x == 5) { SetIndexPath(4, 8); } } } public override ChessType GetChessType() { return ChessType.ChessTypeShi; } }
using System.Collections.Generic; namespace DistributedCollections { public interface IBackplane { void Publish(BackplaneMessage messages); IEnumerable<BackplaneMessage> ReadMessages(MessageId lastId = default(MessageId)); IDistLock CreateLock(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using KartObjects; namespace KartSystem { [Serializable] public class ImportDocumentFromExlParamSettings : Entity { [XmlIgnore] public override string FriendlyName { get { return ""; } } [XmlElement("listSettings")] public List<listSettings> _listSettings { get; set; } } public class listSettings { public string Name { get; set; } public string Table { get; set; } public string GoodPosition { get; set; } public string ArticulPosition { get; set; } public string QuantityPosition { get; set; } public string PricePosition { get; set; } public string MeasurePosition { get; set; } } }
namespace Phenix.Test.使用指南._25._2 { [System.Serializable] [Phenix.Core.Mapping.ReadOnly] public class UserReadOnly : User<UserReadOnly> { private UserReadOnly() { //禁止添加代码 } } /// <summary> /// 清单 /// </summary> [System.Serializable] public class UserReadOnlyList : Phenix.Business.BusinessListBase<UserReadOnlyList, UserReadOnly> { private UserReadOnlyList() { //禁止添加代码 } } }
namespace SGpostMailData.Migrations { using System; using System.Data.Entity.Migrations; public partial class SgDataMobile : DbMigration { public override void Up() { AddColumn("dbo.SgDatas", "MobileNumber", c => c.String()); } public override void Down() { DropColumn("dbo.SgDatas", "MobileNumber"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace DoGoService.Controllers { public class FileTextController : ApiController { // GET: api/FileText public IEnumerable<string> Get() { //return new string[] { "value1", "value2" }; var C = "032010 1"; var G = "320003 1"; var Am = "002210 1"; var F = "133211 1"; return new[] { C, G, Am, F }; } } }
using System.ComponentModel.DataAnnotations; namespace Tndm_ArtShop.ViewModels { public class UrediKorisnikaViewModel { public string Id { get; set; } [Required(ErrorMessage = "Unesite korisnicko ime")] [Display(Name = "Korisnicko ime")] public string UserName { get; set; } [Required(ErrorMessage = "Unesite email")] public string Email { get; set; } public string Adresa { get; set; } public string Grad { get; set; } public string Drzava { get; set; } } }
using Fight; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ProgramGame { public class Box { public int ThreeBoxes(int healthHero, int weaponHeroMaxAttack, int count, int bonusHealth) { FightModule fightModule = new FightModule(); FinalFight finalFight = new FinalFight(); switch (Console.ReadLine()) { case "1": Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("В сундуке вы видите несметные богатства"); Console.WriteLine("*У вас случается сердечный приступ* - 3 HP"); Console.WriteLine("Возвращаемся назад, пока не появился новый монстр"); Console.WriteLine(); Thread.Sleep(5000); healthHero -= 3; break; case "2": Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine(); Console.WriteLine("В сундуке яд *Вы отравились* - 2 HP"); Console.WriteLine("Возвращаемся назад, пока не появился новый монстр"); Console.WriteLine(); Thread.Sleep(5000); healthHero -= 2; break; case "3": Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine(); Console.WriteLine("В сундуке вы находите Ржавый шлем (+5 HP)"); Thread.Sleep(5000); healthHero += 5; break; default: Console.WriteLine("Вам падает на голову камень и вы умираете"); healthHero = 0; break; } return healthHero; } } }