content
stringlengths
23
1.05M
using AutoMapper; using DAL.Entities; namespace API.TransferData.Profiles { internal class SimpleEntityProfile : Profile { public SimpleEntityProfile() { CreateMap<DataEntity, EntityDto>(); CreateMap<UpdateEntityDto, DataEntity>(); } } }
@using Microsoft.AspNetCore.Identity @using PicturesShop.Areas.Identity @using PicturesShop.Areas.Identity.Pages @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @using PicturesShop.Models
using System.Linq; using Marten.Services; using Marten.Testing.Documents; using Marten.Testing.Harness; using Xunit; namespace Marten.Testing.Linq { [ControlledQueryStoryteller] public class query_with_float_Tests : IntegrationContext { [Fact] public void can_query_by_float() { var target1 = new Target {Float = 123.45F}; var target2 = new Target {Float = 456.45F}; theSession.Store(target1, target2); theSession.Store(Target.GenerateRandomData(5).ToArray()); theSession.SaveChanges(); theSession.Query<Target>().Where(x => x.Float > 400).ToArray().Select(x => x.Id) .ShouldContain(x => x == target2.Id); } public query_with_float_Tests(DefaultStoreFixture fixture) : base(fixture) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager { public IPlayer player; public GameManager(IPlayer player) { this.player = player; } public void GameOver() { player.OnGameOver(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace mulitThread { public partial class Form1 : Form { Form2 _f2; public Form1() { InitializeComponent(); } //新开一个线程,执行一个方法,没有参数传递 public void DoWork1() { Thread t = new Thread(new ThreadStart(DoSomeThing)); t.Start(); } //带参数 public void DoWork2() { Thread t = new Thread(new ParameterizedThreadStart(DoSomeThing)); t.Start("form1 use paramer"); } //使用线程池 public void DoWork3() { ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomeThing), "use from 1 paramer"); } //使用自定义委托 public void DoWork4() { WaitCallback wc = new WaitCallback(DoSomeThing4); ThreadPool.QueueUserWorkItem(wc, "invoke from 1"); } public delegate void MyInvokeDelegate(string name); public void ChangeText(string name) { this.textBox1.Text = name; } public void DoSomeThing4(object o) { this.Invoke(new MyInvokeDelegate(ChangeText), o.ToString()); } public void DoSomeThing() { Form2 f2 = new Form2(this); f2.textBox1.Text = "form1 use"; MessageBox.Show("form1 use"); f2.Show(); } public void DoSomeThing(object o) { Form2 f2 = new Form2(this); f2.textBox1.Text = o.ToString(); MessageBox.Show(o.ToString()); f2.Show(); } private void button1_Click(object sender, EventArgs e) { DoWork1(); } private void button1_Click_1(object sender, EventArgs e) { DoWork2(); } private void button4_Click(object sender, EventArgs e) { DoWork3(); } private void button3_Click(object sender, EventArgs e) { DoWork4(); _f2 = new Form2(this); //_f2.btn1.Click += btn1_Click; _f2.Show(); } void btn1_Click(object sender, EventArgs e) { Thread t = new Thread(new ParameterizedThreadStart(ChangeTexts)); t.Start("good"); } public void ChangeTexts(object name) { for (int i = 0; i < 100000; i++) { this.Invoke(new Action(delegate() { _f2.textBox1.Text = name.ToString() + i.ToString(); })); } } } }
using UnityEngine; public class PlayerAnimatorController : MonoBehaviour { public GameObject SpriteHolder; private Animator animator; private Vector3 scale; void Start() { animator = SpriteHolder.GetComponent<Animator>(); scale = transform.localScale; } private void Flip() { scale.x *= -1; transform.localScale = scale; } public void UpdateParameters(float motion, bool isGrounded, bool isHurt) { animator.SetFloat("motion", motion); if (motion * scale.x < 0) Flip(); animator.SetBool("isGrounded", isGrounded); animator.SetBool("isHurt", isHurt); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spaceship : MonoBehaviour { public GameObject Bomb; public Sprite No_Work; void Update () { if (GameObject.Find("Canvas").GetComponent<GameMaster>().Life <= 0) { this.gameObject.GetComponent<SpriteRenderer>().sprite = No_Work; GameObject.Find("Canvas").GetComponent<GameMaster>().Game_Active = false; GameObject.Find("Canvas").GetComponent<GameMaster>().Announcement.text = "YOU WIN!"; }else { if (this.gameObject.transform.position.x <= -6.5) { transform.eulerAngles = new Vector3(0, 0, -90); }else if (this.gameObject.transform.position.x >= 6.5) { transform.eulerAngles = new Vector3(0, 0, 90); } transform.Translate(Vector2.up * Time.deltaTime * 2); if (Random.Range(0, GameObject.Find("Canvas").GetComponent<GameMaster>().Life + 50) == 24) { Instantiate(Bomb, new Vector2(transform.position.x, transform.position.y - 1), new Quaternion(0, 0, 0, 0)); } } } void OnCollisionEnter2D (Collision2D collision) { if (collision.gameObject.name == "Laser" && GameObject.Find("Canvas").GetComponent<GameMaster>().Life > 0) { GameObject.Find("Canvas").GetComponent<GameMaster>().Score += 15; GameObject.Find("Canvas").GetComponent<GameMaster>().Life -= 10; } } }
#region Copyright Syncfusion Inc. 2001-2021. // Copyright Syncfusion Inc. 2001-2021. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // licensing@syncfusion.com. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebSampleBrowser.Menu { public class menufields { public string id { get; set; } public int? parentId { get; set; } public string text { get; set; } public string sprite { get; set; } } public partial class Databinding_Local : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { List<menufields> sites = new List<menufields>(); sites.Add(new menufields { id = "1", parentId = null, text = "Group A" }); sites.Add(new menufields { id = "2", parentId = null, text = "Group B" }); sites.Add(new menufields { id = "3", parentId = null, text = "Group C" }); sites.Add(new menufields { id = "4", parentId = null, text = "Group D" }); //first level child sites.Add(new menufields { id = "11", parentId = 1, text = "Algeria", sprite = "flag-dz" }); sites.Add(new menufields { id = "12", parentId = 1, text = "Armenia", sprite = "flag-am" }); sites.Add(new menufields { id = "13", parentId = 1, text = "Bangladesh", sprite = "flag-bd" }); sites.Add(new menufields { id = "14", parentId = 1, text = "Cuba", sprite = "flag-cu" }); sites.Add(new menufields { id = "15", parentId = 2, text = "Denmark", sprite = "flag-dk" }); sites.Add(new menufields { id = "16", parentId = 2, text = "Egypt", sprite = "flag-eg" }); sites.Add(new menufields { id = "17", parentId = 3, text = "Finland", sprite = "flag-fi" }); sites.Add(new menufields { id = "18", parentId = 3, text = "India", sprite = "flag-in" }); sites.Add(new menufields { id = "19", parentId = 3, text = "Malaysia", sprite = "flag-my" }); sites.Add(new menufields { id = "20", parentId = 4, text = "New Zealand", sprite = "flag-nz" }); sites.Add(new menufields { id = "21", parentId = 4, text = "Norway", sprite = "flag-no" }); sites.Add(new menufields { id = "22", parentId = 4, text = "Poland", sprite = "flag-pl" }); sites.Add(new menufields { id = "23", parentId = 5, text = "Romania", sprite = "flag-ro" }); sites.Add(new menufields { id = "24", parentId = 5, text = "Singapore", sprite = "flag-sg" }); sites.Add(new menufields { id = "25", parentId = 5, text = "Thailand", sprite = "flag-th" }); sites.Add(new menufields { id = "26", parentId = 5, text = "Ukraine", sprite = "flag-ua" }); //second level child sites.Add(new menufields { id = "111", parentId = 11, text = "First Place" }); sites.Add(new menufields { id = "112", parentId = 12, text = "Second Place" }); sites.Add(new menufields { id = "113", parentId = 13, text = "Third place" }); sites.Add(new menufields { id = "114", parentId = 14, text = "Fourth Place" }); sites.Add(new menufields { id = "115", parentId = 15, text = "First Place" }); sites.Add(new menufields { id = "116", parentId = 16, text = "Second Place" }); sites.Add(new menufields { id = "117", parentId = 17, text = "Third Place" }); sites.Add(new menufields { id = "118", parentId = 18, text = "First Place" }); sites.Add(new menufields { id = "119", parentId = 19, text = "Second Place" }); sites.Add(new menufields { id = "120", parentId = 20, text = "First Place" }); sites.Add(new menufields { id = "121", parentId = 21, text = "Second Place" }); sites.Add(new menufields { id = "122", parentId = 22, text = "Third place" }); sites.Add(new menufields { id = "123", parentId = 3, text = "Fourth Place" }); sites.Add(new menufields { id = "120", parentId = 24, text = "First Place" }); sites.Add(new menufields { id = "121", parentId = 25, text = "Second Place" }); sites.Add(new menufields { id = "122", parentId = 26, text = "Third place" }); this.sitemenu.Fields.DataSource = sites; } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Netcool.Api.Domain.Menus; using Netcool.Core.AspNetCore.Controllers; using Netcool.Core.Services.Dto; namespace Netcool.Api.Controllers { [Route("menus")] [Authorize] public class MenusController : QueryControllerBase<MenuDto, int, PageRequest> { private readonly IMenuService _menuService; public MenusController(IMenuService service) : base(service) { _menuService = service; } [HttpGet("tree")] public ActionResult<MenuTreeNode> GetTree() { var node = _menuService.GetMenuTree(); return Ok(node); } [HttpPut("{id}")] public IActionResult Update(int id, [FromBody] MenuDto input) { input.Id = id; Service.Update(input); return Ok(); } } }
namespace dotnetcore { public class MySettings { public string CouchbaseBucket { get; set; } public string CouchbaseServer { get; set; } } }
namespace DbKeeperNet.Engine { public interface IUpdateStepExecutedMarker { void MarkAsExecuted(string assembly, string version, int stepNumber); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Mono.Linker.Tests.Cases.Expectations.Assertions; using Mono.Linker.Tests.Cases.Expectations.Metadata; using Mono.Linker.Tests.Cases.LinkAttributes.Dependencies; namespace Mono.Linker.Tests.Cases.LinkAttributes { [SetupCompileBefore ("attributes.dll", new string[] { "Dependencies/TestRemoveDontRemoveAttributes.cs" }, resources: new object[] { new string[] { "Dependencies/TestRemoveAttribute.xml", "ILLink.LinkAttributes.xml" } }, addAsReference: false)] [SetupCompileBefore ("library.dll", new string[] { "Dependencies/ReferencedAssemblyWithAttributes.cs" }, references: new string[] { "attributes.dll" })] [SetupLinkerAction ("copyused", "attributes")] // Ensure that assembly-level attributes are kept [IgnoreLinkAttributes (false)] [KeptAttributeInAssembly ("library.dll", "Mono.Linker.Tests.Cases.LinkAttributes.Dependencies.TestDontRemoveAttribute")] [RemovedAttributeInAssembly ("library.dll", "Mono.Linker.Tests.Cases.LinkAttributes.Dependencies.TestRemoveAttribute")] class EmbeddedLinkAttributesInReferencedAssembly_AssemblyLevel { public static void Main () { ReferenceOtherAssembly (); } [Kept] public static void ReferenceOtherAssembly () { var _1 = new ReferencedAssemblyWithAttributes (); } } }
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Threading.Tasks; namespace GoogleMapsComponents.Maps { /// <summary> /// Animations that can be played on a marker. /// Use the setAnimation method on Marker or the animation option to play an animation. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum Animation { /// <summary> /// Marker bounces until animation is stopped. /// </summary> [EnumMember(Value = "google.maps.Animation.BOUNCE")] Bounce = 1, /// <summary> /// Marker falls from the top of the map ending with a small bounce. /// </summary> [EnumMember(Value = "google.maps.Animation.DROP")] Drop } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Xml; using System.Xml.Schema; using Mono.Options; namespace Mono.Documentation { public class MDocValidator : MDocCommand { XmlReaderSettings settings; long errors = 0; public override void Run (IEnumerable<string> args) { string[] validFormats = { "ecma", }; string format = "ecma"; var p = new OptionSet () { { "f|format=", "The documentation {0:FORMAT} used within PATHS. " + "Valid formats include:\n " + string.Join ("\n ", validFormats) + "\n" + "If no format provided, `ecma' is used.", v => format = v }, }; List<string> files = Parse (p, args, "validate", "[OPTIONS]+ PATHS", "Validate PATHS against the specified format schema."); if (files == null) return; if (Array.IndexOf (validFormats, format) < 0) Error ("Invalid documentation format: {0}.", format); Run (format, files); } public void Run (string format, IEnumerable<string> files) { InitializeSchema (format); // skip args[0] because it is the provider name foreach (string arg in files) { if (IsMonodocFile (arg)) ValidateFile (arg); if (Directory.Exists (arg)) { RecurseDirectory (arg); } } Message (errors == 0 ? TraceLevel.Info : TraceLevel.Error, "Total validation errors: {0}", errors); } public void InitializeSchema (string format, ValidationEventHandler extraHandler = null) { Stream s = null; switch (format) { case "ecma": s = Assembly.GetExecutingAssembly ().GetManifestResourceStream ("monodoc-ecma.xsd"); break; default: throw new NotSupportedException (string.Format ("The format `{0}' is not suppoted.", format)); } if (s == null) throw new NotSupportedException (string.Format ("The schema for `{0}' was not found.", format)); settings = new XmlReaderSettings (); settings.Schemas.Add (XmlSchema.Read (s, null)); settings.Schemas.Compile (); settings.ValidationType = ValidationType.Schema; settings.ValidationEventHandler += OnValidationEvent; if (extraHandler != null) settings.ValidationEventHandler += extraHandler; } public void ValidateFile (string file) { if (settings == null) InitializeSchema ("ecma"); try { using (var reader = XmlReader.Create (new XmlTextReader (file), settings)) { while (reader.Read ()) { // do nothing } } } catch (Exception e) { Message (TraceLevel.Error, "mdoc: {0}", e.ToString ()); } } public void ValidateFile (TextReader textReader) { if (settings == null) InitializeSchema ("ecma"); try { using (var xmlReader = XmlReader.Create (textReader, settings)) while (xmlReader.Read ()) {} } catch (Exception e) { Message (TraceLevel.Error, "mdoc: {0}", e.ToString ()); } } void RecurseDirectory (string dir) { string[] files = Directory.GetFiles (dir, "*.xml"); foreach (string f in files) { if (IsMonodocFile (f)) ValidateFile (f); } string[] dirs = Directory.GetDirectories (dir); foreach (string d in dirs) RecurseDirectory (d); } void OnValidationEvent (object sender, ValidationEventArgs a) { errors++; Message (TraceLevel.Error, "mdoc: {0}", a.Message); } static bool IsMonodocFile (string file) { var dpath = Path.GetDirectoryName (file); var dname = Path.GetFileName (dpath); if (File.Exists (file) && Path.GetExtension (file).ToLower () == ".xml" && !dname.Equals(Consts.FrameworksIndex)) return true; else return false; } } }
namespace StripeTests { using System; using System.IO; using System.Reflection; using System.Text; using Newtonsoft.Json; using Stripe; using Xunit; public class StripeAccountTest : BaseStripeTest { [Fact] public void Deserialize() { string json = GetFixture("/v1/accounts/acct_123"); var account = Mapper<StripeAccount>.MapFromJson(json); Assert.NotNull(account); Assert.IsType<StripeAccount>(account); Assert.NotNull(account.Id); Assert.Equal("account", account.Object); } [Fact] public void DeserializeWithExpansions() { string[] expansions = { "business_logo", }; string json = GetFixture("/v1/accounts/acct_123", expansions); var account = Mapper<StripeAccount>.MapFromJson(json); Assert.NotNull(account); Assert.IsType<StripeAccount>(account); Assert.NotNull(account.Id); Assert.Equal("account", account.Object); Assert.NotNull(account.BusinessLogo); Assert.Equal("file_upload", account.BusinessLogo.Object); } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using NSubstitute; using Wolfberry.TelldusLive.Models.Client; using Wolfberry.TelldusLive.Repositories; using Xunit; namespace Wolfberry.TelldusLive.Tests.Repositories { public class ClientRepositoryTests { [Fact] public async Task GetClientsAsync_NoArguments_ReturnsOk() { const string expectedId = "123"; var mockedClients = new ClientsResponse { Client = new List<Client> { new Client { Id = expectedId } } }; const string url = "https://wolfberry.se:443/api"; var telldusClient = Substitute.For<ITelldusHttpClient>(); telldusClient.BaseUrl .Returns(url); telldusClient.GetAsJsonAsync(default) .ReturnsForAnyArgs(JsonConvert.SerializeObject(mockedClients)); IClientRepository repository = new ClientRepository(telldusClient); var clients = await repository.GetClientsAsync(); Assert.NotNull(clients); Assert.Equal(expectedId, clients.Client.First().Id); } } }
using System; using System.Collections.Generic; using JetBrains.Annotations; using Perfolizer.Common; using Perfolizer.Mathematics.Common; using Perfolizer.Mathematics.QuantileEstimators; using Perfolizer.Mathematics.Sequences; namespace Perfolizer.Mathematics.Functions { public class GammaEffectSizeFunction : QuantileCompareFunction { public static readonly GammaEffectSizeFunction Instance = new GammaEffectSizeFunction(); private const double Eps = 1e-9; public GammaEffectSizeFunction([CanBeNull] IQuantileEstimator quantileEstimator = null) : base(quantileEstimator) { } public override double GetValue(Sample a, Sample b, Probability probability) { Assertion.NotNull(nameof(a), a); Assertion.NotNull(nameof(b), b); try { double aMad = MedianAbsoluteDeviation.CalcMad(a); double bMad = MedianAbsoluteDeviation.CalcMad(b); if (aMad < Eps && bMad < Eps) { double aMedian = QuantileEstimator.GetMedian(a); double bMedian = QuantileEstimator.GetMedian(b); if (Math.Abs(aMedian - bMedian) < Eps) return 0; return aMedian < bMedian ? double.PositiveInfinity : double.NegativeInfinity; } double aQuantile = QuantileEstimator.GetQuantile(a, probability); double bQuantile = QuantileEstimator.GetQuantile(b, probability); double pooledMad = PooledMad(a.Count, b.Count, aMad, bMad); return (bQuantile - aQuantile) / pooledMad; } catch (Exception) { return double.NaN; } } public override double[] GetValues(Sample a, Sample b, IReadOnlyList<Probability> probabilities) { Assertion.NotNull(nameof(a), a); Assertion.NotNull(nameof(b), b); Assertion.NotNullOrEmpty(nameof(probabilities), probabilities); int k = probabilities.Count; try { double aMad = MedianAbsoluteDeviation.CalcMad(a); double bMad = MedianAbsoluteDeviation.CalcMad(b); if (aMad < Eps && bMad < Eps) { double aMedian = QuantileEstimator.GetMedian(a); double bMedian = QuantileEstimator.GetMedian(b); if (Math.Abs(aMedian - bMedian) < Eps) return ConstantSequence.Zero.GenerateArray(k); return aMedian < bMedian ? ConstantSequence.PositiveInfinity.GenerateArray(k) : ConstantSequence.NegativeInfinity.GenerateArray(k); } double[] aQuantile = QuantileEstimator.GetQuantiles(a, probabilities); double[] bQuantile = QuantileEstimator.GetQuantiles(b, probabilities); double pooledMad = PooledMad(a.Count, b.Count, aMad, bMad); double[] values = new double[k]; for (int i = 0; i < k; i++) values[i] = (bQuantile[i] - aQuantile[i]) / pooledMad; return values; } catch (Exception) { return ConstantSequence.NaN.GenerateArray(k); } } public static double PooledMad(int n1, int n2, double mad1, double mad2) { return Math.Sqrt(((n1 - 1) * mad1.Sqr() + (n2 - 1) * mad2.Sqr()) / (n1 + n2 - 2)); } protected override double CalculateValue(double quantileA, double quantileB) { throw new NotSupportedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace ScriptCenter.Controls { public class Wizard : Form { private WizardPage currentPage; public void ShowPage(WizardPage c) { if (this.currentPage != null) this.Controls.Remove(this.currentPage); c.Dock = DockStyle.Fill; c.Wizard = this; this.Controls.Add(c); this.currentPage = c; } protected override void OnShown(EventArgs e) { base.OnShown(e); foreach (Control c in this.Controls) { if (c is WizardPage) { this.currentPage = (WizardPage)c; ((WizardPage)c).Wizard = this; break; } } } } public class WizardPage : UserControl { public Wizard Wizard { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using System.Data; public partial class Admin_Default : System.Web.UI.Page { SqlConnection con = new SqlConnection(Helper.GetCon()); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GetFeedback(); ltTotalUsers.Text = Helper.CountData("users", "", ""); ltTotalOrders.Text = Helper.CountData("orders", "", ""); ltTotalFeedback.Text = Helper.CountData("feedback", "", ""); ltTotalProducts.Text = Helper.CountData("products", "", ""); SetTheProgress(pUsers, ltTotalUsers.Text + "%"); SetTheProgress(pOrders, ltTotalOrders.Text + "%"); SetTheProgress(pFeedback, ltTotalFeedback.Text + "%"); SetTheProgress(pProducts, ltTotalProducts.Text + "%"); } } void SetTheProgress(HtmlGenericControl bar, string value) { bar.Attributes.Add("style", string.Format("width:{0};", value)); } void GetFeedback() { con.Open(); SqlCommand com = new SqlCommand(); com.Connection = con; com.CommandText = "Select feebackid, feedback, response, datecreated from feedback"; SqlDataAdapter da = new SqlDataAdapter(com); DataSet ds = new DataSet(); da.Fill(ds, "Feedback"); lvFeedback.DataSource = ds; lvFeedback.DataBind(); con.Close(); } protected void OnPagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e) { (lvFeedback.FindControl("DataPager1") as DataPager).SetPageProperties(e.StartRowIndex, e.MaximumRows, false); this.GetFeedback(); } }
using System; using System.Linq; using System.Reflection; using FluentAssertions; using Xunit; namespace Ploch.Common.Tests.Reflection { public class AttributeHelpersTests { [Fact] public void GetAttributes_Inherited_From_ParentTest() { var attributes = typeof(TestTypes.ClassWithInherited_Attribute1_1_And_Attribute2) .GetCustomAttributes<TestTypes.Attribute1Attribute>(true); attributes.Should().HaveCount(2); attributes.Should().ContainSingle(attr => attr.GetType() == typeof(TestTypes.Attribute1Attribute)); attributes.Should().ContainSingle(attr => attr.GetType() == typeof(TestTypes.Attribute1_1Attribute)); } /// <exception cref="TypeLoadException"> /// A custom attribute type cannot be loaded. /// </exception> [Fact] public void GetAttributesSingleNotInheritedTest() { var attributes = typeof(TestTypes.ClassWith_Attribute2).GetCustomAttributes<TestTypes.Attribute2Attribute>(); attributes.Should().HaveCount(1); var attribute = attributes.Single(); attribute.Name.Should().Be(nameof(TestTypes.Attribute2Attribute)); attribute.GetType().Should().Be<TestTypes.Attribute2Attribute>(); } } }
using System; using System.Linq; using Microsoft.AspNetCore.Mvc; using NSwag.Annotations; namespace DataService.Controllers { /* Don't know why, but nswag generates an empty path here and the UI blows up */ [Route("[Controller]")] public class HealthCheckController : Controller { public HealthCheckController() { } [HttpGet("")] [SwaggerOperation(operationId: "getHealthCheck")] [ProducesResponseType(typeof(string), 200)] public IActionResult Ping() { return Ok("I'm fine"); } } }
#if Full || App using Microsoft.AspNetCore.Http; namespace Netnr.SharedApp { /// <summary> /// 客户端信息 /// </summary> public class ClientTo { /// <summary> /// 构造 /// </summary> /// <param name="content"></param> public ClientTo(HttpContext content) { var header = content.Request.HttpContext.Request.Headers; IPv4 = content.Request.HttpContext.Connection.RemoteIpAddress.ToString(); //取代理IP if (header.ContainsKey("X-Forwarded-For")) { IPv4 = header["X-Forwarded-For"].ToString(); } Language = header["Accept-Language"].ToString().Split(';')[0]; Referer = header["Referer"].ToString(); UserAgent = header["User-Agent"].ToString(); } /// <summary> /// IPv4 /// </summary> public string IPv4 { get; set; } /// <summary> /// IPv6 /// </summary> public string IPv6 { get; set; } /// <summary> /// UA /// </summary> public string UserAgent { get; set; } /// <summary> /// 语言 /// </summary> public string Language { get; set; } /// <summary> /// 引荐 /// </summary> public string Referer { get; set; } } } #endif
using UnityEngine; namespace Fjord.Common.Utilities { /// <summary> /// Utility methods for UnityEngine.Color. /// </summary> public static class ColorUtility { public static Color MoveTowards(Color a, Color b, float maxAmount) { return new Color( Mathf.MoveTowards(a.r, b.r, maxAmount), Mathf.MoveTowards(a.g, b.g, maxAmount), Mathf.MoveTowards(a.b, b.b, maxAmount), Mathf.MoveTowards(a.a, b.a, maxAmount)); } } }
using System; using ObjCRuntime; namespace Firebase.PerformanceMonitoring { [Native] public enum HttpMethod : long { Get, Put, Post, Delete, Head, Patch, Options, Trace, Connect } }
// Copyright (c) 2021 Yoakke. // Licensed under the Apache License, Version 2.0. // Source repository: https://github.com/LanguageDev/Yoakke using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Yoakke.Ir.Model; using Type = Yoakke.Ir.Model.Type; namespace Yoakke.Ir { /// <summary> /// A builder to help constructing <see cref="IAssembly"/>s. /// </summary> public class AssemblyBuilder { private IProcedure? currentProcedure; private IBasicBlock? currentBasicBlock; /// <summary> /// The built <see cref="IAssembly"/>. /// </summary> public IAssembly Assembly { get; } = new Assembly(); /// <summary> /// The current <see cref="IProcedure"/> we are building. /// </summary> public IProcedure CurrentProcedure { get => this.currentProcedure ?? throw new InvalidOperationException("No procedure is being built"); set { this.currentProcedure = value; this.currentBasicBlock = this.currentProcedure.BasicBlocks.Count > 0 ? this.currentProcedure.BasicBlocks[^1] : null; } } /// <summary> /// The current <see cref="IBasicBlock"/> we are building. /// </summary> public IBasicBlock CurrentBasicBlock { get => this.currentBasicBlock ?? throw new InvalidOperationException("No basic block is being built"); set { this.currentBasicBlock = value; this.currentProcedure = this.currentBasicBlock.Procedure; } } /// <summary> /// Defines a new <see cref="IProcedure"/> in the <see cref="Assembly"/>. /// </summary> /// <param name="name">The logical name of the procedure.</param> /// <param name="result">The defined <see cref="IProcedure"/> gets /// written here.</param> /// <returns>This instance to chain calls.</returns> public AssemblyBuilder DefineProcedure(string name, out IProcedure result) { var proc = new Procedure(name); var bb = new BasicBlock(proc); proc.BasicBlocks.Add(bb); this.Assembly.Procedures.Add(name, proc); this.currentProcedure = proc; this.currentBasicBlock = bb; result = proc; return this; } /// <summary> /// Defines a new <see cref="IProcedure"/> in the <see cref="Assembly"/>. /// </summary> /// <param name="name">The logical name of the procedure.</param> /// <returns>This instance to chain calls.</returns> public AssemblyBuilder DefineProcedure(string name) => this.DefineProcedure(name, out var _); /// <summary> /// Defines a new parameter in the current <see cref="IProcedure"/>. /// </summary> /// <param name="type">The type of the argument to define.</param> /// <param name="result">The <see cref="Value"/> gets written here /// that can be used to reference the defined parameter.</param> /// <returns>This instance to chain calls.</returns> public AssemblyBuilder DefineParameter(Type type, out Value result) { var proc = this.CurrentProcedure; var param = new Parameter(type); result = new Value.Argument(param); proc.Parameters.Add(param); return this; } /// <summary> /// Defines a new parameter in the current <see cref="IProcedure"/>. /// </summary> /// <param name="type">The type of the argument to define.</param> /// <returns>This instance to chain calls.</returns> public AssemblyBuilder DefineParameter(Type type) => this.DefineParameter(type, out var _); /// <summary> /// Defines a new <see cref="IBasicBlock"/> in the current <see cref="IProcedure"/>. /// </summary> /// <param name="result">The new <see cref="IBasicBlock"/> gets written here.</param> /// <returns>This instance to chain calls.</returns> public AssemblyBuilder DefineBasicBlock(out IBasicBlock result) { var proc = this.CurrentProcedure; result = new BasicBlock(proc); proc.BasicBlocks.Add(result); this.currentBasicBlock = result; return this; } /// <summary> /// Defines a new <see cref="IBasicBlock"/> in the current <see cref="IProcedure"/>. /// </summary> /// <returns>This instance to chain calls.</returns> public AssemblyBuilder DefineBasicBlock() => this.DefineBasicBlock(out var _); /// <summary> /// Defines a local in the current <see cref="IProcedure"/>. /// </summary> /// <param name="type">The <see cref="Type"/> of the local to define.</param> /// <param name="result">The reference to the local gets written here.</param> /// <returns>This instance to chain calls.</returns> public AssemblyBuilder DefineLocal(Type type, out Value result) { var proc = this.CurrentProcedure; var local = new Local(type); result = new Value.Local(local); proc.Locals.Add(local); return this; } /// <summary> /// Defines a <see cref="Local"/> in the current <see cref="IProcedure"/>. /// </summary> /// <param name="type">The <see cref="Type"/> of the <see cref="Local"/> to define.</param> /// <returns>This instance to chain calls.</returns> public AssemblyBuilder DefineLocal(Type type) => this.DefineLocal(type, out var _); /// <summary> /// Writes an <see cref="Instruction"/> to the <see cref="Assembly"/>. /// </summary> /// <param name="instruction">The <see cref="Instruction"/> to add.</param> /// <returns>This instance to chain calls.</returns> public AssemblyBuilder Write(Instruction instruction) { this.CurrentBasicBlock.Instructions.Add(instruction); return this; } #region Instructions /// <summary> /// Writes a return instruction. /// </summary> /// <param name="value">The optional <see cref="Value"/> to return.</param> /// <returns>This instance to chain calls.</returns> public AssemblyBuilder Ret(Value? value = null) => this.Write(new Instruction.Ret(value)); /// <summary> /// Writes an integer addition instruction. /// </summary> /// <param name="left">The first operand to add.</param> /// <param name="right">The second operand to add.</param> /// <param name="result">The <see cref="Value"/> gets written here /// that can be used to reference the result.</param> /// <returns>This instance to chain calls.</returns> public AssemblyBuilder IntAdd(Value left, Value right, out Value result) => this.WriteValueProducer(new Instruction.IntAdd(left, right), out result); /// <summary> /// Writes an integer addition instruction. /// </summary> /// <param name="left">The first operand to add.</param> /// <param name="right">The second operand to add.</param> /// <returns>This instance to chain calls.</returns> public AssemblyBuilder IntAdd(Value left, Value right) => this.IntAdd(left, right, out var _); #endregion private AssemblyBuilder WriteValueProducer(Instruction.ValueProducer ins, out Value result) { var bb = this.CurrentBasicBlock; result = new Value.Temp(ins); bb.Instructions.Add(ins); return this; } } }
// This file has been generated by the GUI designer. Do not modify. namespace QS.Test.TestApp.Views { public partial class ButtonSubscriptionTabView { private global::Gtk.VBox vbox1; private global::Gtk.HBox hbox1; private global::Gtk.Button buttonSave; private global::Gtk.Button buttonCancel; protected virtual void Build() { global::Stetic.Gui.Initialize(this); // Widget QS.Test.TestApp.Views.ButtonSubscriptionTabView global::Stetic.BinContainer.Attach(this); this.Name = "QS.Test.TestApp.Views.ButtonSubscriptionTabView"; // Container child QS.Test.TestApp.Views.ButtonSubscriptionTabView.Gtk.Container+ContainerChild this.vbox1 = new global::Gtk.VBox(); this.vbox1.Name = "vbox1"; this.vbox1.Spacing = 6; // Container child vbox1.Gtk.Box+BoxChild this.hbox1 = new global::Gtk.HBox(); this.hbox1.Name = "hbox1"; this.hbox1.Spacing = 6; // Container child hbox1.Gtk.Box+BoxChild this.buttonSave = new global::Gtk.Button(); this.buttonSave.CanFocus = true; this.buttonSave.Name = "buttonSave"; this.buttonSave.UseUnderline = true; this.buttonSave.Label = global::Mono.Unix.Catalog.GetString("Сохранить"); global::Gtk.Image w1 = new global::Gtk.Image(); w1.Pixbuf = global::Stetic.IconLoader.LoadIcon(this, "gtk-save", global::Gtk.IconSize.Menu); this.buttonSave.Image = w1; this.hbox1.Add(this.buttonSave); global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.buttonSave])); w2.Position = 0; w2.Expand = false; w2.Fill = false; // Container child hbox1.Gtk.Box+BoxChild this.buttonCancel = new global::Gtk.Button(); this.buttonCancel.CanFocus = true; this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.UseUnderline = true; this.buttonCancel.Label = global::Mono.Unix.Catalog.GetString("Отменить"); global::Gtk.Image w3 = new global::Gtk.Image(); w3.Pixbuf = global::Stetic.IconLoader.LoadIcon(this, "gtk-revert-to-saved", global::Gtk.IconSize.Menu); this.buttonCancel.Image = w3; this.hbox1.Add(this.buttonCancel); global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.buttonCancel])); w4.Position = 1; w4.Expand = false; w4.Fill = false; this.vbox1.Add(this.hbox1); global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.hbox1])); w5.Position = 0; w5.Expand = false; w5.Fill = false; this.Add(this.vbox1); if ((this.Child != null)) { this.Child.ShowAll(); } this.Hide(); } } }
using Photon.Pun; using UnityEngine; public class MasterClientUi : MonoBehaviour { private void Start() { if (!PhotonNetwork.IsMasterClient) { Destroy(gameObject); } } }
#r "../../../Core/bin/debug/netcoreapp3.1/Core.dll" #r "System.Runtime.dll" #r "System.Collections.dll" using System; using System.Collections.Generic; using System.Text; using LCGuidebook.Core; using LCGuidebook.Core.DataStructures; public void InitNationalProperties() { ResourceManager.Me.MiscProperties.Add("NukeArsenal", new Queue<NuclearMissile>()); }
using System.Collections.Generic; namespace SnipInsight.Forms.Features.Library { public class Grouping<K, T> : List<T> { public Grouping(K key) { this.Key = key; } public Grouping(K key, IEnumerable<T> items) : this(key) { this.AddRange(items); } public K Key { get; private set; } } }
using System; using System.Threading.Tasks; using System.Web; using OwnID.Extensibility.Cache; using OwnID.Extensibility.Configuration; using OwnID.Extensibility.Exceptions; using OwnID.Extensibility.Flow; using OwnID.Extensibility.Flow.Contracts.MagicLink; using OwnID.Extensibility.Providers; using OwnID.Extensibility.Services; using OwnID.Extensions; using OwnID.Flow.Adapters; using OwnID.Services; namespace OwnID.Commands.MagicLink { public class SendMagicLinkCommand { private readonly ICacheItemRepository _cacheItemRepository; private readonly IEmailService _emailService; private readonly IIdentitiesProvider _identitiesProvider; private readonly IMagicLinkConfiguration _magicLinkConfiguration; private readonly IOwnIdCoreConfiguration _ownIdCoreConfiguration; private readonly ILocalizationService _localizationService; private readonly TimeSpan _tokenExpiration; private readonly IUserHandlerAdapter _userHandlerAdapter; public SendMagicLinkCommand(ICacheItemRepository cacheItemRepository, IUserHandlerAdapter userHandlerAdapter, IIdentitiesProvider identitiesProvider, IEmailService emailService, IMagicLinkConfiguration magicLinkConfiguration, IOwnIdCoreConfiguration ownIdCoreConfiguration, ILocalizationService localizationService) { _cacheItemRepository = cacheItemRepository; _userHandlerAdapter = userHandlerAdapter; _identitiesProvider = identitiesProvider; _emailService = emailService; _magicLinkConfiguration = magicLinkConfiguration; _ownIdCoreConfiguration = ownIdCoreConfiguration; _localizationService = localizationService; _tokenExpiration = TimeSpan.FromMilliseconds(magicLinkConfiguration.TokenLifetime); } public async Task<MagicLinkResponse> ExecuteAsync(string email) { var did = await _userHandlerAdapter.GetUserIdByEmail(email); if (string.IsNullOrEmpty(did)) throw new CommandValidationException($"No user was found with email '{email}'"); var result = new MagicLinkResponse(); var context = _identitiesProvider.GenerateContext(); var token = _identitiesProvider.GenerateMagicLinkToken(); await _cacheItemRepository.CreateAsync(new CacheItem { ChallengeType = ChallengeType.Login, Context = context, Payload = token, DID = did, Status = CacheItemStatus.Finished }, _tokenExpiration); if (_magicLinkConfiguration.SameBrowserUsageOnly) { result.CheckTokenKey = $"ownid-mlc-{context}"; result.CheckTokenValue = GetCheckToken(context, token, did); result.CheckTokenLifetime = _magicLinkConfiguration.TokenLifetime; } var userName = await _userHandlerAdapter.GetUserNameAsync(did); var link = new UriBuilder(_magicLinkConfiguration.RedirectUrl); var query = HttpUtility.ParseQueryString(link.Query); query["ownid-mtkn"] = token; query["ownid-ctxt"] = context; link.Query = query.ToString() ?? string.Empty; var subject = string.Format(_localizationService.GetLocalizedString("Email_MagicLink_Subject"), _ownIdCoreConfiguration.Name); var body = _localizationService.GetLocalizedString("Email_MagicLink_Body") .Replace("{userName}", userName) .Replace("{link}", link.Uri.ToString()); await _emailService.SendAsync(email, subject, body, true, userName); return result; } public static string GetCheckToken(string context, string token, string did) { return $"{context}::{token}::{did}".GetSha256(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using SBA_BACKEND.Domain.Models; using SBA_BACKEND.Domain.Services.Communications; using SBA_BACKEND.Domain.Services; using SBA_BACKEND.Domain.Persistence.Repositories; namespace SBA_BACKEND.Services { public class CustomerService : ICustomerService { private readonly ICustomerRepository _customerRepository; private readonly IUserRepository userRepository; private IUnitOfWork _unitOfWork; public CustomerService(ICustomerRepository object1, IUnitOfWork object2, IUserRepository userRepository) { this._customerRepository = object1; this._unitOfWork = object2; this.userRepository = userRepository; } public async Task<CustomerResponse> DeleteAsync(int id) { var existingCustomer = await _customerRepository.FindById(id); if (existingCustomer == null) return new CustomerResponse("Customer not found"); try { _customerRepository.Remove(existingCustomer); await _unitOfWork.CompleteAsync(); return new CustomerResponse(existingCustomer); } catch (Exception ex) { return new CustomerResponse($"An error ocurred while deleting the customer: {ex.Message}"); } } public async Task<CustomerResponse> GetByIdAsync(int id) { var existingCustomer = await _customerRepository.FindById(id); if (existingCustomer == null) return new CustomerResponse("Customer not found"); return new CustomerResponse(existingCustomer); } public async Task<IEnumerable<Customer>> ListAsync() { return await _customerRepository.ListAsync(); } public async Task<CustomerResponse> SaveAsync(int userId, Customer customer) { var existingUser = await userRepository.FindById(userId); if (existingUser == null) return new CustomerResponse("User not found"); try { customer.UserId = userId; await _customerRepository.AddAsync(customer); await _unitOfWork.CompleteAsync(); return new CustomerResponse(customer); } catch (Exception e) { return new CustomerResponse($"An error ocurred while saving the customer: {e.Message}"); } } public async Task<CustomerResponse> UpdateAsync(int id, Customer customer) { var existingCustomer = await _customerRepository.FindById(id); if (existingCustomer == null) return new CustomerResponse("Customer not found"); existingCustomer.Description = customer.Description; existingCustomer.ImageUrl = customer.ImageUrl; existingCustomer.FirstName = customer.FirstName; existingCustomer.LastName = customer.LastName; existingCustomer.PhoneNumber = customer.PhoneNumber; try { _customerRepository.Update(existingCustomer); await _unitOfWork.CompleteAsync(); return new CustomerResponse(existingCustomer); } catch (Exception ex) { return new CustomerResponse($"An error ocurred while updating the customer: {ex.Message}"); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MauiWrapPanel.DebugTool { /// <summary> /// Because VS17.2 have bug, can't run net6-ios, so i add this for debug info to show at windows. /// When release, use Trace output log. /// </summary> internal class SimpleDebug { static MessageClient client = new MessageClient("192.168.0.144", 399); public static void WriteLine(string message) { #if __IOS__ client.SendMessage(message + "~iOS" + $"~{DateTime.Now}" + "\n");//~ split Log,Platform,Time #elif ANDROID client.SendMessage(message + "~Android" + $"~{DateTime.Now}" + "\n");//~ split Log,Platform,Time #else client.SendMessage(message + "~Windows" + $"~{DateTime.Now}" + "\n");//~ split Log,Platform,Time #endif #if DEBUG System.Diagnostics.Debug.WriteLine(message); #else Trace.WriteLine(message, "SharpConstraintLayout"); #endif } public static void WriteLine(string tag, string message) { WriteLine($"{tag}: {message}"); } } }
using System.Collections.Generic; using System.Threading.Tasks; namespace AteraAPI.V3.Interfaces { /// <summary> /// Defines the API endpoint for tickets. /// </summary> public interface ITicketApiEndpoint : IReadCreateApiEndpoint<ITicket>, IReadUpdateApiEndpoint<ITicket>, IReadDeleteApiEndpoint<ITicket> { /// <summary> /// Gets resolved and closed tickets. /// </summary> /// <returns></returns> IEnumerable<ITicket> GetResolvedAndClosed(); /// <summary> /// Gets the billable duration for a ticket. /// </summary> /// <param name="ticketId"></param> /// <returns></returns> IDuration GetBillableDuration(int ticketId); /// <summary> /// Gets the non-billable duration for a ticket. /// </summary> /// <param name="ticketId"></param> /// <returns></returns> IDuration GetNonBillableDuration(int ticketId); /// <summary> /// Gets the work hours for a ticket. /// </summary> /// <param name="ticketId"></param> /// <returns></returns> IWorkHours GetWorkHours(int ticketId); /// <summary> /// Gets work hour records for a ticket. /// </summary> /// <param name="ticketId"></param> /// <returns></returns> IEnumerable<IWorkHourRecord> GetWorkHourRecords(int ticketId); /// <summary> /// Gets comments for a ticket. /// </summary> /// <param name="ticketId"></param> /// <returns></returns> IEnumerable<IComment> GetComments(int ticketId); /// <summary> /// Gets resolved and closed tickets. /// </summary> /// <returns></returns> Task<IEnumerable<ITicket>> GetResolvedAndClosedAsync(); /// <summary> /// Gets the billable duration for a ticket. /// </summary> /// <param name="ticketId"></param> /// <returns></returns> Task<IDuration> GetBillableDurationAsync(int ticketId); /// <summary> /// Gets the non-billable duration for a ticket. /// </summary> /// <param name="ticketId"></param> /// <returns></returns> Task<IDuration> GetNonBillableDurationAsync(int ticketId); /// <summary> /// Gets the work hours for a ticket. /// </summary> /// <param name="ticketId"></param> /// <returns></returns> Task<IWorkHours> GetWorkHoursAsync(int ticketId); /// <summary> /// Gets work hour records for a ticket. /// </summary> /// <param name="ticketId"></param> /// <returns></returns> Task<IEnumerable<IWorkHourRecord>> GetWorkHourRecordsAsync(int ticketId); /// <summary> /// Gets comments for a ticket. /// </summary> /// <param name="ticketId"></param> /// <returns></returns> Task<IEnumerable<IComment>> GetCommentsAsync(int ticketId); } }
using Microsoft.AspNetCore.Mvc; namespace $safeprojectname$.Controllers { [Route("api/[controller]")] [ApiController] public class EmployeeController : ControllerBase { /// <summary> /// Retrieve the employee by their ID. /// </summary> /// <param name="id">The ID of the desired Employee</param> /// <returns>A string status</returns> [HttpGet] [Route("{id}")] public ActionResult<string> GetByID(int id) { return "Found Employee"; } /// <summary> /// Returns a group of Employees matching the given first and last names. /// </summary> /// <remarks> /// Here is a sample remarks placeholder. /// </remarks> /// <param name="firstName">The first name to search for</param> /// <param name="lastName">The last name to search for</param> /// <returns>A string status</returns> [HttpGet] [Route("byname/{firstName}/{lastName}")] public ActionResult<string> GetByName(string firstName, string lastName) { return "Found another employee"; } } }
/* * ITSE 1430 * Shahla Ally * Final: 12/13/2017 */ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MovieLib { /// <summary>Provides helpers for validating objects.</summary> public static class ObjectValidator { /// <summary>Validates an object.</summary> /// <param name="value">The value to validate.</param> public static void ValidateObject ( IValidatableObject value ) { Validator.ValidateObject(value, new ValidationContext(value), true); } /// <summary>Validates an object and returns the results.</summary> /// <param name="value">The value.</param> /// <returns>The validation results.</returns> public static IEnumerable<ValidationResult> TryValidateObject ( IValidatableObject value ) { var results = new List<ValidationResult>(); if (!Validator.TryValidateObject(value, new ValidationContext(value), results)) return results; return Enumerable.Empty<ValidationResult>(); } } }
using System; using System.Text.Json.Serialization; using System.Text.Json; namespace JsonExtended.Serialization { // var options = new JsonSerializerOptions(JsonSerializerDefaults.Web); // options.Converters.Add(new DateOnlyConverter()); // options.Converters.Add(new TimeOnlyConverter()); public class DateOnlyConverter : JsonConverter<DateOnly> { private readonly string serializationFormat; public DateOnlyConverter() : this(null) { } public DateOnlyConverter(string serializationFormat) { this.serializationFormat = serializationFormat ?? "yyyy-MM-dd"; } public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var value = reader.GetString(); return DateOnly.Parse(value!); } public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString(serializationFormat)); } }
using Barista.Shared.Entities.Enemy; using Barista.Shared.Entities.Hero; namespace Barista.Shared.Logic.UseCases { public interface IMoveEnemyTowardsHeroUseCase { bool CanMove(EnemyEntity enemyEntity, HeroEntity heroEntity, int range); void Move(EnemyEntity enemyEntity, HeroEntity heroEntity, int range); } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace ClienteService { [ServiceContract] public interface IClienteService { [OperationContract] String Insert(Cliente cliente); [OperationContract] string Update(Cliente cliente); [OperationContract] Cliente FindCliente(int dni); [OperationContract] String Delete(int dni); [OperationContract] List<Cliente> ListarClientes(); } [DataContract] public class Cliente { int clientes_id; string username; string userpass; string nombre; string apellidos; string email; string direccion; string dni; string telefono; [DataMember] public int Clientes_id { get { return clientes_id; } set { clientes_id = value; } } [DataMember] public String Username { get { return username; } set { username = value; } } [DataMember] public String Userpass { get { return userpass; } set { userpass = value; } } [DataMember] public String Nombre { get { return nombre; } set { nombre = value; } } [DataMember] public String Apellidos { get { return apellidos; } set { apellidos = value; } } [DataMember] public String Email { get { return email; } set { email = value; } } [DataMember] public String Direccion { get { return direccion; } set { direccion = value; } } [DataMember] public String Dni { get { return dni; } set { dni = value; } } [DataMember] public String Telefono { get { return telefono; } set { telefono = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Reader.SDK.Exception { public static class ReaderError { public const UInt32 INPUT_FILE_NOT_SUPPORTED = 0x20000000; public const UInt32 INPUT_FILE_OPEN_FAILED = 0x20000001; public const UInt32 INPUT_FILE_FORMAT_INVALID = 0x20000002; public const UInt32 ERROR_WHILE_READING = 0x20000003; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace uk.andyjohnson.ElephantBackup { /// <summary> /// Represents the result of a backup operation. /// </summary> public class BackupResult { /// <summary> /// Overall success/failure. /// </summary> public bool Success { get; set; } /// <summary> /// start time of backup. /// </summary> public DateTime StartTime { get; set; } /// <summary> /// End time of backup. /// </summary> public DateTime EndTime { get; set; } /// <summary> /// Time taken for backup. /// </summary> public TimeSpan Timetaken { get { return EndTime - StartTime; } } /// <summary> /// Number of byts copied. /// </summary> public long BytesCopied { get; set; } /// <summary> /// Number of files copied. /// </summary> public long FilesCopied { get; set; } /// <summary> /// Number of directories copied. /// </summary> public long DirectoriesCopied { get; set; } /// <summary> /// Number of files skipped. /// </summary> public long FilesSkipped { get; set; } /// <summary> /// Number of directories skipped. /// </summary> public long DirectoriesSkipped { get; set; } /// <summary> /// path to log file. /// </summary> public string LogFilePath { get; set; } /// <summary> /// Exceptin causing filure, or null on success. /// </summary> public Exception Exception { get; set; } } }
namespace PeNet.Structures.MetaDataTables { public class AssemblyRefOS : AbstractTable { public AssemblyRefOS(byte[] buff, uint offset, HeapSizes heapSizes, IndexSize indexSizes) : base(buff, offset, heapSizes, indexSizes) { OSPlatformID = ReadSize(4); OSMajorVersion = ReadSize(4); OSMinorVersion = ReadSize(4); AssemblyRef = ReadSize(IndexSizes[Index.AssemblyRef]); } public uint OSPlatformID { get; } public uint OSMajorVersion { get; } public uint OSMinorVersion { get; } public uint AssemblyRef { get; } } }
using System.Collections.Generic; using System.Threading.Tasks; using Tyres.Service.Constants; using Tyres.Shared.DataTransferObjects.Users; namespace Tyres.Service.Interfaces { public interface IUserService { Task<List<UserSummaryDTO>> AllAsync(int page = PageConstants.DefaultPage); } }
using UnityEngine; using System.Collections.Generic; using RtMidi.LowLevel; sealed class MidiInTest : MonoBehaviour { #region Private members MidiProbe _probe; List<MidiInPort> _ports = new List<MidiInPort>(); // Does the port seem real or not? // This is mainly used on Linux (ALSA) to filter automatically generated // virtual ports. bool IsRealPort(string name) { return !name.Contains("Through") && !name.Contains("RtMidi"); } // Scan and open all the available output ports. void ScanPorts() { for (var i = 0; i < _probe.PortCount; i++) { var name = _probe.GetPortName(i); Debug.Log("MIDI-in port found: " + name); _ports.Add(IsRealPort(name) ? new MidiInPort(i) { OnNoteOn = (byte channel, byte note, byte velocity) => Debug.Log(string.Format("{0} [{1}] On {2} ({3})", name, channel, note, velocity)), OnNoteOff = (byte channel, byte note) => Debug.Log(string.Format("{0} [{1}] Off {2}", name, channel, note)), OnControlChange = (byte channel, byte number, byte value) => Debug.Log(string.Format("{0} [{1}] CC {2} ({3})", name, channel, number, value)) } : null ); } } // Close and release all the opened ports. void DisposePorts() { foreach (var p in _ports) p?.Dispose(); _ports.Clear(); } #endregion #region MonoBehaviour implementation void Start() { _probe = new MidiProbe(MidiProbe.Mode.In); } void Update() { // Rescan when the number of ports changed. if (_ports.Count != _probe.PortCount) { DisposePorts(); ScanPorts(); } // Process queued messages in the opened ports. foreach (var p in _ports) p?.ProcessMessages(); } void OnDestroy() { _probe?.Dispose(); DisposePorts(); } #endregion }
namespace Bonsai.Shaders.Rendering { static class ShaderConstants { public static readonly string ModelViewMatrix = "modelview"; public static readonly string ProjectionMatrix = "projection"; public static readonly string NormalMatrix = "normalMatrix"; public static readonly string Texture = "texture"; public static readonly string BumpScaling = GetUniformName(nameof(Assimp.Material.BumpScaling)); public static readonly string ColorAmbient = GetUniformName(nameof(Assimp.Material.ColorAmbient)); public static readonly string ColorDiffuse = GetUniformName(nameof(Assimp.Material.ColorDiffuse)); public static readonly string ColorEmissive = GetUniformName(nameof(Assimp.Material.ColorEmissive)); public static readonly string ColorReflective = GetUniformName(nameof(Assimp.Material.ColorReflective)); public static readonly string ColorSpecular = GetUniformName(nameof(Assimp.Material.ColorSpecular)); public static readonly string ColorTransparent = GetUniformName(nameof(Assimp.Material.ColorTransparent)); public static readonly string Opacity = GetUniformName(nameof(Assimp.Material.Opacity)); public static readonly string Reflectivity = GetUniformName(nameof(Assimp.Material.Reflectivity)); public static readonly string Shininess = GetUniformName(nameof(Assimp.Material.Shininess)); public static readonly string ShininessStrength = GetUniformName(nameof(Assimp.Material.ShininessStrength)); static string GetUniformName(string resourceName) { if (resourceName.Length < 1) return resourceName; if (resourceName.Length == 1) return resourceName.ToLowerInvariant(); return resourceName.Substring(0, 1).ToLowerInvariant() + resourceName.Substring(1); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class IndexModel : Basemodel { //public int index; public Color color; public IndexModel(Color i) { color = i; } public IndexModel() { color = Color.red; } }
using System; using System.Collections.Generic; namespace Orleans.Runtime { internal class RuntimeTypeHandlerEqualityComparer : IEqualityComparer<RuntimeTypeHandle> { public static RuntimeTypeHandlerEqualityComparer Instance { get; } = new RuntimeTypeHandlerEqualityComparer(); RuntimeTypeHandlerEqualityComparer() { } public int GetHashCode(RuntimeTypeHandle handle) => handle.GetHashCode(); public bool Equals(RuntimeTypeHandle first, RuntimeTypeHandle second) => first.Equals(second); } }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TP.Framework.Tests { [TestClass] public class TPAttributePackageTests { private TPAttribute health; private TPModifier healthIncreaser; private void Reset() { health = new TPAttribute(100); healthIncreaser = new TPModifier(ModifierType.FlatIncrease, 10); } [TestMethod] public void AddModifier() { Reset(); Assert.AreEqual(100, health.Value); health.Modifiers.Add(healthIncreaser); Assert.AreEqual(110, health.Value); } [TestMethod] public void RemoveModifier() { Reset(); health.Modifiers.Add(healthIncreaser); bool removed = health.Modifiers.Remove(healthIncreaser); Assert.IsTrue(removed); Assert.AreEqual(100, health.Value); } [TestMethod] public void HasModifier() { Reset(); bool has = false; has = health.Modifiers.HasModifier(healthIncreaser); Assert.IsFalse(has); health.Modifiers.Add(healthIncreaser); has = health.Modifiers.HasModifier(healthIncreaser); Assert.IsTrue(has); health.Modifiers.Remove(healthIncreaser); has = health.Modifiers.HasModifier(healthIncreaser); Assert.IsFalse(has); } [TestMethod] public void Compare() { Reset(); int compare = health.Modifiers.Compare(healthIncreaser, healthIncreaser); Assert.AreEqual(0, compare); compare = health.Modifiers.Compare(healthIncreaser, new TPModifier(ModifierType.FlatIncrease, 10, 1)); Assert.AreEqual(-1, compare); compare = health.Modifiers.Compare(healthIncreaser, new TPModifier(ModifierType.FlatIncrease, 10, -1)); Assert.AreEqual(1, compare); } [TestMethod] public void PrioritySorting() { Reset(); TPModifier healthIncreaserII = new TPModifier(ModifierType.Percentage, 0.5f, 1); health.Modifiers.Add(healthIncreaser); health.Modifiers.Add(healthIncreaserII); Assert.AreEqual(165, health.Value); health.Modifiers.ChangeModifier(healthIncreaserII, new TPModifier(ModifierType.Percentage, 0.5f, -1)); Assert.AreEqual(160, health.Value); } } }
using System; using System.Collections.Generic; namespace Structure { public class Map { private readonly Dictionary<Type, object> _layers = new Dictionary<Type, object>(); /// <summary> /// Add layer to map. Second typed parameter is a type of layer cell /// </summary> /// <typeparam name="TLayer"></typeparam> /// <typeparam name="TCell"></typeparam> /// <param name="layer"></param> public void AddLayer<TLayer, TCell>(TLayer layer) where TLayer : Layer<TCell> { _layers.Add(typeof(TLayer), layer); } /// <summary> /// Check if there is a layer in the map /// </summary> /// <typeparam name="TLayer"></typeparam> /// <typeparam name="TCell"></typeparam> /// <returns></returns> public bool HasLayer<TLayer, TCell>() where TLayer : Layer<TCell> { return _layers.ContainsKey(typeof(TLayer)); } /// <summary> /// Get layer by type (type is key) /// </summary> /// <typeparam name="TLayer"></typeparam> /// <typeparam name="TCell"></typeparam> /// <returns></returns> public TLayer GetLayer<TLayer, TCell>() where TLayer : Layer<TCell> { return _layers[typeof(TLayer)] as TLayer; } } }
using System; namespace Epam.Task3.Round { public class Program { public static void Main(string[] args) { Round round = new Round(); Console.WriteLine("Enter X coordinate: "); round.X = int.Parse(Console.ReadLine()); Console.WriteLine("Enter Y coordinate: "); round.Y = int.Parse(Console.ReadLine()); Console.WriteLine("Enter a radius: "); while (true) { Console.WriteLine("Enter a radius: "); try { round.Radius = int.Parse(Console.ReadLine()); break; } catch (ArgumentException e) { Console.WriteLine(e.Message); } } Console.WriteLine("The area equals: {0}", round.Area); Console.WriteLine("The length equals: {0}", round.Length); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using Microsoft.Its.Domain.Sql; namespace Microsoft.Its.Domain.Testing { public static class ReadModelDbContextExtensions { public static void SetReadModelTrackingTo(this DbContext db, long toEventId, params object[] addForProjectors) { // forward all existing read model tracking foreach (var readModelInfo in db.Set<ReadModelInfo>()) { readModelInfo.CurrentAsOfEventId = toEventId; } foreach (var projector in addForProjectors) { var projectorName = ReadModelInfo.NameForProjector(projector); db.Set<ReadModelInfo>().AddOrUpdate( i => i.Name, new ReadModelInfo { Name = projectorName, CurrentAsOfEventId = toEventId }); } db.SaveChanges(); } } }
using System; using Terraria.ModLoader.IO; using Arcana.Reference; namespace Arcana.Spells.Elements { public class Arcane : Element { public Arcane() : base(Constants.Elements.ARCANE) { } public static readonly Func<TagCompound, Arcane> DESERIALIZER = Load<Arcane>; } }
using System.Windows; using Microsoft.Phone.Controls; using Coding4Fun.Toolkit.Controls; namespace Coding4Fun.Toolkit.Test.WindowsPhone.Samples { public partial class Slider : PhoneApplicationPage { public Slider() { InitializeComponent(); } private void ResultSlider_ValueChanged(object sender, PropertyChangedEventArgs<double> e) { SliderResult.Text = e.NewValue.ToString(); } private void ResultWithStepSlider_ValueChanged(object sender, PropertyChangedEventArgs<double> e) { SliderWithStepResult.Text = e.NewValue.ToString(); } private void Button_Click(object sender, RoutedEventArgs e) { sliderVisTest.Visibility = (sliderVisTest.Visibility == Visibility.Visible) ? Visibility.Collapsed : Visibility.Visible; } } }
/*=============================================================================== Copyright (C) 2020 Immersal Ltd. All Rights Reserved. This file is part of the Immersal SDK. The Immersal SDK cannot be copied, distributed, or made available to third-parties for commercial purposes without written permission of Immersal Ltd. Contact sdk@immersal.com for licensing requests. ===============================================================================*/ #if (UNITY_IOS || PLATFORM_ANDROID) && !UNITY_EDITOR using System.Runtime.InteropServices; using UnityEngine; namespace Immersal { public class NativeBindings { #if UNITY_IOS [DllImport("__Internal")] public static extern void startLocation(); [DllImport("__Internal")] public static extern void stopLocation(); [DllImport("__Internal")] public static extern double getLatitude(); [DllImport("__Internal")] public static extern double getLongitude(); [DllImport("__Internal")] public static extern double getAltitude(); [DllImport("__Internal")] public static extern double getHorizontalAccuracy(); [DllImport("__Internal")] public static extern double getVerticalAccuracy(); [DllImport("__Internal")] public static extern bool locationServicesEnabled(); #elif PLATFORM_ANDROID static AndroidJavaClass obj = new AndroidJavaClass("com.immersal.nativebindings.Main"); #endif public static bool StartLocation() { if (!Input.location.isEnabledByUser) { return false; } #if UNITY_IOS startLocation(); #elif PLATFORM_ANDROID obj.CallStatic("startLocation"); #endif return true; } public static void StopLocation() { #if UNITY_IOS stopLocation(); #elif PLATFORM_ANDROID obj.CallStatic("stopLocation"); #endif } public static double GetLatitude() { #if UNITY_IOS return getLatitude(); #elif PLATFORM_ANDROID return obj.CallStatic<double>("getLatitude"); #endif } public static double GetLongitude() { #if UNITY_IOS return getLongitude(); #elif PLATFORM_ANDROID return obj.CallStatic<double>("getLongitude"); #endif } public static double GetAltitude() { #if UNITY_IOS return getAltitude(); #elif PLATFORM_ANDROID return obj.CallStatic<double>("getAltitude"); #endif } public static double GetHorizontalAccuracy() { #if UNITY_IOS return getHorizontalAccuracy(); #elif PLATFORM_ANDROID return obj.CallStatic<double>("getHorizontalAccuracy"); #endif } public static double GetVerticalAccuracy() { #if UNITY_IOS return getVerticalAccuracy(); #elif PLATFORM_ANDROID return obj.CallStatic<double>("getVerticalAccuracy"); #endif } public static bool LocationServicesEnabled() { #if UNITY_IOS return locationServicesEnabled(); #elif PLATFORM_ANDROID return obj.CallStatic<bool>("locationServicesEnabled"); #endif } } } #endif
namespace Axiverse.Interface.Graphics { /// <summary> /// Interface for resources which need to be disposed and recreated when the presenter is /// resized. /// </summary> public interface IPresenterResource { /// <summary> /// Recreate resources bound to the presenter. /// </summary> void Recreate(); /// <summary> /// Dispose resources bound to the presenter. /// </summary> void Dispose(); } }
using System; using System.Web.UI; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using TypeMock.ArrangeActAssert; using Nucleo.Web.Templates; namespace Nucleo.Web.FormControls { [TestClass] public class FormItemSectionRendererTest { [TestMethod] public void RenderingTemplateWorksOK() { //Arrange var render = new FormItemSectionRenderer(); var template = Isolate.Fake.Instance<ControlElementTemplate>(); Isolate.WhenCalled(() => template.ReturnsContent).WillReturn(true); Isolate.WhenCalled(() => template.GetTemplate()).WillReturn("Test"); var ctl = new FormItemSection { Content = template, Page = new Page() }; render.Initialize(ctl, ctl.Page); //Act var writer = new StringControlWriter(); render.Render(writer); //Assert Assert.AreEqual("Test", writer.ToString()); } } }
@using System.Web.Optimization <!DOCTYPE html> <html data-ng-app="MicroBlogApp"> <head> <meta content="IE=edge, chrome=1" http-equiv="X-UA-Compatible" /> <title>MicroBlog</title> @Styles.Render("~/Content/Css") </head> <body> <div> <nav class="navbar navbar-default navbar-fixed-top" role="navigation" data-ng-controller="indexController"> <div class="container"> <div class="navbar-header"> <button class="btn btn-success navbar-toggle" data-ng-click="navbarExpanded = !navbarExpanded"> <span class="glyphicon glyphicon-chevron-down"></span> </button> <a class="navbar-brand" href="#/">Micro Blog</a> </div> <div class="collapse navbar-collapse" data-collapse="!navbarExpanded"> <ul class="nav navbar-nav navbar-right"> <li data-ng-hide="!authentication.isAuth"><a href="#">Welcome {{authentication.userName}}</a></li> <li data-ng-hide="!authentication.isAuth"><a href="" data-ng-click="logOut()">Logout</a></li> <li data-ng-hide="authentication.isAuth"><a href="#/login">Login</a></li> <li data-ng-hide="authentication.isAuth"><a href="#/signup">Sign Up</a></li> </ul> </div> </div> </nav> <div class="jumbotron"> <div class="container"> <div class="page-header text-center"> <h1>MicroBlogging Demo App</h1> </div> <p class="text-center"> Demo app using AngularJS, using OAuth bearer token authentication, ASP.NET Web API 2, OWIN middleware, and ASP.NET Identity for generating tokens and registering users. </p> </div> </div> <div class="container"> <add-post></add-post> <div data-ng-view=""> </div> </div> <div id="footer" class="navbar navbar-fixed-bottom"> <div class="container"> <div class="row"> <div class="col-md-12"> <p class="text-muted"> Created by Will Blankenship &copy; @DateTime.Now.Year.&nbsp;&nbsp; GitHub:&nbsp;<a target="_blank" href="http://github.com/wblanken">wblanken</a>,&nbsp; Twitter:&nbsp;<a target="_blank" href="http://twitter.com/blanks821">@@blanks821</a> </p> </div> </div> <div class="row"> <div class="col-md-6"> <p class="text-muted"></p> </div> </div> </div> </div> </div> @Scripts.Render("~/bundles/vendors") @Scripts.Render("~/bundles/app") </body> </html>
using System.Security.Cryptography; using System; using System.Text; public class Encryption { public static string Encrypt(string unencrypt,string key) { //密钥 byte[] keyArray = Encoding.UTF8.GetBytes(key); //待加密明文数组 byte[] UnencryptArray = Encoding.UTF8.GetBytes(unencrypt); //Rijndael加密算法 RijndaelManaged rDel = new RijndaelManaged { Key = keyArray, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; ICryptoTransform cTransform = rDel.CreateEncryptor(); //返回加密后的密文 byte[] resultArray = cTransform.TransformFinalBlock(UnencryptArray, 0, UnencryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } public static string Dencrypt(string encryted,string key) { //解密密钥 byte[] keyArray = Encoding.UTF8.GetBytes(key); //待解密密文数组 byte[] EncryptArray = Convert.FromBase64String(encryted); //Rijndael解密算法 RijndaelManaged rDel = new RijndaelManaged { Key = keyArray, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; ICryptoTransform cTransform = rDel.CreateDecryptor(); //返回解密后的明文 byte[] resultArray = cTransform.TransformFinalBlock(EncryptArray, 0, EncryptArray.Length); return Encoding.UTF8.GetString(resultArray); } }
using System.Collections.Generic; using SharpGLTF.Schema2; namespace Toe.ContentPipeline.GLTFSharp { public class ReaderContext { public ModelRoot ModelRoot { get; set; } public ContentContainer Container { get; set; } public IReadOnlyList<IImageAsset> Images { get; set; } public IReadOnlyList<IMesh> Meshes { get; set; } public IReadOnlyList<IMaterialAsset> Materials { get; set; } public IReadOnlyList<INodeAsset> Nodes { get; set; } public IReadOnlyList<ICameraAsset> Cameras { get; set; } public IReadOnlyList<ILightAsset> Lights { get; set; } } }
using System; namespace IR { public abstract class ValueInteractor<R, V> : Interactor<R>, IValueInteractor<V> where R : ValueRepository<V>, new() { public virtual event Action<V> Changed; public virtual V Value { get => Repository.Value; set { if (Repository.Value.Equals(value)) return; Repository.Value = value; Changed?.Invoke(value); } } } }
namespace Discord.API.Client.GatewaySocket { public class ChannelUpdateEvent : Channel { } }
using System; using System.Windows; using System.Windows.Controls; using System.Reflection; using Microsoft.Xna.Framework; namespace System.Windows.Media.Animation { public class ValueChangedEventArgs : EventArgs { public ValueChangedEventArgs ( float value ) : base ( ) { this.Value = value; } public float Value { get; private set; } } public delegate void ValueChangedEventHandler ( object sender, ValueChangedEventArgs e ); public abstract class SingleAnimationBase : IAnimationBase { public SingleAnimationBase ( ) { State = AnimationState.Stopped; } public event EventHandler<EventArgs> Completed; public TimeSpan BeginTime { get; set; } public TimeSpan Duration { get; set; } public AnimationState State { get; protected set; } public bool AutoReverse { get; set; } public int RepeatBehavior { get; set; } protected DateTime StartTime { get; private set; } protected TimeSpan CurrentTime { get; private set; } protected float ComputeValue ( float from, float to, float v ) { float delta = 0f; if ( from < to ) delta = to - from; else delta = -( from - to ); return from + ( delta * v ); } public abstract float GetCurrentValue ( ); public void Begin ( ) { StartTime = DateTime.UtcNow; if ( reverse ) CurrentTime = this.Duration; else CurrentTime = TimeSpan.Zero; State = AnimationState.Started; } public virtual void Begin ( TimeSpan beginTime ) { this.BeginTime = beginTime; this.Begin ( ); } public virtual void Stop ( ) { repeatIndex = 0; State = AnimationState.Stopped; reverse = false; } public virtual void Pause ( ) { State = AnimationState.Paused; } public void Resume ( ) { State = AnimationState.Started; } public void Update ( GameTime gameTime ) { var ctm = DateTime.UtcNow; if ( State == AnimationState.Started ) { var time = ctm - this.StartTime - this.BeginTime; if ( reverse ) time = this.Duration - time; if ( time.Ticks > 0 ) { if ( time > this.Duration ) { this.CurrentTime = this.Duration; this.UpdateTargetProperty ( ); if ( this.AutoReverse ) { reverse = true; this.Begin ( ); } else { if ( repeatIndex < RepeatBehavior - 1 ) { repeatIndex++; this.Begin ( ); } else { repeatIndex = 0; State = AnimationState.Stopped; this.RaiseCompletedEvent ( ); } } } else this.CurrentTime = time; } else { this.CurrentTime = TimeSpan.Zero; if ( reverse ) { if ( repeatIndex < RepeatBehavior - 1 ) { repeatIndex++; reverse = false; this.Begin ( ); } else { repeatIndex = 0; State = AnimationState.Stopped; reverse = false; this.RaiseCompletedEvent ( ); } } } } if ( lastTime != CurrentTime ) { lastTime = CurrentTime; //System.Diagnostics.Debug.WriteLine ( this.GetCurrentValue ( ) ); this.UpdateTargetProperty ( ); } //base.Update ( gameTime ); } void UpdateTargetProperty ( ) { if ( targetPropertyInfo == null && !propertyInfoChecked ) { target = Storyboard.GetTarget ( this ); targetProperty = Storyboard.GetTargetProperty ( this ); if ( target != null && targetProperty != null ) { targetPropertyInfo = target .GetType ( ) .GetProperty ( targetProperty ); } propertyInfoChecked = true; } if ( targetPropertyInfo != null ) { targetPropertyInfo.SetValue ( target, GetCurrentValue ( ), null ); } } protected void RaiseCompletedEvent ( ) { if ( this.Completed != null ) this.Completed ( this, EventArgs.Empty ); } private int repeatIndex; private bool reverse; private bool propertyInfoChecked; private TimeSpan lastTime; private Control target; private String targetProperty; private PropertyInfo targetPropertyInfo; } public enum AnimationState { Started, Paused, Stopped, } }
using Jotunn.Utils; namespace AsgardLegacy { class SE_Ability3_CD : SE_Stats { public SE_Ability3_CD() { base.name = "SE_Ability3_CD"; base.m_ttl = 2f; } public override bool CanAdd(Character character) { return character.IsPlayer(); } } }
using System.Diagnostics.CodeAnalysis; using HarmonyLib; using SolastaCommunityExpansion.Features; using SolastaModApi.Extensions; namespace SolastaCommunityExpansion.Patches.CustomFeatures { [HarmonyPatch(typeof(GameLocationCharacter), "StartBattleTurn")] [SuppressMessage("Minor Code Smell", "S101:Types should be named in PascalCase", Justification = "Patch")] internal static class GameLocationCharacter_StartBattleTurn { internal static void Postfix(GameLocationCharacter __instance) { if (!__instance.Valid) { return; } var character = __instance.RulesetCharacter; var listeners = character?.GetSubFeaturesByType<ICharacterTurnStartListener>(); if (listeners == null) { return; } foreach (var listener in listeners) { listener.OnChracterTurnStarted(__instance); } } } [HarmonyPatch(typeof(GameLocationCharacter), "EndBattleTurn")] [SuppressMessage("Minor Code Smell", "S101:Types should be named in PascalCase", Justification = "Patch")] internal static class GameLocationCharacter_EndBattleTurn { internal static void Postfix(GameLocationCharacter __instance) { if (!__instance.Valid) { return; } var character = __instance.RulesetCharacter; var listeners = character?.GetSubFeaturesByType<ICharacterTurnEndListener>(); if (listeners == null) { return; } foreach (var listener in listeners) { listener.OnChracterTurnEnded(__instance); } } } [HarmonyPatch(typeof(GameLocationCharacter), "StartBattle")] [SuppressMessage("Minor Code Smell", "S101:Types should be named in PascalCase", Justification = "Patch")] internal static class GameLocationCharacter_StartBattle { internal static void Postfix(GameLocationCharacter __instance, bool surprise) { if (!__instance.Valid) { return; } var character = __instance.RulesetCharacter; var listeners = character?.GetSubFeaturesByType<ICharacterBattlStartedListener>(); if (listeners == null) { return; } foreach (var listener in listeners) { listener.OnChracterBattleStarted(__instance, surprise); } } } [HarmonyPatch(typeof(GameLocationCharacter), "EndBattle")] [SuppressMessage("Minor Code Smell", "S101:Types should be named in PascalCase", Justification = "Patch")] internal static class GameLocationCharacter_EndBattle { internal static void Postfix(GameLocationCharacter __instance) { if (!__instance.Valid) { return; } var character = __instance.RulesetCharacter; var listeners = character?.GetSubFeaturesByType<ICharacterBattlEndedListener>(); if (listeners == null) { return; } foreach (var listener in listeners) { listener.OnChracterBattleEnded(__instance); } } } }
namespace Pact.Palantir.Usecase { /// <summary> /// The base response. /// </summary> public abstract class BaseResponse { /// <summary> /// Response Code used to express the success or failure of a usecase. Base of all responses /// </summary> public ResponseCode Code { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Demo04.Models; using Gods.Foundation; namespace Demo04.ViewModels { public class FileInfoViewModel : NotificationObject { public FileInfoEntity FileInfoEntity { get; private set; } public FileInfoViewModel(FileInfoEntity fileInfoEntity) { FileInfoEntity = fileInfoEntity; } public string Name { get { return FileInfoEntity.Name; } set { FileInfoEntity.Name = value; RaisePropertyChanged("Name"); } } public string Url { get { return FileInfoEntity.Url; } set { FileInfoEntity.Url = value; RaisePropertyChanged("Url"); } } public string LocalPath { get { return FileInfoEntity.LocalPath; } set { FileInfoEntity.LocalPath = value; RaisePropertyChanged("LocalPath"); } } private int _progressPercentage; public int ProgressPercentage { get { return _progressPercentage; } set { _progressPercentage = value; RaisePropertyChanged("ProgressPercentage"); } } private DownloadState _downloadState; public DownloadState DownloadState { get { return _downloadState; } set { _downloadState = value; RaisePropertyChanged("DownloadState"); } } // private long _fileTotalSize; // // public long FileTotalSize // { // get { return _fileTotalSize; } // set // { // _fileTotalSize = value; // RaisePropertyChanged("FileTotalSize"); // } // } // // private long _fileCurrentSize; // // public long FileCurrentSize // { // get { return _fileCurrentSize; } // set // { // _fileCurrentSize = value; // RaisePropertyChanged("FileCurrentSize"); // } // } public static FileInfoViewModel FromNewFileInfo(string fileName, string fileUrl, string localPath) { return new FileInfoViewModel(new FileInfoEntity() { Name = fileName, Url = fileUrl, LocalPath = localPath }); } public static FileInfoViewModel FromFileInfo(FileInfoEntity fileInfoEntity) { return new FileInfoViewModel(fileInfoEntity); } } }
namespace SharpDoop.Core.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class MapContextTests { [TestMethod] public void EmptyKeyValues() { MapContext<string, int> context = new MapContext<string, int>(); Assert.IsNotNull(context.KeyValues); Assert.AreEqual(0, context.KeyValues.Keys.Count); } [TestMethod] public void EmitKeyValue() { MapContext<string, int> context = new MapContext<string, int>(); context.Emit("word", 1); Assert.IsNotNull(context.KeyValues); Assert.AreEqual(1, context.KeyValues.Keys.Count); Assert.IsTrue(context.KeyValues.ContainsKey("word")); Assert.IsNotNull(context.KeyValues["word"]); Assert.AreEqual(1, context.KeyValues["word"].Count); Assert.AreEqual(1, context.KeyValues["word"][0]); } [TestMethod] public void EmitSaveKeyValues() { MapContext<string, int> context = new MapContext<string, int>(); context.Emit("a", 1); context.Emit("word", 1); context.Emit("is", 1); context.Emit("a", 1); context.Emit("word", 1); Assert.IsNotNull(context.KeyValues); Assert.AreEqual(3, context.KeyValues.Keys.Count); Assert.IsTrue(context.KeyValues.ContainsKey("word")); Assert.IsNotNull(context.KeyValues["word"]); Assert.AreEqual(2, context.KeyValues["word"].Count); Assert.AreEqual(1, context.KeyValues["word"][0]); Assert.AreEqual(1, context.KeyValues["word"][1]); Assert.IsTrue(context.KeyValues.ContainsKey("a")); Assert.IsNotNull(context.KeyValues["a"]); Assert.AreEqual(2, context.KeyValues["a"].Count); Assert.AreEqual(1, context.KeyValues["a"][0]); Assert.AreEqual(1, context.KeyValues["a"][1]); Assert.IsTrue(context.KeyValues.ContainsKey("is")); Assert.IsNotNull(context.KeyValues["is"]); Assert.AreEqual(1, context.KeyValues["is"].Count); Assert.AreEqual(1, context.KeyValues["is"][0]); } } }
using System; namespace Xendor.QueryModel.Converts { internal abstract class Convert<TOut> : IConvert { public object Parse(string value) { return ToConvert(value); } public Type Type => typeof(TOut); protected abstract TOut ToConvert(string value); } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using NativeFace = Sbt.NativeCoreTypes.Face; namespace Sbt.CoreTypes { public class Brep : Solid { private readonly List<Face> faces; public IList<Face> Faces { get { return faces.AsReadOnly(); } } public override IList<Face> ToFaces() { return Faces; } internal Brep(NativeCoreTypes.Brep fromNative) { faces = new List<Face>(); var firstNativeFace = fromNative.faces; var nativeFaceSize = Marshal.SizeOf(typeof(NativeFace)); for (int i = 0; i < fromNative.faceCount; ++i) { var ptr = firstNativeFace + i * nativeFaceSize; var faceObj = Marshal.PtrToStructure(ptr, typeof(NativeFace)); faces.Add(new Face((NativeFace)faceObj)); } } public Brep(IEnumerable<Face> fcs) { faces = new List<Face>(fcs); } internal override Solid ScaledBy(double factor) { return new Brep(faces.Select(f => f.ScaledBy(factor))); } internal override NativeCoreTypes.Solid ToNative() { var native = new NativeCoreTypes.Solid(); // because of the union? native.repType = NativeCoreTypes.SolidRepType.Brep; native.asBrep.faceCount = (uint)faces.Count; var faceSize = Marshal.SizeOf(typeof(NativeFace)); native.asBrep.faces = Marshal.AllocHGlobal(faces.Count * faceSize); for (int i = 0; i < faces.Count; ++i) { var natStruct = faces[i].ToNative(); var loc = native.asBrep.faces + faceSize * i; Marshal.StructureToPtr(natStruct, loc, false); } return native; } } }
using Jp.Database.Context; using JPProject.AspNet.Core; using JPProject.Domain.Core.ViewModels; using MediatR; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration; namespace JPProject.Admin.Api.Configuration { public static class AdminUiConfiguration { public static IServiceCollection ConfigureAdminUi(this IServiceCollection services, IConfiguration configuration) { services.ConfigureProviderForContext<EventStoreContext>(DetectDatabase(configuration)); services.AddDbContext<EventStoreContext>(ProviderSelector.WithProviderAutoSelection(DetectDatabase(configuration))); services .ConfigureJpAdminServices<AspNetUser>() .ConfigureJpAdminStorageServices() .AddJpAdminContext(ProviderSelector.WithProviderAutoSelection(DetectDatabase(configuration))) .AddEventStore<EventStoreContext>(); return services; } public static void ConfigureDefaultSettings(this IServiceCollection services) { // Adding MediatR for Domain Events and Notifications services.AddMediatR(typeof(Startup)); } /// <summary> /// it's just a tuple. Returns 2 parameters. /// Trying to improve readability at ConfigureServices /// </summary> private static (DatabaseType, string) DetectDatabase(IConfiguration configuration) => ( configuration.GetValue<DatabaseType>("ApplicationSettings:DatabaseType"), configuration.GetConnectionString("SSOConnection")); } }
using Leeax.Web.Builders; using System; using Microsoft.AspNetCore.Components; namespace Leeax.Web.Components.Modals { public partial class LxModalRenderer : IDisposable { public const string ClassName = "lx-modalrenderer"; protected override void BuildAttributeSet(AttributeSetBuilder builder) { builder.AddClassAttribute(x => x .Add(ClassName) .Add(ClassNames.Active, RenderService.ActiveModal != null)); } protected override void OnInitialized() { // If a dialog gets changed re-render component RenderService.StateChanged += StateHasChanged; } public void Dispose() { RenderService.StateChanged -= StateHasChanged; } [Inject] private IModalRenderService RenderService { get; set; } = null!; } }
// // QueryUnaryExpression.cs // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Collections.Generic; using System.Diagnostics; using Couchbase.Lite.Query; using Couchbase.Lite.Util; using JetBrains.Annotations; namespace Couchbase.Lite.Internal.Query { internal enum UnaryOpType { Missing, NotMissing, NotNull, Null, Valued, NotValued } internal sealed class QueryUnaryExpression : QueryExpression { #region Variables private readonly IExpression _argument; private readonly UnaryOpType _type; #endregion #region Constructors internal QueryUnaryExpression([NotNull]IExpression argument, UnaryOpType type) { Debug.Assert(argument != null); _argument = argument; _type = type; } #endregion #region Overrides protected override object ToJSON() { var obj = new List<object>(); switch (_type) { case UnaryOpType.Missing: case UnaryOpType.Null: obj.Add("IS"); obj.Add(_type == UnaryOpType.Null ? null : MissingValue ); break; case UnaryOpType.NotMissing: case UnaryOpType.NotNull: obj.Add("IS NOT"); obj.Add(_type == UnaryOpType.NotNull ? null : MissingValue ); break; case UnaryOpType.Valued: obj.Add("IS VALUED"); break; case UnaryOpType.NotValued: obj.Add("IS NOT VALUED"); break; } var operand = Misc.TryCast<IExpression, QueryExpression>(_argument); if ((operand as QueryTypeExpression)?.ExpressionType == ExpressionType.Aggregate) { obj.InsertRange(1, operand.ConvertToJSON() as IList<object>); } else { obj.Insert(1, operand.ConvertToJSON()); } return obj; } #endregion } }
namespace Lykke.Service.IntrinsicEventIndicators.Core.Domain.Model { public interface IIntrinsicEventIndicatorsRow { string RowId { get; } string AssetPair { get; } string PairName { get; } string Exchange { get; } } public class IntrinsicEventIndicatorsRow : IIntrinsicEventIndicatorsRow { public string RowId { get; set; } public string AssetPair { get; set; } public string PairName { get; set; } public string Exchange { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Trigger_Wall : MonoBehaviour, ITriggerable { public Cube_Behavior.Direction Direction; private Cube_Behavior cube_Behavior; private void Awake() { cube_Behavior = GetComponentInParent<Cube_Behavior>(); } public void Trigger(float distance, List<PlayerCharacterController.ELEMENTS> playersElements) { if (playersElements.Contains(GetRequiredElement())) cube_Behavior.MoveCube(Direction); } public bool InRange(float distance, List<PlayerCharacterController.ELEMENTS> playersElements) { return playersElements.Contains(GetRequiredElement()); } public PlayerCharacterController.ELEMENTS GetRequiredElement() => PlayerCharacterController.ELEMENTS.AIR; }
// Scatter Plot with Errorbars // An array of values can be supplied for error bars and redering options can be customized as desired var plt = new ScottPlot.Plot(600, 400); int pointCount = 20; Random rand = new Random(0); double[] xs = DataGen.Consecutive(pointCount); double[] ys = DataGen.RandomWalk(rand, pointCount); double[] xErr = DataGen.RandomNormal(rand, pointCount, .2); double[] yErr = DataGen.RandomNormal(rand, pointCount); var sp = plt.AddScatter(xs, ys); sp.XError = xErr; sp.YError = yErr; sp.ErrorCapSize = 3; sp.ErrorLineWidth = 1; sp.LineStyle = LineStyle.Dot; plt.SaveFig("scatter_errorbar.png");
// <copyright file="FtpShellCommandAutoCompletion.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace TestFtpServer.Shell { /// <summary> /// A handler for auto completion. /// </summary> internal class FtpShellCommandAutoCompletion : IAutoCompleteHandler { private readonly IReadOnlyCollection<ICommandInfo> _commands; /// <summary> /// Initializes a new instance of the <see cref="FtpShellCommandAutoCompletion"/> class. /// </summary> /// <param name="commandInfos">The registered command handlers.</param> public FtpShellCommandAutoCompletion( IEnumerable<ICommandInfo> commandInfos) { _commands = commandInfos.OfType<IRootCommandInfo>().ToList(); } /// <summary> /// Gets the executable command for the given text. /// </summary> /// <param name="text">The text to find the command for.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The found executable command.</returns> public async ValueTask<IExecutableCommandInfo?> GetCommandAsync(string text, CancellationToken cancellationToken) { var words = text.Trim().Split( Separators, StringSplitOptions.RemoveEmptyEntries); IReadOnlyCollection<ICommandInfo> current = _commands; IReadOnlyCollection<ICommandInfo> next = _commands; for (var i = 0; i != words.Length; ++i) { var word = words[i]; current = next.FindCommandInfo(word); next = await current.ToAsyncEnumerable() .SelectMany(x => x.GetSubCommandsAsync(cancellationToken)) .ToListAsync(cancellationToken) .ConfigureAwait(false); } if (current.Count != 1) { return null; } return current.Single() as IExecutableCommandInfo; } /// <inheritdoc /> public async Task<string[]> GetSuggestionsAsync(string? text, int index) { if (string.IsNullOrWhiteSpace(text)) { return _commands.Select(x => x.Name).ToArray(); } var words = text!.Substring(0, index) .Trim() .Split(Separators, StringSplitOptions.RemoveEmptyEntries); IReadOnlyCollection<ICommandInfo> current = _commands; for (var i = 0; i != words.Length; ++i) { var word = words[i]; var found = current.FindCommandInfo(word); current = await found .ToAsyncEnumerable() .SelectMany(x => x.GetSubCommandsAsync(CancellationToken.None)) .ToListAsync() .ConfigureAwait(false); } var lastWord = text.Substring(index).Trim(); if (!string.IsNullOrEmpty(lastWord)) { current = current.FindCommandInfo(lastWord); } var result = current .Select(x => x.Name) .Concat(current.SelectMany(x => x.AlternativeNames)) .Where(x => x.StartsWith(lastWord, StringComparison.OrdinalIgnoreCase)) .ToArray(); return result; } /// <inheritdoc /> public char[] Separators { get; set; } = { ' ', '\t' }; } }
// Copyright (c) 2021 DrBarnabus using Microsoft.Extensions.Hosting; using System; using System.Threading; using System.Threading.Tasks; namespace Servly.Core.Internal { internal class ServlyHost : IServlyHost { private readonly IHost _host; public ServlyHost(IHost host) { _host = host; } public IServiceProvider Services => _host.Services; public async Task StartAsync(CancellationToken cancellationToken = default) { await _host.StartAsync(cancellationToken); } public async Task StopAsync(CancellationToken cancellationToken = default) { await _host.StopAsync(cancellationToken); } public async Task StopAsync(TimeSpan timeout) { await _host.StopAsync(timeout); } public async Task WaitForShutdownAsync(CancellationToken cancellationToken = default) { await _host.WaitForShutdownAsync(cancellationToken); } public async Task RunAsync(CancellationToken cancellationToken = default) { try { await StartAsync(cancellationToken).ConfigureAwait(false); await WaitForShutdownAsync(cancellationToken).ConfigureAwait(false); } finally { await DisposeAsync().ConfigureAwait(false); } } public void Dispose() { DisposeAsync().AsTask().GetAwaiter().GetResult(); } public async ValueTask DisposeAsync() { switch (_host) { // ReSharper disable once SuspiciousTypeConversion.Global case IAsyncDisposable asyncDisposable: await asyncDisposable.DisposeAsync().ConfigureAwait(false); break; case IDisposable disposable: disposable.Dispose(); break; } } } }
using System; using QuantoAgent.Database; namespace QuantoAgent.Models { public class GContext { public string Path { get; set; } public string Method { get; set; } public DBUser User { get; set; } } }
namespace EasyMobile.Internal { /// <summary> /// Simple serializable version of <see cref="System.Collections.Generic.KeyValuePair{string, string}"/> /// </summary> public class StringStringKeyValuePair : SerializableKeyValuePair<string, string> { public StringStringKeyValuePair(string key, string value) : base(key, value) { } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using Npoi.Core.OpenXmlFormats.Spreadsheet; using Npoi.Core.SS.UserModel; using Npoi.Core.SS.Util; using NUnit.Framework; using System; using TestCases.SS.UserModel; namespace Npoi.Core.XSSF.UserModel { /** * Test array formulas in XSSF * * @author Yegor Kozlov * @author Josh Micich */ [TestFixture] public class TestXSSFSheetUpdateArrayFormulas : BaseTestSheetUpdateArrayFormulas { public TestXSSFSheetUpdateArrayFormulas() : base(XSSFITestDataProvider.instance) { } // Test methods common with HSSF are in superclass // Local methods here Test XSSF-specific details of updating array formulas [Test] public void TestXSSFSetArrayFormula_SingleCell() { ICellRange<ICell> cells; XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet(); // 1. Single-cell array formula String formula1 = "123"; CellRangeAddress range = CellRangeAddress.ValueOf("C3:C3"); cells = sheet.SetArrayFormula(formula1, range); Assert.AreEqual(1, cells.Size); // check GetFirstCell... XSSFCell firstCell = (XSSFCell)cells.TopLeftCell; Assert.AreSame(firstCell, sheet.GetFirstCellInArrayFormula(firstCell)); //retrieve the range and check it is the same Assert.AreEqual(range.FormatAsString(), firstCell.ArrayFormulaRange.FormatAsString()); ConfirmArrayFormulaCell(firstCell, "C3", formula1, "C3"); } [Test] public void TestXSSFSetArrayFormula_multiCell() { ICellRange<ICell> cells; String formula2 = "456"; XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet(); CellRangeAddress range = CellRangeAddress.ValueOf("C4:C6"); cells = sheet.SetArrayFormula(formula2, range); Assert.AreEqual(3, cells.Size); // sheet.SetArrayFormula Creates rows and cells for the designated range /* * From the spec: * For a multi-cell formula, the c elements for all cells except the top-left * cell in that range shall not have an f element; */ // Check that each cell exists and that the formula text is Set correctly on the first cell XSSFCell firstCell = (XSSFCell)cells.TopLeftCell; ConfirmArrayFormulaCell(firstCell, "C4", formula2, "C4:C6"); ConfirmArrayFormulaCell(cells.GetCell(1, 0), "C5"); ConfirmArrayFormulaCell(cells.GetCell(2, 0), "C6"); Assert.AreSame(firstCell, sheet.GetFirstCellInArrayFormula(firstCell)); } private static void ConfirmArrayFormulaCell(ICell c, String cellRef) { ConfirmArrayFormulaCell(c, cellRef, null, null); } private static void ConfirmArrayFormulaCell(ICell c, String cellRef, String formulaText, String arrayRangeRef) { if (c == null) { throw new AssertionException("Cell should not be null."); } CT_Cell ctCell = ((XSSFCell)c).GetCTCell(); Assert.AreEqual(cellRef, ctCell.r); if (formulaText == null) { Assert.IsFalse(ctCell.IsSetF()); Assert.IsNull(ctCell.f); } else { CT_CellFormula f = ctCell.f; Assert.AreEqual(arrayRangeRef, f.@ref); Assert.AreEqual(formulaText, f.Value); Assert.AreEqual(ST_CellFormulaType.array, f.t); } } } }
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.Azure.IIoT.Crypto.KeyVault.Models { using Microsoft.Azure.IIoT.Crypto.Models; using Microsoft.Azure.KeyVault.Models; using System; using System.Runtime.Serialization; /// <summary> /// Key and secret identifier keyvault bundle handle /// </summary> [DataContract] internal class KeyVaultKeyHandle : KeyHandle { /// <summary> /// Key identifier /// </summary> [DataMember] public string SecretIdentifier { get; internal set; } /// <summary> /// Key identifier /// </summary> [DataMember] public string KeyIdentifier { get; internal set; } /// <summary> /// Create key handle /// </summary> /// <param name="keyIdentifier"></param> /// <param name="secretIdentifier"></param> internal static KeyVaultKeyHandle Create(string keyIdentifier, string secretIdentifier) { return new KeyVaultKeyHandle { KeyIdentifier = keyIdentifier, SecretIdentifier = secretIdentifier }; } /// <summary> /// Create key handle /// </summary> /// <param name="bundle"></param> internal static KeyVaultKeyHandle Create(CertificateBundle bundle) { return Create(bundle.KeyIdentifier?.Identifier, bundle.SecretIdentifier?.Identifier); } /// <summary> /// Create key handle /// </summary> /// <param name="bundle"></param> /// <param name="secret"></param> internal static KeyVaultKeyHandle Create(KeyBundle bundle, SecretBundle secret = null) { return Create(bundle.KeyIdentifier?.Identifier, secret.SecretIdentifier?.Identifier); } /// <summary> /// Get id from handle /// </summary> /// <param name="handle"></param> /// <returns></returns> public static KeyVaultKeyHandle GetBundle(KeyHandle handle) { if (handle is KeyVaultKeyHandle id) { return id; } throw new ArgumentException("Bad handle type"); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; namespace PIT.Core { public class ObservableCollectionEx<T> : ObservableCollection<T> where T : INotifyPropertyChanged { public ObservableCollectionEx() { CollectionChanged += ObservableCollectionEx_CollectionChanged; } public ObservableCollectionEx(IEnumerable<T> collection) : base(collection) { } public ObservableCollectionEx(List<T> list) : base(list) { } public event EventHandler<T> CollectionItemPropertyChanged; protected virtual void OnCollectionItemPropertyChanged(T e) { var handler = CollectionItemPropertyChanged; if (handler != null) handler(this, e); } private void ObservableCollectionEx_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Remove) { foreach (T item in e.NewItems) { item.PropertyChanged -= EntityViewModelPropertyChanged; } } else if (e.Action == NotifyCollectionChangedAction.Add) { foreach (T item in e.NewItems) { item.PropertyChanged += EntityViewModelPropertyChanged; } } } public virtual void EntityViewModelPropertyChanged(object sender, PropertyChangedEventArgs e) { OnCollectionItemPropertyChanged((T)sender); var args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset); OnCollectionChanged(args); } } }
using System.ComponentModel.DataAnnotations; namespace SavingMoney.WebApi.Model; /// <summary> /// Entity recording costs records entered by the users /// </summary> public class Cost { /// <summary> /// Entity id /// </summary> public int Id { get; set; } /// <summary> /// Organization /// </summary> [Required] public int OrganizationId { get; set; } /// <summary> /// Predicted cost subcategory id /// </summary> [Required] public int CostSubCategoryId { get; set; } /// <summary> /// Who added the cost /// </summary> [Required] public int AddedBy { get; set; } /// <summary> /// When the cost was spent /// </summary> [Required] public DateTime TimeSpentUtc { get; set; } /// <summary> /// Comment explaining the cost /// </summary> [Required] [MaxLength(1000)] public string Comment { get; set; } /// <summary> /// Amount spent /// </summary> [Required] [Range(0, int.MaxValue)] public decimal Amount { get; set; } /// <summary> /// Type of currency /// </summary> [Required] public CurrencyType Currency { get; set; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VotingCommon.Enumerations; using VotingCommon.Properties; namespace VotingCommon.Converts { public class VoteConvert { private static readonly List<Tuple<int, string>> voteList = new List<Tuple<int, string>>() { new Tuple<int, string>((int)VoteEnum.Yes, Resources.VOTE_YES), new Tuple<int, string>((int)VoteEnum.No, Resources.VOTE_NO), new Tuple<int, string>((int)VoteEnum.Abstain, Resources.VOTE_ABSTAIN), new Tuple<int, string>((int)VoteEnum.Missing, Resources.VOTE_MISSING), new Tuple<int, string>((int)VoteEnum.NotVoting, Resources.VOTE_NOT_VOTING), }; public static List<Tuple<int, string>> GetVoteList() { return voteList; } public static string Convert(VoteEnum vote) { switch (vote) { case VoteEnum.Yes: return Resources.VOTE_YES; case VoteEnum.No: return Resources.VOTE_NO; case VoteEnum.Abstain: return Resources.VOTE_ABSTAIN; case VoteEnum.Missing: return Resources.VOTE_MISSING; case VoteEnum.NotVoting: return Resources.VOTE_NOT_VOTING; } return null; } public static string GetItemClass(VoteEnum vote) { switch (vote) { case VoteEnum.Yes: return "list-group-item-success"; case VoteEnum.No: return "list-group-item-danger"; case VoteEnum.Abstain: return "list-group-item-warning"; case VoteEnum.Missing: return null; case VoteEnum.NotVoting: return "list-group-item-info"; } return null; } } }
using System.ComponentModel; using BoC.InversionOfControl; namespace BoC.ComponentModel.TypeExtension.DefaultSetupTasks { public class RegisterTypeDescriptor : IContainerInitializer { public void Execute() { TypeDescriptor.AddProvider(new ExtendedTypeDescriptionProvider(typeof(object)), typeof(object)); } } }
using System; using MediatR; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using Application.Features.GetProducts.Queries; namespace Api.Controllers { [ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { private readonly IMediator mediator; public ProductsController(IMediator mediator) { this.mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); } [HttpGet] public async Task<IActionResult> GetProducts([FromQuery] GetProductsQuery query) { IEnumerable<GetProductsQuery.Product> products = await mediator.Send(query); return products.Any() ? Ok(products) : NotFound(query); } } }
using Iced.Intel; using System; using MBBSEmu.Extensions; using Xunit; using static Iced.Intel.AssemblerRegisters; namespace MBBSEmu.Tests.CPU { public class ROR_Tests : CpuTestBase { [Fact] public void ROR_AX_IMM16_1() { Reset(); mbbsEmuCpuRegisters.AX = 2; var instructions = new Assembler(16); instructions.ror(ax, 1); CreateCodeSegment(instructions); mbbsEmuCpuCore.Tick(); Assert.Equal(2 >> 1, mbbsEmuCpuRegisters.AX); } [Fact] public void ROR_AX_IMM16_CF_OF() { Reset(); mbbsEmuCpuRegisters.AX = 1; var instructions = new Assembler(16); instructions.ror(ax, 1); CreateCodeSegment(instructions); mbbsEmuCpuCore.Tick(); Assert.Equal(0x8000, mbbsEmuCpuRegisters.AX); Assert.True(mbbsEmuCpuRegisters.CarryFlag); Assert.True(mbbsEmuCpuRegisters.OverflowFlag); } [Fact] public void ROR_AX_IMM16_OF() { Reset(); mbbsEmuCpuRegisters.AX = 0x8000; var instructions = new Assembler(16); instructions.ror(ax, 1); CreateCodeSegment(instructions); mbbsEmuCpuCore.Tick(); Assert.Equal(0x8000 >> 1, mbbsEmuCpuRegisters.AX); Assert.False(mbbsEmuCpuRegisters.CarryFlag); Assert.True(mbbsEmuCpuRegisters.OverflowFlag); } [Fact] public void ROR_AL_IMM8_1() { Reset(); mbbsEmuCpuRegisters.AL = 2; var instructions = new Assembler(16); instructions.ror(al, 1); CreateCodeSegment(instructions); mbbsEmuCpuCore.Tick(); Assert.Equal(2 >> 1, mbbsEmuCpuRegisters.AL); } [Fact] public void ROR_AL_IMM8_CF_OF() { Reset(); mbbsEmuCpuRegisters.AL = 1; var instructions = new Assembler(16); instructions.ror(al, 1); CreateCodeSegment(instructions); mbbsEmuCpuCore.Tick(); Assert.Equal(0x80, mbbsEmuCpuRegisters.AX); Assert.True(mbbsEmuCpuRegisters.CarryFlag); Assert.True(mbbsEmuCpuRegisters.OverflowFlag); } [Fact] public void ROR_AL_IMM8_OF() { Reset(); mbbsEmuCpuRegisters.AL = 0x80; var instructions = new Assembler(16); instructions.ror(al, 1); CreateCodeSegment(instructions); mbbsEmuCpuCore.Tick(); Assert.Equal(0x80 >> 1, mbbsEmuCpuRegisters.AX); Assert.False(mbbsEmuCpuRegisters.CarryFlag); Assert.True(mbbsEmuCpuRegisters.OverflowFlag); } [Fact] public void ROR_M8_IMM8_1() { Reset(); mbbsEmuCpuRegisters.DS = 2; CreateDataSegment(new byte[] { 2 }, 2); var instructions = new Assembler(16); instructions.ror(__byte_ptr[0], 1); CreateCodeSegment(instructions); mbbsEmuCpuCore.Tick(); Assert.Equal(2 >> 1, mbbsEmuMemoryCore.GetByte(2,0)); } [Fact] public void ROR_M16_IMM8_1() { Reset(); mbbsEmuCpuRegisters.DS = 2; CreateDataSegment(BitConverter.GetBytes((ushort)2), 2); var instructions = new Assembler(16); instructions.ror(__word_ptr[0], 1); CreateCodeSegment(instructions); mbbsEmuCpuCore.Tick(); Assert.Equal(2 >> 1, mbbsEmuMemoryCore.GetByte(2, 0)); } [Fact] public void ROR_M8_CL_1() { Reset(); mbbsEmuCpuRegisters.DS = 2; mbbsEmuCpuRegisters.CL = 1; CreateDataSegment(new byte[] { 2 }, 2); var instructions = new Assembler(16); instructions.ror(__byte_ptr[0],cl); CreateCodeSegment(instructions); mbbsEmuCpuCore.Tick(); Assert.Equal(2 >> 1, mbbsEmuMemoryCore.GetByte(2, 0)); } [Fact] public void ROR_M8_IMM8_7() { Reset(); mbbsEmuCpuRegisters.DS = 2; CreateDataSegment(new byte[] { 0x80 }, 2); var instructions = new Assembler(16); instructions.ror(__byte_ptr[0], 7); CreateCodeSegment(instructions); mbbsEmuCpuCore.Tick(); Assert.Equal(0x80 >> 7, mbbsEmuMemoryCore.GetByte(2, 0)); } } }
using FluentValidation; using Shared; using Shared.Entity; using Shared.Validator; namespace Domain.Entidade { public class TurmaDisciplina : EntityCrud<TurmaDisciplina> { public override AbstractValidator<TurmaDisciplina> Validador => new TurmaDisciplinaValidator(); public string DisciplinaId { get; set; } public Disciplina Disciplinas { get; set; } public string TurmaId { get; set; } public Turma Turmas { get; set; } public override void PreencherDados(TurmaDisciplina data) { DisciplinaId = data.DisciplinaId; } public override ResultadoValidacao Validar() { return ExecutarValidacaoPadrao(this); } } internal class TurmaDisciplinaValidator : AbstractValidator<TurmaDisciplina> { public TurmaDisciplinaValidator() { RuleFor(x => x.DisciplinaId) .NotNull().WithMessage(Textos.Geral_Mensagem_Erro_Campo_null) .MaximumLength(36); RuleFor(x => x.TurmaId) .NotNull().WithMessage(Textos.Geral_Mensagem_Erro_Campo_null) .MaximumLength(36); } } }
using System; using System.Collections.ObjectModel; using System.Linq; using Microsoft.Extensions.Configuration; namespace SeleniumGridManager.Web.Services.Configuration { public class AppConfigurationService : IAppConfigurationService { private IConfiguration _config; public ReadOnlyCollection<NodeConfiguration> Nodes { get { NodeConfiguration[] array = this._config.GetSection( "Nodes" ).Get<NodeConfiguration[]>(); return Array.AsReadOnly( array ); } } public AppConfigurationService( IConfiguration config) { this._config = config; } public NodeConfiguration GetNodeConfiguration(string nodeId) { return this.Nodes.FirstOrDefault( n => n.Id.Equals( nodeId, StringComparison.OrdinalIgnoreCase ) ); } } }
#pragma warning disable 4014 namespace Unosquare.Labs.EmbedIO.Tests { using System.Threading.Tasks; using NUnit.Framework; [TestFixture] public class EasyRoutesTest { private const string Ok = "Ok"; [Test] public async Task AddOnAny_ResponseOK() { var server = new TestWebServer(); server .OnAny((ctx, ct) => ctx.StringResponseAsync(Ok, cancellationToken: ct)); server.RunAsync(); Assert.AreEqual(Ok, await server.GetClient().GetAsync()); } [Test] public async Task AddOnGet_ResponseOK() { var server = new TestWebServer(); server .OnGet((ctx, ct) => ctx.StringResponseAsync(Ok, cancellationToken: ct)); server.RunAsync(); Assert.AreEqual(Ok, await server.GetClient().GetAsync()); } [Test] public async Task AddOnPost_ResponseOK() { var server = new TestWebServer(); server .OnPost((ctx, ct) => ctx.StringResponseAsync(Ok, cancellationToken: ct)); server.RunAsync(); var response = await server.GetClient().SendAsync(new TestHttpRequest(Constants.HttpVerbs.Post)); Assert.AreEqual(Ok, response.GetBodyAsString()); } [Test] public async Task AddOnPut_ResponseOK() { var server = new TestWebServer(); server .OnPut((ctx, ct) => ctx.StringResponseAsync(Ok, cancellationToken: ct)); server.RunAsync(); var response = await server.GetClient().SendAsync(new TestHttpRequest(Constants.HttpVerbs.Put)); Assert.AreEqual(Ok, response.GetBodyAsString()); } [Test] public async Task AddOnHead_ResponseOK() { var server = new TestWebServer(); server .OnHead((ctx, ct) => ctx.StringResponseAsync(Ok, cancellationToken: ct)); server.RunAsync(); var response = await server.GetClient().SendAsync(new TestHttpRequest(Constants.HttpVerbs.Head)); Assert.AreEqual(Ok, response.GetBodyAsString()); } [Test] public async Task AddOnDelete_ResponseOK() { var server = new TestWebServer(); server .OnDelete((ctx, ct) => ctx.StringResponseAsync(Ok, cancellationToken: ct)); server.RunAsync(); var response = await server.GetClient().SendAsync(new TestHttpRequest(Constants.HttpVerbs.Delete)); Assert.AreEqual(Ok, response.GetBodyAsString()); } [Test] public async Task AddOnOptions_ResponseOK() { var server = new TestWebServer(); server .OnOptions((ctx, ct) => ctx.StringResponseAsync(Ok, cancellationToken: ct)); server.RunAsync(); var response = await server.GetClient().SendAsync(new TestHttpRequest(Constants.HttpVerbs.Options)); Assert.AreEqual(Ok, response.GetBodyAsString()); } [Test] public async Task AddOnPatch_ResponseOK() { var server = new TestWebServer(); server .OnPatch((ctx, ct) => ctx.StringResponseAsync(Ok, cancellationToken: ct)); server.RunAsync(); var response = await server.GetClient().SendAsync(new TestHttpRequest(Constants.HttpVerbs.Patch)); Assert.AreEqual(Ok, response.GetBodyAsString()); } } } #pragma warning restore 4014
using UnityEngine; using UnityEngine.UI; using System.Collections; using UnityEngine.Events; public class MenuOption : MonoBehaviour { public Menu Menu; public Text OptionText; public Text ValueText; public Menu.Option OptionInfo; public void OnClick() { if (OptionInfo.Enabled) { OptionInfo.Callback(); } } void Update () { if (OptionInfo.Enabled) { if (OptionInfo.OptionTextColourOverride.HasValue) { OptionText.color = OptionInfo.OptionTextColourOverride.Value; } else { OptionText.color = Menu.EnabledOptionColour; } ValueText.color = Menu.EnabledValueColour; if (OptionInfo.BoldText) { OptionText.fontStyle = FontStyle.Bold; } else { OptionText.fontStyle = FontStyle.Normal; } } else { OptionText.color = Menu.DisabledOptionColour; ValueText.color = Menu.DisabledValueColour; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace ExRatesSharp.Objects { public class CustomResponse { [JsonProperty("rates")] public Dictionary<string, Dictionary<string, double>> Rates { get; set; } [JsonProperty("start_at")] public DateTimeOffset StartAt { get; set; } [JsonProperty("base")] public string BaseCurrency { get; set; } [JsonProperty("end_at")] public DateTimeOffset EndAt { get; set; } } }
using GetcuReone.MvvmFrame.Wpf; using GetcuReone.MvvmFrame.Wpf.Commands; using GetcuReone.MvvmFrame.Wpf.EventArgs; using GetcuReone.MvvmFrame.Wpf.Models; using MvvmFrame.Wpf.TestWpf.Pages; using System.Threading.Tasks; namespace MvvmFrame.Wpf.TestWpf.ViewModels { public sealed class MainViewModel : ViewModelBase { public ButtonModel GoBack_ButtonModel { get; private set; } public ButtonModel GoForward_ButtonModel { get; private set; } public ButtonModel Navigate_ButtonModel { get; private set; } public ButtonModel Refresh_ButtonModel { get; set; } protected override void Initialize() { GoBack_ButtonModel = GetModel<ButtonModel>(); GoBack_ButtonModel.Command = new Command(GoBack); GoForward_ButtonModel = GetModel<ButtonModel>(); GoForward_ButtonModel.Command = new Command(GoForward); Navigate_ButtonModel = GetModel<ButtonModel>(); Navigate_ButtonModel.Command = new Command(Navigate); Refresh_ButtonModel = GetModel<ButtonModel>(); Refresh_ButtonModel.Command = new Command(Refresh); } private void GoBack(CommandArgs e) => NavigationManager.GoBack(); private void GoForward(CommandArgs e) => NavigationManager.GoForward(); private void Refresh(CommandArgs e) => NavigationManager.Refresh(); private void Navigate(CommandArgs e) => Navigate<HomePage, HomeViewModel>("Hi, home"); protected override ValueTask OnGoPageAsync(object navigateParam) { return default; } protected override ValueTask OnLeavePageAsync(NavigatingEventArgs args) { return default; } protected override ValueTask OnLoadPageAsync() { return default; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using AppService.Core.Interfaces; using AppService.Core.Models; using AppService.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace AppService.Controllers { [Route("api/[controller]")] public class HeroesController : Controller { private readonly IRepository _heroRepo; public HeroesController(IRepository heroRepository) { _heroRepo = heroRepository; } [HttpGet] public async Task<IEnumerable<Superhero>> Get() { return await _heroRepo.GetAll<Superhero>() .ToListAsync(); } [HttpGet("{id}")] public async Task<Superhero> Get(int id) { return await _heroRepo.GetAll<Superhero>() .FirstOrDefaultAsync(hero => hero.Id == id); } [HttpPost] public async Task<IActionResult> Post([FromBody]Superhero hero) { hero.ImageUrl = Path.Combine("images", hero.ImageUrl); await _heroRepo.UpdateAsync(hero); return Ok(); } [HttpPost("uploadImage")] public async Task<IActionResult> Post([FromForm]IFormFile file) { System.Console.WriteLine(file); string folderName = "wwwroot/images"; string filePath = Path.Combine(Directory.GetCurrentDirectory(), folderName); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } if (file != null && file.Length > 0) { string finalDestination = Path.Combine(filePath, file.FileName); using (var stream = new FileStream(finalDestination, FileMode.Create)) { await file.CopyToAsync(stream); } } return Ok(); } } }
namespace LmkPhotoViewer.Model { using System; using LmkImageLib; public class FileInfo : ModelBase { public FileInfo(string filePath) { this.FilePath = filePath; if (System.IO.File.Exists(this.FilePath)) { this.Info = new System.IO.FileInfo(FilePath); this.UpdateDateTimeCached = this.Info.LastWriteTime; } } #region Property private string filePath; public string FilePath { get { return filePath; } private set { filePath = value; RaisePropertyChanged(() => FilePath); } } private DateTime updateDateTimeCached; public DateTime UpdateDateTimeCached { get { return updateDateTimeCached; } private set { updateDateTimeCached = value; RaisePropertyChanged(() => UpdateDateTimeCached); } } private System.IO.FileInfo info; public System.IO.FileInfo Info { get { return info; } private set { info = value; RaisePropertyChanged(() => Info); } } #endregion #region Method /// <summary> /// If Updated, return true. /// </summary> /// <returns>judge updated or not</returns> public bool? CheckUpdated() { this.Info.Refresh(); // removed if (!this.Info.Exists) return null; // update if(this.UpdateDateTimeCached != this.Info.LastWriteTime) { this.UpdateDateTimeCached = this.Info.LastWriteTime; return true; } return false; } #endregion } }
using System; using AutoMapper; using CleanArchitecture.Application.ViewModels; using CleanArchitecture.Domain.Models; namespace CleanArchitecture.Application.AutoMapper { public class DomainToViewModelProfile : Profile { public DomainToViewModelProfile() { CreateMap<Course, CourseViewModel>(); } } }
@using Microsoft.AspNetCore.Identity @using WebAppLuisMendozaSamuel @using WebAppLuisMendozaSamuel.Models @using WebAppLuisMendozaSamuel.Models.AccountViewModels @using WebAppLuisMendozaSamuel.Models.ManageViewModels @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
var provider = ArchiveProviderFactory.Create(PersonProvider.ProviderName); provider.SetDesiredColumns("firstName", "CountAll(firstName)", "Count(middleName)", "Sum(rank):HideDetail", "GroupBy(middleName):Header,Footer,1", "GroupBy(lastName):Header,Footer,2"); provider.SetDesiredEntities("person"); provider.SetPagingInfo(100, 0); provider.SetRestriction(new ArchiveRestrictionInfo("contactId", "=", CultureDataFormatter.Encode(24))); foreach (var row in provider.GetRows(AggregationProvider2.GrandTotalOption + "=true")) { // ... }
using System; using System.Linq; using System.Threading.Tasks; using NpuRozklad.Core.Entities; using NpuRozklad.Core.Interfaces; using NpuRozklad.Telegram.BotActions; using NpuRozklad.Telegram.Services.Interfaces; namespace NpuRozklad.Telegram.Handlers.CallbackQueryHandlers.SpecificHandlers { public class ShowTimetableFacultyGroupViewMenuCallbackHandler : SpecificHandlerBase { private readonly ITelegramBotActions _botActions; private readonly IFacultiesProvider _facultiesProvider; private readonly IFacultyGroupsProvider _facultyGroupsProvider; private CallbackQueryData _callbackQueryData; private Faculty _faculty; private Group _facultyGroup; private DayOfWeek _dayOfWeek; private bool _isNextWeek; private string _facultyTypeId; private string _facultyGroupTypeId; public ShowTimetableFacultyGroupViewMenuCallbackHandler(ITelegramBotActions botActions, IFacultiesProvider facultiesProvider, IFacultyGroupsProvider facultyGroupsProvider, ITelegramBotService telegramBotService) : base(telegramBotService) { _botActions = botActions; _facultiesProvider = facultiesProvider; _facultyGroupsProvider = facultyGroupsProvider; } protected override async Task HandleImplementation(CallbackQueryData callbackQueryData) { _callbackQueryData = callbackQueryData; ProcessCallbackQueryData(); await GetFaculty(); await GetFacultyGroup(); var actionOptions = new ShowTimetableFacultyGroupViewMenuOptions { FacultyGroup = _facultyGroup, DayOfWeek = _dayOfWeek, IsNextWeekSelected = _isNextWeek }; await _botActions.ShowTimetableFacultyGroupViewMenu(actionOptions); } private async Task GetFacultyGroup() { var facultyGroupTypeId = _facultyGroupTypeId; var facultyGroups = await _facultyGroupsProvider.GetFacultyGroups(_faculty); _facultyGroup = facultyGroups.FirstOrDefault(g => g.TypeId == facultyGroupTypeId); } private void ProcessCallbackQueryData() { var values = _callbackQueryData.Values; _isNextWeek = values[0] == "1"; _dayOfWeek = (DayOfWeek) Convert.ToInt32(values[1]); _facultyGroupTypeId = values[2]; _facultyTypeId = values[3]; } private async Task GetFaculty() { var faculties = await _facultiesProvider.GetFaculties(); var facultyTypeId = _facultyTypeId; _faculty = faculties.FirstOrDefault(f => f.TypeId == facultyTypeId); } } }
using UnityEngine; using System.Collections; public class ChunkGenerator : MonoBehaviour { ChunkSettings chunkSettings; public ChunkGenerator(ChunkSettings chunkSettings) { this.chunkSettings = chunkSettings; } public void GenerateChunk(Chunk<Voxel> chunk, Vector3 worldPos) { Color color = Random.ColorHSV(); Vector3 voxelPositionStart = worldPos; int chunkSL = chunkSettings.ChunkSL; float voxelSize = chunkSettings.VoxelSize; for (int z = 0; z < chunkSL; z++) { for (int y = 0; y < chunkSL; y++) { for (int x = 0; x < chunkSL; x++) { Vector3Int index3D = new Vector3Int(x, y, z); Vector3 voxelPosition = voxelPositionStart + (Vector3)index3D * voxelSize; Voxel voxel = new Voxel(); byte voxDensity = GetDensity(voxelPosition); voxel.Color = 0b00100101; voxel.Density = voxDensity; if (voxDensity == 0) { voxel.IsAir = true; } else { voxel.IsAir = false; } chunk.SetVoxel(index3D, voxel); } } } } void DisplayDot(Vector3 pos, Color color) { Debug.DrawRay(pos, Random.insideUnitSphere * 0.2f, color, 1000); } byte GetDensity(Vector3 input) { float noise = GetNoise(input); if (noise > 0.5f) { //return 255; return (byte)(Mathf.Clamp((noise - 0.5f) * 5, 0f, 1) * 255); } else { return 0; } } float GetNoise(Vector3 input) { //return 0; Vector3 noiseInput = input * 0.16f * 0.2f; float noise = Noise.Noise.GetNoise(noiseInput.x, noiseInput.y, noiseInput.z); return noise; } }
using System.Text.Json; using AutoMapper; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using NodaTime; using Serilog; using TreniniDotNet.Common.Uuid; using TreniniDotNet.Infrastructure.HealthChecks; using TreniniDotNet.Infrastructure.Identity.DependencyInjection; using TreniniDotNet.Infrastructure.Persistence.DependencyInjection; using TreniniDotNet.Web.Catalog.V1; using TreniniDotNet.Web.Collecting.V1; using TreniniDotNet.Web.Infrastructure.DependencyInjection; using TreniniDotNet.Web.Infrastructure.ViewModels.Links; using TreniniDotNet.Web.Uploads; namespace TreniniDotNet.Web { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } private IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(Configuration) .CreateLogger(); services.AddControllers(o => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); o.Filters.Add(new AuthorizeFilter(policy)); }) .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; }); services.AddHttpContextAccessor(); services.AddRepositories(Configuration); services.AddUseCases(); services.AddCatalogPresenters(); services.AddCollectingPresenter(); services.AddOpenApi(); services.AddVersioning(); services.AddAutoMapper(typeof(Startup)); services.AddMediatR(typeof(Startup).Assembly); services.AddSingleton<ILinksGenerator, AspNetLinksGenerator>(); services.AddSingleton<IGuidSource, GuidSource>(); services.AddSingleton<IClock>(SystemClock.Instance); var uploadsSection = Configuration.GetSection("Uploads"); services.Configure<UploadSettings>(uploadsSection); services.AddIdentityManagement(Configuration); services.AddHealthChecks() .AddDatabaseHealthChecks(); services.AddMigrations(Configuration); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopmentOrTesting()) { app.UseExceptionHandler("/error-local-development"); app.EnsureDatabaseCreated(); } else { app.UseExceptionHandler("/error"); app.UseHttpsRedirection(); } app.UseSerilogRequestLogging(); app.UseRouting(); app.UseAuthorization(); app.UseAuthentication(); app.UseOpenApi(); app.UseSwaggerUi3(settings => { settings.TagsSorter = "alpha"; settings.OperationsSorter = "alpha"; }); app.UseHealthChecks("/health"); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } public static class HostEnvironmentEnvExtensions { public static bool IsDevelopmentOrTesting(this IHostEnvironment hostEnvironment) => hostEnvironment.IsDevelopment() || "Testing" == hostEnvironment.EnvironmentName; } }