content
stringlengths
23
1.05M
namespace SIL.Machine.WebApi { public class SegmentPairDto { public string[] SourceSegment { get; set; } public string[] TargetSegment { get; set; } public bool SentenceStart { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using Xunit.Abstractions; namespace Micser.TestCommon { public class TestFileManager { private readonly List<string> _fileNames; private readonly ITestOutputHelper _testOutputHelper; public TestFileManager(ITestOutputHelper testOutputHelper) { _fileNames = new List<string>(); _testOutputHelper = testOutputHelper; } public void DeleteFiles() { foreach (var fileName in _fileNames) { try { File.Delete(fileName); } catch (Exception ex) { _testOutputHelper.WriteLine(ex.ToString()); } } _fileNames.Clear(); } public string GetFileName() { var fn = Guid.NewGuid() + ".tmp"; _fileNames.Add(fn); return fn; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using XUnity.AutoTranslator.Plugin.Core.Utilities; namespace XUnity.AutoTranslator.Plugin.Core { /// <summary> /// Public API Surface for the Auto Translator Plugin. /// </summary> public interface ITranslator { /// <summary> /// Queries the plugin to provide a translated text for the untranslated text. /// If the translation cannot be found in the cache, it will make a /// request to the translator selected by the user. /// </summary> /// <param name="untranslatedText">The untranslated text to provide a translation for.</param> /// <param name="onCompleted">Callback to completion of the translation.</param> void TranslateAsync( string untranslatedText, Action<TranslationResult> onCompleted ); /// <summary> /// Queries the plugin to provide a translated text for the untranslated text. /// If the translation cannot be found in the cache, the method returns false /// and returns null as the untranslated text. /// </summary> /// <param name="untranslatedText">The untranslated text to provide a translation for.</param> /// <param name="translatedText">The translated text.</param> /// <returns></returns> bool TryTranslate( string untranslatedText, out string translatedText ); } }
/* http://www.cgsoso.com/forum-257-1.html CG搜搜 Unity3d 插件团购 CGSOSO 主打游戏开发,影视设计等CG资源素材。 每日Unity3d插件免费更新,仅限下载试用,如若商用,请务必官网购买! */ using System; using UnityEngine; using System.Collections; public class MoveOnGround : MonoBehaviour { public event EventHandler<CollisionInfo> OnCollision; public bool IsRootMove = true; private EffectSettings effectSettings; private Transform tRoot, tTarget; private Vector3 targetPos; private bool isInitialized; private bool isFinished; private ParticleSystem[] particles; private void GetEffectSettingsComponent(Transform tr) { var parent = tr.parent; if (parent!=null) { effectSettings = parent.GetComponentInChildren<EffectSettings>(); if (effectSettings==null) GetEffectSettingsComponent(parent.transform); } } private void Start() { GetEffectSettingsComponent(transform); if (effectSettings==null) Debug.Log("Prefab root have not script \"PrefabSettings\""); particles = effectSettings.GetComponentsInChildren<ParticleSystem>(); InitDefaultVariables(); isInitialized = true; } void OnEnable() { if(isInitialized) InitDefaultVariables(); } private void InitDefaultVariables() { foreach (var particle in particles) { particle.Stop(); } isFinished = false; tTarget = effectSettings.Target.transform; if (IsRootMove) tRoot = effectSettings.transform; else { tRoot = transform.parent; tRoot.localPosition = Vector3.zero; } targetPos = tRoot.position + Vector3.Normalize(tTarget.position - tRoot.position) * effectSettings.MoveDistance; RaycastHit verticalHit; Physics.Raycast(tRoot.position, Vector3.down, out verticalHit); tRoot.position = verticalHit.point; foreach (var particle in particles) { particle.Play(); } } private void Update() { if (tTarget==null || isFinished) return; var pos = tRoot.position; RaycastHit verticalHit; Physics.Raycast(new Vector3(pos.x, 0.5f, pos.z), Vector3.down, out verticalHit); tRoot.position = verticalHit.point; pos = tRoot.position; var endPoint = effectSettings.IsHomingMove ? tTarget.position : targetPos; var pointOnGround = new Vector3(endPoint.x, 0, endPoint.z); if (Vector3.Distance(new Vector3(pos.x, 0, pos.z), pointOnGround) <= effectSettings.ColliderRadius) { effectSettings.OnCollisionHandler(new CollisionInfo()); isFinished = true; } tRoot.position = Vector3.MoveTowards(pos, pointOnGround, effectSettings.MoveSpeed * Time.deltaTime); } }
using System.Linq; using Com.Ericmas001.Userbase.Models.ServiceInterfaces; using Com.Ericmas001.Userbase.Test.Util; using FluentAssertions; using Unity; using Xunit; namespace Com.Ericmas001.Userbase.Test { [Collection("Com.Ericmas001.Userbase.Test")] public class ManagementTest { [Fact] public void PurgeConnectionTokens() { // Arrange var expiredToken = Values.ExpiredToken; var validToken = Values.ValidToken; var util = new UserbaseSystemUtil(delegate (IUserbaseDbContext model) { model.UserTokens.Add(expiredToken); model.UserTokens.Add(validToken); }); // Act util.Container.Resolve<IManagementService>().PurgeConnectionTokens(); // Assert util.Model.UserTokens.Single().Should().Be(validToken); } [Fact] public void PurgeRecoveryTokens() { // Arrange var expiredRecoveryToken = Values.ExpiredRecoveryToken; var validRecoveryToken = Values.ValidRecoveryToken; var util = new UserbaseSystemUtil(delegate (IUserbaseDbContext model) { model.UserRecoveryTokens.Add(expiredRecoveryToken); model.UserRecoveryTokens.Add(validRecoveryToken); }); // Act util.Container.Resolve<IManagementService>().PurgeRecoveryTokens(); // Assert util.Model.UserRecoveryTokens.Single().Should().Be(validRecoveryToken); } [Fact] public void PurgeUsers() { // Arrange var activeUser = Values.UserSpongeBob; var inactiveUser = Values.UserDora; inactiveUser.Active = false; var util = new UserbaseSystemUtil(delegate (IUserbaseDbContext model) { model.Users.Add(activeUser); model.Users.Add(inactiveUser); }); // Act util.Container.Resolve<IManagementService>().PurgeUsers(); // Assert util.Model.Users.Single().Should().Be(activeUser); } } }
//--------------------------------------------------------------------- // <copyright file="IRelationshipEnd.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System; using System.Collections.Generic; namespace System.Data.EntityModel.SchemaObjectModel { /// <summary> /// Abstracts the properties of an End element in a relationship /// </summary> internal interface IRelationshipEnd { /// <summary> /// Name of the End /// </summary> string Name { get; } /// <summary> /// Type of the End /// </summary> SchemaEntityType Type { get; } /// <summary> /// Multiplicity of the End /// </summary> System.Data.Metadata.Edm.RelationshipMultiplicity? Multiplicity { get; set; } /// <summary> /// The On&lt;Operation&gt;s defined for the End /// </summary> ICollection<OnOperation> Operations { get; } } }
using System; using System.Windows.Forms; using GTA; namespace ScriptInstance { // Main script is auto-started and creates AI scripts using key presses. // T key to spawn AIone // Y key to spawn AItwo // G key to change AIone animation // H key to SetWait(6) for AItwo // J key to pause AIone public class Main : Script { AI AIone = null; AI AItwo = null; public Main() { KeyDown += OnKeyDown; Interval = 1000; } private void OnKeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.T) // Create AI Script and store as AIone { SpawnAIone(); } else if (e.KeyCode == Keys.Y) // Create AI Script and store as AItwo { SpawnAItwo(); } else if (e.KeyCode == Keys.G) // Changes AIone animation { if (AIone != null) { if (AIone.animation == "Jump") { AIone.animation = "HandsUp"; } else { AIone.animation = "Jump"; } GTA.UI.Notification.Show("SpawnAI: Animation(" + AIone.animation + ");"); } } else if (e.KeyCode == Keys.H) // Sets Wait() for AItwo { AItwo.SetWait(6000); } else if (e.KeyCode == Keys.J) // Toggles Pause() for AIone { if (AIone.IsPaused) { AIone.Resume(); } else { AIone.Pause(); } } } private void SpawnAIone() { if (AIone == null) { AIone = InstantiateScript<AI>(); if (AIone != null) { GTA.UI.Notification.Show("SpawnAI: Ped(1);"); } } else { AIone.Abort(); AIone = null; // Clear instance to create a new script next time GTA.UI.Notification.Show("SpawnAI: Ped(1).Abort();"); } } private void SpawnAItwo() { if (AItwo == null || !AItwo.IsRunning) { AItwo = InstantiateScript<AI>(); if (AItwo != null) { GTA.UI.Notification.Show("SpawnAI: Ped(2);"); } } else { AItwo.Abort(); // Instead of setting AItwo to null, can also checking status with 'IsRunning' GTA.UI.Notification.Show("SpawnAI: Ped(2).Abort();"); } } } [ScriptAttributes(NoDefaultInstance = true)] public class AI : Script { public AI() { Tick += OnTick; Aborted += OnShutdown; Interval = 3000; } private Ped ped = null; private int wait = -1; public string animation = "HandsUp"; public void SetWait(int ms) { if (ms > wait) { wait = ms; } } private void OnTick(object sender, EventArgs e) { if (wait > -1) { Wait(wait); wait = -1; } if (ped == null) { ped = World.CreatePed(PedHash.Beach01AMY, Game.Player.Character.Position + (GTA.Math.Vector3.RelativeFront * 3)); } // Repeat animation if alive if (ped != null && ped.IsAlive) { if (animation == "HandsUp") { ped.Task.HandsUp(1000); } else if (animation == "Jump") { ped.Task.Jump(); } } } private void OnShutdown(object sender, EventArgs e) { // Clear pedestrian on script abort ped?.Delete(); } } }
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Public License (Ms-PL). // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details. // All other rights reserved. using Microsoft.Test.CommandLineParsing; using System; using Xunit; using Xunit.Extensions; namespace Microsoft.Test.AcceptanceTests { public class CommandLineParserTests { [Theory] [InlineData("/Verbose", "/RunId=10", true, 10)] // bug! [InlineData("/Verbose=true", "/RunId=10", true, 10)] [InlineData("/Verbose=True", "/RunId=10", true, 10)] [InlineData("/RunId=10", "/Verbose=true", true, 10)] public void TestCommonUsage(string arg1, string arg2, bool? expectedVerbose, int? expectedRunId) { CommandLineArguments a = new CommandLineArguments(); string[] args = new string[] { arg1, arg2 }; a.ParseArguments(args); Assert.Equal<bool?>(expectedVerbose, a.Verbose); Assert.Equal<int?>(expectedRunId, a.RunId); } [Theory] [InlineData("/Verbose", "/RUNID=10", true, 10)] [InlineData("/Verbose", "/RunID=10", true, 10)] [InlineData("/VERBOSE", "/RunId=10", true, 10)] public void CasingScenarios(string arg1, string arg2, bool? expectedVerbose, int? expectedRunId) { CommandLineArguments a = new CommandLineArguments(); string[] args = new string[] { arg1, arg2 }; a.ParseArguments(args); Assert.Equal<bool?>(expectedVerbose, a.Verbose); Assert.Equal<int?>(expectedRunId, a.RunId); } [Theory] [InlineData("/Verbose", "")] [InlineData("", "/RunId=10")] [InlineData("/sample", "/howMany=10")] public void ExceptionsUponMismatchedFields(string arg1, string arg2) { CommandLineArguments a = new CommandLineArguments(); string[] args = new string[] { arg1, arg2 }; Assert.Throws<ArgumentException>( delegate { a.ParseArguments(args); }); } [Theory] [InlineData("/Verbose", "/RunId=true")] // bug in docs [InlineData("/Verbose", "/RunId=10.1")] // bug in docs public void ExceptionsUponMismatchedFields2(string arg1, string arg2) { CommandLineArguments a = new CommandLineArguments(); string[] args = new string[] { arg1, arg2 }; Assert.Throws<Exception>( delegate { a.ParseArguments(args); }); } [Theory] [InlineData("/Verbose=0", "/RunId=10")] // bug in docs public void ExceptionsUponMismatchedFields3(string arg1, string arg2) { CommandLineArguments a = new CommandLineArguments(); string[] args = new string[] { arg1, arg2 }; Assert.Throws<FormatException>( delegate { a.ParseArguments(args); }); } [Fact] public void MoreArgsThanExpectedInTheParsedIntoClass() { CommandLineArguments a = new CommandLineArguments(); string[] args = new string[] { "/Verbose", "/TestId=3", "/RunId=10" }; Assert.Throws<ArgumentException>( delegate { a.ParseArguments(args); }); } // // Supporting classes // protected class CommandLineArguments { public bool? Verbose { get; set; } public int? RunId { get; set; } } } }
using UnityEngine; public class GetPixelsExample : MonoBehaviour { [SerializeField] uDesktopDuplication.Texture uddTexture; [SerializeField] int x = 100; [SerializeField] int y = 100; const int width = 64; const int height = 32; public Texture2D texture; Color32[] colors = new Color32[width * height]; void Start() { texture = new Texture2D(width, height, TextureFormat.ARGB32, false); GetComponent<Renderer>().material.mainTexture = texture; } void Update() { // must be called (performance will be slightly down). uDesktopDuplication.Manager.primary.useGetPixels = true; var monitor = uddTexture.monitor; if (!monitor.hasBeenUpdated) return; if (monitor.GetPixels(colors, x, y, width, height)) { texture.SetPixels32(colors); texture.Apply(); } Debug.Log(monitor.GetPixel(monitor.cursorX, monitor.cursorY)); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using UnityEngine.UI; public class CampaignSaveDataUiElement : MonoBehaviour { [SerializeField] private TextMeshProUGUI CampaignText; private CampaignSaveData SaveData; public CampaignSaveData CurrentSaveData { get { return SaveData; } set { SaveData = value; UpdateUi(); } } private void UpdateUi() { CampaignText.text = SaveData.SaveDataTitle; } public void OnClick() { CampaignPage.Instance.LoadSaveData(SaveData); } }
namespace Extensions { public class ConsumerConfig : BaseKafkaConfig { public string[] SubscriptionTopics { get; set; } public override string DefaultTopic => SubscriptionTopics[0]; public string GroupId { get; set; } } }
using Odachi.CodeGen.TypeScript.StackinoDue.Renderers; using Odachi.CodeGen.TypeScript.StackinoDue.TypeHandlers; using Odachi.CodeModel; using System; using System.Collections.Generic; using System.Text; namespace Odachi.CodeGen.TypeScript.StackinoDue { public static class PackageExtensions { public static void Render_TypeScript_StackinoDue(this Package package, TypeScriptOptions options) { if (package == null) throw new ArgumentNullException(nameof(package)); if (options == null) throw new ArgumentNullException(nameof(options)); var generator = new TypeScriptCodeGenerator(); generator.TypeHandlers.Insert(0, new StackinoDueTypeHandler()); generator.FragmentRenderers.Add(new EnumRenderer()); generator.FragmentRenderers.Add(new ObjectRenderer()); generator.FragmentRenderers.Add(new ServiceRenderer()); generator.Generate(package, options); } } }
using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Text; namespace EventSourcingOnAzureFunctions.Common.Notification { public class NotificationDispatcherNameResolver : INameResolver { private readonly IConfiguration _configuration; public NotificationDispatcherNameResolver(IConfiguration config) { _configuration = config; } public string Resolve(string name) { if (string.IsNullOrEmpty(name)) { return null; } return _configuration[name]; } } }
// Copyright (c) Microsoft. All rights reserved. using System; using Windows.ApplicationModel.Background; using Windows.Devices.Adc; using Windows.System.Threading; using Microsoft.IoT.AdcMcp3008; using Windows.Devices.Adc.Provider; using System.Collections.Generic; // The Background Application template is documented at http://go.microsoft.com/fwlink/?LinkID=533884&clcid=0x409 namespace SampleAdcConsumer { public sealed class StartupTask : IBackgroundTask { BackgroundTaskDeferral deferral; AdcChannel channelZero; AdcChannel channelOne; AdcChannel channelTwo; AdcChannel channelThree; ThreadPoolTimer timer; AdcChannelMode mode; enum ADCProviders { Adx1x15, Mcp3008 } ADCProviders whichProvider = ADCProviders.Mcp3008; public async void Run(IBackgroundTaskInstance taskInstance) { deferral = taskInstance.GetDeferral(); mode = AdcChannelMode.SingleEnded; //mode = AdcChannelMode.Differential; AdcController controller = null; switch (whichProvider) { case ADCProviders.Mcp3008: { controller = (await AdcController.GetControllersAsync(AdcMcp3008Provider.GetAdcProvider()))[0]; } break; case ADCProviders.Adx1x15: { controller = (await AdcController.GetControllersAsync(AdcAds1x15.AdcAds1x15Provider.GetAdcProvider(AdcAds1x15.Ads1x15Type.Ads1115)))[0]; } break; }; controller.ChannelMode = mode; channelZero = controller.OpenChannel(0); channelOne = controller.OpenChannel(1); channelTwo = controller.OpenChannel(2); channelThree = controller.OpenChannel(3); timer = ThreadPoolTimer.CreatePeriodicTimer(this.Tick, TimeSpan.FromMilliseconds(1000)); } void Tick(ThreadPoolTimer sender) { if (mode == AdcChannelMode.SingleEnded) { System.Diagnostics.Debug.WriteLine("0: " + channelZero.ReadValue()); System.Diagnostics.Debug.WriteLine("1: " + channelOne.ReadValue()); System.Diagnostics.Debug.WriteLine("2: " + channelTwo.ReadValue()); System.Diagnostics.Debug.WriteLine("3: " + channelThree.ReadValue()); } else { System.Diagnostics.Debug.WriteLine("0 - 1: " + channelZero.ReadValue()); System.Diagnostics.Debug.WriteLine("0 - 2: " + channelOne.ReadValue()); System.Diagnostics.Debug.WriteLine("1 - 3: " + channelTwo.ReadValue()); System.Diagnostics.Debug.WriteLine("2 - 3: " + channelThree.ReadValue()); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace CommandRunner.Helpers { public class UserHelper { public static async Task<UserInfo> GetUserAsync() { if (File.Exists("./user.lock")) { var file = new FileInfo("./user.lock"); StreamReader stream = file.OpenText(); string content = stream.ReadToEnd(); // UserInfo is null,Init it; if (String.IsNullOrEmpty(content)) { stream.Dispose(); await InitUser(); } else { try { UserInfo user = JsonConvert.DeserializeObject<UserInfo>(content); if (String.IsNullOrEmpty(user.UserName) || String.IsNullOrEmpty(user.Password)) { //UserInfo is null,reinit it. stream.Dispose(); await InitUser(); } else { return user; } } catch (Exception) { // not valid UserInfo,reinit it. stream.Dispose(); await InitUser(); } } } else { await InitUser(); } return default(UserInfo); } // Initial User public static async Task InitUser() { var file = new FileInfo("./user.lock"); FileStream stream = file.OpenWrite(); var defaultUser = new UserInfo { UserName = "admin", Password = BitConverter.ToString(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("MSDev.cc"))) }; byte[] jsonBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(defaultUser)); await stream.WriteAsync(jsonBytes, 0, jsonBytes.Length); stream.Dispose(); } public static async Task EditUserAsync(UserInfo user) { var file = new FileInfo("./user.lock"); FileStream stream = file.OpenWrite(); byte[] jsonBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(user)); await stream.WriteAsync(jsonBytes, 0, jsonBytes.Length); stream.Dispose(); } } public class UserInfo { public string UserName { get; set; } public string Password { get; set; } } }
using System; using System.Linq;using System.Collections.Generic; namespace Diana { public partial class DTuple { public string Classname => "Tuple"; public static DModule module_instance {get; private set;} public static DObj bind_len(DObj[] _args) // bind `this` prop { var nargs = _args.Length; if (nargs != 1) throw new ArgumentException($"accessing Tuple.len; needs only 1 argument, got {nargs}."); var arg = _args[0]; var ret = MK.unbox(THint<DObj[]>.val, arg).Length; return MK.create(ret); } public static DObj bind_of(DObj[] _args) // bind method { var nargs = _args.Length; if (nargs != 1) throw new ArgumentException($"calling Tuple.of; needs at least (1) arguments, got {nargs}."); var _arg0 = MK.unbox(THint<IEnumerable<DObj>>.val, _args[0]); { var _return = _arg0.ToArray(); return MK.create(_return); } throw new ArgumentException($"call Tuple.of; needs at most (1) arguments, got {nargs}."); } public static DObj bind_forkey(DObj[] _args) // bind method { var nargs = _args.Length; if (nargs != 2) throw new ArgumentException($"calling Tuple.forkey; needs at least (2) arguments, got {nargs}."); var _arg0 = MK.unbox(THint<DObj[]>.val, _args[0]); var _arg1 = MK.unbox(THint<DObj>.val, _args[1]); { _arg0.ForEachIndex_(_arg1); return MK.None(); } throw new ArgumentException($"call Tuple.forkey; needs at most (2) arguments, got {nargs}."); } static DTuple() { module_instance = new DModule("Tuple"); module_instance.fields.Add("len", MK.FuncN("Tuple.len", bind_len)); module_instance.fields.Add("of", MK.FuncN("Tuple.of", bind_of)); module_instance.fields.Add("forkey", MK.FuncN("Tuple.forkey", bind_forkey)); } } }
namespace PhotoDealer.Web.Infrastructure.Search { using System.ComponentModel; using System.ComponentModel.DataAnnotations; public class SearchViewModel { public string Title { get; set; } public string Author { get; set; } [DisplayName("Price From")] public decimal PriceFrom { get; set; } [DisplayName("Price To")] public decimal PriceTo { get; set; } public string Tag { get; set; } [DisplayName("Category Group")] [UIHint("CategoryGroup")] public int CategoryGroup { get; set; } [UIHint("Category")] public int Category { get; set; } public OrderByEnum OrderBy { get; set; } public OrderTypeEnum OrderType { get; set; } public int Page { get; set; } public PageTypeEnum PageType { get; set; } [DisplayName("Picture Type")] public OwnerTypeEnum OwnerType { get; set; } } }
using Rabbit.Kernel.Caching; using Rabbit.Kernel.Environment.Assemblies.Models; using System; using System.Reflection; namespace Rabbit.Kernel.FileSystems.Dependencies { /// <summary> /// 一个抽象的程序集探测文件夹。 /// </summary> public interface IAssemblyProbingFolder : IVolatileProvider { /// <summary> /// 程序集是否存在。 /// </summary> /// <param name="descriptor">程序集描述符。</param> /// <returns>true为存在,false为不存在。</returns> bool AssemblyExists(AssemblyDescriptor descriptor); /// <summary> /// 获取程序集的最后修改的Utc时间,如果不存在则返回null。 /// </summary> /// <param name="descriptor">程序集描述符。</param> /// <returns>Utc时间。</returns> DateTime? GetAssemblyDateTimeUtc(AssemblyDescriptor descriptor); /// <summary> /// 获取程序集的虚拟路径。 /// </summary> /// <param name="descriptor">程序集描述符。</param> /// <returns>虚拟路径。</returns> string GetAssemblyVirtualPath(AssemblyDescriptor descriptor); /// <summary> /// 装载程序集。 /// </summary> /// <param name="descriptor">程序集描述符。</param> /// <returns>程序集。</returns> Assembly LoadAssembly(AssemblyDescriptor descriptor); /// <summary> /// 删除程序集。 /// </summary> /// <param name="descriptor">程序集描述符。</param> void DeleteAssembly(AssemblyDescriptor descriptor); /// <summary> /// 存储程序集。 /// </summary> /// <param name="descriptor">程序集描述符。</param> /// <param name="fileName">程序集文件名称。</param> void StoreAssembly(AssemblyDescriptor descriptor, string fileName); /// <summary> /// 删除程序集。 /// </summary> /// <param name="moduleName">模块名称。</param> void DeleteAssembly(string moduleName); /// <summary> /// 存储程序集。 /// </summary> /// <param name="moduleName">模块名称。</param> void StoreAssembly(string moduleName); } }
using System.Collections.Generic; namespace HouseScraper.Scraper.ScrapeItems { /// <summary> /// Factory to make new properties /// </summary> public class PropertyFactory : AbstractItemFactory<Property> { /// <summary> /// Make new property from list of stringified attributes /// </summary> /// <param name="strings">List of strings to match property attributes</param> /// <returns>Property</returns> public override Property FromStringList(List<string> strings) { return new Property(strings[0], strings[1], strings[2], strings[3], strings[4], strings[5]); } } }
using System; using JetBrains.Annotations; namespace PowerGenerator { public sealed class Generator : IGenerator { private static int _autoId; [NotNull] private static readonly Random Random; static Generator() { Random = new Random(); } public Generator(int capacity, string name) { Capacity = capacity; Name = name; Type = Random.Next(1, 4); Id = ++_autoId; } public int Type { get; set; } public int Capacity { get; set; } public string Name { get; set; } public int Id { get; set; } public override string ToString() { return string.Format("Generator {0} with capacity {1} MWh", Name, Capacity); } } }
using System.IO; using System.Reflection; using System.Xml.Linq; namespace AlbLib { namespace Internal { /// <summary> /// Class for accessing embedded XML resources. /// </summary> internal static class Resources { /// <summary> /// When this set on, this class will load resources only from this assembly. /// </summary> public static bool AlwaysUseEmbedded{get;set;} /// <summary> /// Loads a XML resource. /// </summary> /// <param name="name"> /// Resource name. /// </param> /// <returns> /// XML document. /// </returns> public static XDocument GetResource(string name) { if(File.Exists(name) && !AlwaysUseEmbedded) { return XDocument.Load(name); }else{ return XDocument.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream(name)); } } private static XDocument functions; /// <summary> /// functions /// |- function: /// name = Function name. /// parameters = Number of parameters. /// </summary> public static XDocument Functions{ get{ if(functions == null) { functions = GetResource("Functions.xml"); } return functions; } } private static XDocument data; /// <summary> /// files /// |- file: /// name = File name. /// type = File type. /// </summary> public static XDocument FileData{ get{ if(data == null) { data = GetResource("Data.xml"); } return data; } } private static XDocument chartable; /// <summary> /// chartable /// |- [treename]: /// char = Unicode character. /// code = Byte code. /// </summary> public static XDocument CharTable{ get{ if(chartable == null) { chartable = GetResource("CharTable.xml"); } return chartable; } } } } }
namespace MassTransit.Registration { using GreenPipes; public interface IBusInstanceSpecification : ISpecification { void Configure(IBusInstance busInstance); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using DAL.App.DTO.OrderModels; using Microsoft.AspNetCore.Identity; namespace DAL.App.DTO.Identity { public class AppUser : IdentityUser<Guid> // , IDomainEntityId { [Required] [StringLength(128, MinimumLength = 1)] public string FirstName { get; set; } = null!; [StringLength(128, MinimumLength = 1)] [Required] public string LastName { get; set; } = null!; public DateTime Birthdate { get; set; } public ICollection<Restaurant>? Restaurants { get; set; } public ICollection<Order>? Orders { get; set; } public ICollection<CreditCard>? CreditCards { get; set; } public ICollection<Contact>? Contacts { get; set; } } }
using System.IO; namespace SelfishMeme { public class Simulation : ISimulation { private readonly TextWriter outputStream; private readonly IBreedingSeasonFactory breedingSeasonFactory; private readonly int breedingSeasons; private IPopulation currentPopulation; public Simulation(Population initialPopulation , IBreedingSeasonFactory breedingSeasonFactory , int breedingSeasons , TextWriter outputStream) { this.currentPopulation = initialPopulation; this.breedingSeasonFactory = breedingSeasonFactory; this.breedingSeasons = breedingSeasons; this.outputStream = outputStream; } public void Run() { for (int i = 0; i < breedingSeasons; i++) { currentPopulation.WriteOutput(outputStream); var nextPopulation = GetNextPopulation(currentPopulation); currentPopulation = nextPopulation; } } private IPopulation GetNextPopulation(IPopulation currentPopulation) { var breedingSeason = breedingSeasonFactory.Build(currentPopulation); breedingSeason.ResolveConfrontations(); return breedingSeason.GetNewPopulation(); } } }
// DocSection: linked_content_get_page_with_subpages // Tip: Find more about .NET SDKs at https://docs.kontent.ai/net using Kentico.Kontent.Delivery; // Creates an instance of the delivery client // ProTip: Use DI for this in your apps https://docs.kontent.ai/net-register-client IDeliveryClient client = DeliveryClientBuilder .WithProjectId("8d20758c-d74c-4f59-ae04-ee928c0816b7") .Build(); // Gets a specific page, its subpages, and linked items // Create strongly typed models according to https://docs.kontent.ai/net-strong-types IDeliveryItemResponse<Page> response = await client.GetItemAsync<Page>("insurance_listing", new DepthParameter(1) ); Page item = response.Item; // EndDocSection
namespace DotnetNativeInterop { public class Program { static void Main() { using var window = new MyWindow(); Thread.Sleep(1000); window.Clear(0, 0xff, 0); Thread.Sleep(1000); window.Clear(0, 0, 0xff); Thread.Sleep(1000); window.Clear(0xff, 0, 0); Thread.Sleep(1000); } } }
namespace TONBRAINS.TONOPS.WebApp.Common.Models { public class ModuleLoggingModel : ModuleModel { public LoggingModel Logging { get; set; } } }
using OpenRasta.Web; namespace OpenRasta.CommunicationFeatures { public static class CommunicationExtensions { public static void Feature<T>(this ICommunicationContext context, T feature) { context.PipelineData[GetFeatureKey<T>()] = feature; } public static bool Feature<T>(this ICommunicationContext context, out T feature) where T : class { if (!context.PipelineData.TryGetValue(GetFeatureKey<T>(), out var untypedFeature)) { feature = null; return false; } feature = (T) untypedFeature; return true; } static string GetFeatureKey<T>() { return $"openrasta.{typeof(T).Name}"; } } }
using System; using System.Runtime.Serialization; using Orchard.Localization; namespace Orchard.Commands { [Serializable] public class OrchardCommandHostRetryException : OrchardCoreException { public OrchardCommandHostRetryException(LocalizedString message) : base(message) { } public OrchardCommandHostRetryException(LocalizedString message, Exception innerException) : base(message, innerException) { } protected OrchardCommandHostRetryException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using UnityEngine; using UnityEngine.Events; using UnityEngine.EventSystems; namespace Common.Unity.Cameras { public class SimpleCameraController2D : MonoBehaviour { private class CameraState { public Vector3 position; public float size; } [SerializeField] private UnityEvent m_cameraMovedEvent; [SerializeField] private float m_positionSpeed = 10f; [SerializeField] private float m_positionLerpTime = 0.2f; [SerializeField] private float m_zoomSpeed = 10f; [SerializeField] private float m_zoomMin = 1.0f; [SerializeField] private float m_zoomMax = 100.0f; [SerializeField] private float m_zoomLerpTime = 0.2f; private Camera m_camera; private CameraState m_targetCameraState = new CameraState(); private CameraState m_interpolatingCameraState = new CameraState(); private bool m_moved; private void OnEnable() { m_camera = GetComponent<Camera>(); m_targetCameraState.position = transform.position; m_targetCameraState.size = m_camera.orthographicSize; m_interpolatingCameraState.position = transform.position; m_interpolatingCameraState.size = m_camera.orthographicSize; } private void Update() { m_moved = false; var translation = GetTranslationDirection(); var scroll = GetScrollAmount(); m_targetCameraState.position += translation; m_targetCameraState.size += scroll; m_targetCameraState.size = Mathf.Clamp(m_targetCameraState.size, m_zoomMin, m_zoomMax); LerpTowards(m_interpolatingCameraState, m_targetCameraState); transform.position = m_interpolatingCameraState.position; m_camera.orthographicSize = m_interpolatingCameraState.size; if (m_moved) m_cameraMovedEvent.Invoke(); } public void Enable() { enabled = true; } public void Disable() { enabled = false; } private Vector3 GetTranslationDirection() { Vector3 direction = new Vector3(); if (Input.GetKey(KeyCode.W)) { m_moved = true; direction += Vector3.up; } if (Input.GetKey(KeyCode.S)) { m_moved = true; direction += Vector3.down; } if (Input.GetKey(KeyCode.A)) { m_moved = true; direction += Vector3.left; } if (Input.GetKey(KeyCode.D)) { m_moved = true; direction += Vector3.right; } return direction * Time.deltaTime * m_positionSpeed; } private float GetScrollAmount() { float delta = Input.mouseScrollDelta.y; if (delta != 0) m_moved = true; return Input.mouseScrollDelta.y * Time.deltaTime * -m_zoomSpeed; } private void LerpTowards(CameraState state, CameraState target) { var positionLerp = 1f - Mathf.Exp((Mathf.Log(1f - 0.99f) / m_positionLerpTime) * Time.deltaTime); var zoomLerp = 1f - Mathf.Exp((Mathf.Log(1f - 0.99f) / m_zoomLerpTime) * Time.deltaTime); state.position = Vector3.Lerp(state.position, target.position, positionLerp); state.size = Mathf.Lerp(state.size, target.size, zoomLerp); } } }
using System; using System.Collections.Generic; namespace Elvet.FridayNightLive.Data { internal class Session { public ulong GuildId { get; set; } public int Number { get; set; } public DateTime? Date { get; set; } public List<SessionWinner> Winners { get; set; } = new(); public List<SessionHost> Hosts { get; set; } = new(); public string Activity { get; set; } = string.Empty; } }
using System.ComponentModel.DataAnnotations; using DataAnnotationsExtensions; using SharpLite.Domain; using SharpLite.Domain.Validators; namespace CaTS.Domain { [HasUniqueDomainSignature( ErrorMessage = "A customer already exists with the provided account number")] public class Customer : Entity { [DomainSignature] [Required(ErrorMessage = "Account number must be provided")] [StringLength(8, MinimumLength = 8, ErrorMessage = "Account number must be exactly 8 characters")] [Display(Name = "Account Number")] public virtual string AccountNumber { get; set; } [Required(ErrorMessage = "First name must be provided")] [StringLength(200, ErrorMessage = "First name must be 200 characters or fewer")] [Display(Name = "First Name")] public virtual string FirstName { get; set; } [Required(ErrorMessage = "Last name must be provided")] [StringLength(200, ErrorMessage = "Last name must be 200 characters or fewer")] [Display(Name = "Last Name")] public virtual string LastName { get; set; } [Email] [Required(ErrorMessage = "Email address must be provided")] [StringLength(200, ErrorMessage = "Email must be 200 characters or fewer")] [Display(Name = "Email")] public virtual string EmailAddress { get; set; } } }
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using EdFi.Common.Configuration; using EdFi.Common.Extensions; namespace EdFi.Ods.Common.Configuration { public class ApiSettings { private readonly Lazy<DatabaseEngine> _databaseEngine; private readonly Lazy<ApiMode> _apiMode; public ApiSettings() { _databaseEngine = new Lazy<DatabaseEngine>(() => DatabaseEngine.TryParseEngine(Engine)); _apiMode = new Lazy<ApiMode>( () => { if (ApiMode.TryParse(x => x.Value.EqualsIgnoreCase(Mode), out ApiMode apiMode)) { return apiMode; } throw new NotSupportedException( $"Not supported Mode \"{Mode}\". Supported modes: {ApiConfigurationConstants.Sandbox}, {ApiConfigurationConstants.YearSpecific}, and {ApiConfigurationConstants.SharedInstance}."); } ); } public string Mode { get; set; } public string Engine { get; set; } public bool PlainTextSecrets { get; set; } public int[] Years { get; set; } public List<Feature> Features { get; set; } = new List<Feature>(); public List<string> ExcludedExtensions { get; set; } = new List<string>(); public bool? UseReverseProxyHeaders { get; set; } public string PathBase { get; set; } public DatabaseEngine GetDatabaseEngine() => _databaseEngine.Value; public ApiMode GetApiMode() => _apiMode.Value; public bool IsFeatureEnabled(string featureName) => Features.SingleOrDefault(x => x.Name.EqualsIgnoreCase(featureName) && x.IsEnabled) != null; } }
using System; namespace NAudio.Midi { /// <summary> /// MIDI MetaEvent Type /// </summary> public enum MetaEventType : byte { /// <summary>Track sequence number</summary> TrackSequenceNumber = 0x00, /// <summary>Text event</summary> TextEvent = 0x01, /// <summary>Copyright</summary> Copyright = 0x02, /// <summary>Sequence track name</summary> SequenceTrackName = 0x03, /// <summary>Track instrument name</summary> TrackInstrumentName = 0x04, /// <summary>Lyric</summary> Lyric = 0x05, /// <summary>Marker</summary> Marker = 0x06, /// <summary>Cue point</summary> CuePoint = 0x07, /// <summary>Program (patch) name</summary> ProgramName = 0x08, /// <summary>Device (port) name</summary> DeviceName = 0x09, /// <summary>MIDI Channel (not official?)</summary> MidiChannel = 0x20, /// <summary>MIDI Port (not official?)</summary> MidiPort = 0x21, /// <summary>End track</summary> EndTrack = 0x2F, /// <summary>Set tempo</summary> SetTempo = 0x51, /// <summary>SMPTE offset</summary> SmpteOffset = 0x54, /// <summary>Time signature</summary> TimeSignature = 0x58, /// <summary>Key signature</summary> KeySignature = 0x59, /// <summary>Sequencer specific</summary> SequencerSpecific = 0x7F, } }
using System; using System.Text; namespace EncodeDecode_Variant { public class EncodeDecodeWithKey { public static void Main() { // idea - if cipher is longer then message -> continue encrypt string message = Console.ReadLine(); string cipher = Console.ReadLine(); Console.WriteLine(message); string encoded = Encrypt(message, cipher); Console.WriteLine(encoded); string decoded = Encrypt(encoded, cipher); Console.WriteLine(decoded); } private static string Encrypt(string message, string cipher) { var result = new StringBuilder(message); var steps = Math.Max(message.Length, cipher.Length); for (int step = 0; step < steps; step++) { var messageIndex = step % message.Length; var cypherIndex = step % cipher.Length; result[messageIndex] = (char)(result[messageIndex] ^ cipher[cypherIndex]); // Console.WriteLine(result[messageIndex].ToString()); } return result.ToString(); ; } } }
using System; using Windows.UI.Xaml.Data; namespace Emlid.UniversalWindows.UI.Converters { /// <summary> /// Null test to boolean one-way value converter. /// </summary> /// <remarks> /// Converts null to false and non-null to true, any object type. /// </remarks> public class NullBoolValueConverter : IValueConverter { /// <summary> /// Modifies the source data before passing it to the target for display in the UI. /// </summary> public object Convert(object value, Type targetType, object parameter, string language) { // Return false when null return ReferenceEquals(value, null); } /// <summary> /// Two-way bindings are not supported. /// </summary> public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotSupportedException(); } } }
using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; namespace Sharpen.Engine.Analysis { // We have a slight terminology issue here. Users talk about files. // Roslyn talks about documents. For the code identifiers we will // use the term documents. For the user messages we will use files. public sealed class MultipleDocumentsScopeAnalyzer : BaseScopeAnalyzer { private readonly IReadOnlyCollection<Document> documents; public MultipleDocumentsScopeAnalyzer() : this((IReadOnlyCollection<Document>)null) { } // Will end up in a user friendly error message. public MultipleDocumentsScopeAnalyzer(Document document) : this(document == null ? null : new [] {document}) { } public MultipleDocumentsScopeAnalyzer(IReadOnlyCollection<Document> documents) // Documents collection can be null. { this.documents = documents; } protected override string GetCanExecuteScopeAnalysisErrorMessage() { if (documents == null || documents.Count <= 0) { return "There are no files selected or the selected files do not belong to the solution."; } // We can still have a situation that users call the analysis on a custom generated // file that has the <auto-generated> comment. In that case the analysis will be skipped // by the engine and will always return zero results without any warning provided to the // user that the analysis will in fact not run. // So far we will leave it like this. It's an unlikely corner case and we do not want to // add performance penalty on regular case by double-checking here if the file content // is generated. if (!documents.Any(DocumentShouldBeAnalyzed)) { return "The selected files do not contain any C# files that could be analyzed."; } return null; } protected override string ScopeAnalysisHelpMessage => "To start file analysis, select at least one non-generated C# file that belongs to the solution."; protected override IEnumerable<Document> GetDocumentsToAnalyze() { return documents ?? Enumerable.Empty<Document>(); } } }
using System.Web.Mvc; namespace SFA.DAS.EmployerAccounts.Web.ViewModels { public class RenameEmployerAccountViewModel : ViewModelBase { public string HashedId { get; set; } [AllowHtml] public string CurrentName { get; set; } [AllowHtml] public string NewName { get; set; } public string NewNameError => GetErrorMessage(nameof(NewName)); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ConsumableScript : ItemScript { public static int MAX_BONUS_VALUE = 10; [Range(0, 100)] [SerializeField] private int defaultHealValue; [Range(0, 100)] [SerializeField] private int healValue; private void Awake() { type = ItemType.Consumable; } protected override void Start() { base.Start(); } protected override void Update() { base.Update(); } public int GetHealValue() { return this.healValue; } public int GetDefaultHealValue() { return defaultHealValue; } public void SetHealValue(int healVal) { this.healValue = healVal; } public int Consume() { int retVal = this.healValue; return retVal; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class InputInteractable : MonoBehaviour { [Header("Settings")] [SerializeField] bool _onlyOnce; [SerializeField] UnityEvent _pressEvent; [SerializeField] UnityEvent _releaseEvent; [SerializeField] Condition _condition; [SerializeField] [Range(0, 20)] float _distance; enum Condition { Distance, Logic } bool _done; public bool Ready = true; bool _pressInteractionCalled; Transform _target; private void Start() { _target = FindObjectOfType<InteractionTrigger>().transform; } public void PressInteraction() { if (_onlyOnce && _done) return; bool execute = false; ; switch (_condition) { case Condition.Distance: if (_target != null && Vector3.Distance(transform.position, _target.position) < _distance) execute = true; break; case Condition.Logic: execute = Ready; break; default: break; } if (execute) { _pressEvent.Invoke(); _pressInteractionCalled = true; } } public void ReleaseInteraction() { if (_onlyOnce && _done) return; if (_pressInteractionCalled) { _done = true; _releaseEvent.Invoke(); //Reset boolean for next PressInteraction _pressInteractionCalled = false; } } public void SetLogicReady(bool ready) { Ready = ready; } private void OnDrawGizmos() { Gizmos.color = Color.yellow; Gizmos.DrawWireSphere(transform.position, _distance); } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reflection; using System.Text; namespace DMM.Common.Configuration { [ConfigurationCollection(typeof(BehaviorConfigurationElement), AddItemName = "behavior")] public class BehaviorSectionsCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new BehaviorConfigurationElement(); } protected override object GetElementKey(ConfigurationElement element) { BehaviorConfigurationElement section = (BehaviorConfigurationElement)element; return section.Type; } } }
using System; namespace Documentos.Clases { public class Factura : Documento { public Factura(Cliente cliente) : base(cliente: cliente) { } public override void Imprimir() { Console.WriteLine($"Factura para: {this._cliente.Presentarse()}"); Console.WriteLine($"Imprimiendo factura No. {_numero} con fecha {_fecha}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _08.MilitaryElite { public abstract class SpecialisedSoldier : Private, ISpecialisedSoldier { private string corps; protected SpecialisedSoldier(int id, string firstName, string lastName, double salary, string corps) : base(id, firstName, lastName, salary) { this.Corps = corps; } public string Corps { get { return corps; } set { if (!value.Equals("Airforces") && !value.Equals("Marines")) { throw new ArgumentException("Invalid corps time"); } corps = value; } } public override string ToString() { return string.Format($"{base.ToString()}{Environment.NewLine}Corps: {this.Corps}"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PullTracker : MonoBehaviour { private ParasiteHead p_head; private SpriteRenderer sr; private GameObject tracker; private void Awake () { p_head = GameObject.FindWithTag("ParasiteHead").GetComponent<ParasiteHead>(); sr = GetComponent<SpriteRenderer>(); tracker = GameObject.Find("MouseTrackerReverse").gameObject; } // Update is called once per frame void Update() { if(p_head.IsGrabbed()) { if(!sr.enabled) sr.enabled = true; if(!tracker.activeSelf) tracker.SetActive(true); Vector3 p_pos = p_head.transform.position; Vector3 m_pos = Camera.main.ScreenToWorldPoint(Input.mousePosition); m_pos.z = 0; Vector3 p_m_diff = p_pos - m_pos; Vector3 m_pos_reverse = p_pos + p_m_diff; Vector3 p_mr_diff = m_pos_reverse - p_pos; Vector3 mid_point = Vector3.Lerp(p_pos, m_pos_reverse, 0.5f); transform.position = mid_point; transform.localScale = new Vector3(transform.localScale.x, p_mr_diff.magnitude, 1); float angle = Vector3.SignedAngle(Vector3.up, p_mr_diff, Vector3.forward); transform.localEulerAngles = new Vector3(0,0,angle); tracker.transform.position = m_pos_reverse; } else { if (sr.enabled) sr.enabled = false; if(tracker.activeSelf) tracker.SetActive(false); } } }
//--------------------------------------------------------------------- // <copyright file="ThreadGetSetDataRule.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace DataWebRules { using Microsoft.FxCop.Sdk; /// <summary> /// This rule checks that Thread.GetData and Thread.SetData aren't used. /// </summary> public class ThreadGetSetDataRule : BaseDataWebRule { private Method methodUnderCheck; /// <summary>Initializes a new <see cref="ThreadGetSetDataRule"/> instance.</summary> public ThreadGetSetDataRule() : base("ThreadGetSetDataRule") { } /// <summary>Visibility of targets to which this rule commonly applies.</summary> public override TargetVisibilities TargetVisibility { get { return TargetVisibilities.All; } } /// <summary>Checks type members.</summary> /// <param name="member">Member being checked.</param> /// <returns>A collection of problems found in <paramref name="member"/> or null.</returns> public override ProblemCollection Check(Member member) { Method method = member as Method; if (method == null) { return null; } methodUnderCheck = method; Visit(method); return Problems.Count > 0 ? Problems : null; } /// <summary>Visits a constructor invocation.</summary> /// <param name="cons">Construction.</param> /// <returns>Resulting expression to visit.</returns> public override void VisitMethodCall(MethodCall methodCall) { if (methodCall != null) { MemberBinding callBinding = methodCall.Callee as MemberBinding; if (callBinding != null) { Method method = callBinding.BoundMember as Method; if (method != null && method.DeclaringType.Namespace.Name == "System.Threading" && method.DeclaringType.Name.Name == "Thread" && (method.Name.Name == "GetData" || method.Name.Name == "SetData")) { this.Problems.Add(new Problem(GetResolution(methodUnderCheck.FullName))); } } } base.VisitMethodCall(methodCall); } } }
using Microsoft.Extensions.Logging; namespace OmniSharp.MSBuild.Discovery { internal static class Extensions { public static void RegisterDefaultInstance(this IMSBuildLocator msbuildLocator, ILogger logger) { MSBuildInstance instanceToRegister = null; var invalidVSFound = false; foreach (var instance in msbuildLocator.GetInstances()) { if (instance.IsInvalidVisualStudio()) { invalidVSFound = true; } else { instanceToRegister = instance; break; } } if (instanceToRegister != null) { // Did we end up choosing the standalone MSBuild because there was an invalid Visual Studio? // If so, provide a helpful message to the user. if (invalidVSFound && instanceToRegister.DiscoveryType == DiscoveryType.StandAlone) { logger.LogWarning(@"It looks like you have Visual Studio 2017 RTM installed. Try updating Visual Studio 2017 to the most recent release to enable better MSBuild support."); } msbuildLocator.RegisterInstance(instanceToRegister); } else { logger.LogError("Could not locate MSBuild instance to register with OmniSharp"); } } public static bool IsInvalidVisualStudio(this MSBuildInstance instance) // MSBuild from Visual Studio 2017 RTM cannot be used. => instance.Version.Major == 15 && instance.Version.Minor == 0 && (instance.DiscoveryType == DiscoveryType.DeveloperConsole || instance.DiscoveryType == DiscoveryType.VisualStudioSetup); } }
using System; using System.Collections.Generic; using MongoDB.Bson.Serialization.Attributes; namespace Hangfire.Mongo.Dto { #pragma warning disable 1591 public class StateDto { [BsonElement(nameof(Name))] public string Name { get; set; } [BsonElement(nameof(Reason))] public string Reason { get; set; } [BsonElement(nameof(CreatedAt))] public DateTime CreatedAt { get; set; } [BsonElement(nameof(Data))] public Dictionary<string, string> Data { get; set; } } #pragma warning restore 1591 }
using Microsoft.AspNetCore.Mvc; using TLDR.Models; using System; using System.Threading.Tasks; namespace TLDR.Web.Services { public interface IAuthorItemService { IActionResult GetAuthorById(Guid id); IActionResult GetAllAuthors(); Task<IActionResult> CreateAuthor(AuthorItem value); Task<IActionResult> UpdateAuthor(AuthorItemResponse value); Task<IActionResult> DeleteAuthor(Guid id); } }
using UnityEngine; using System.Collections; public class Mole : MonoBehaviour { public float moveDistance; public float moveTime; public float waitTime; public TextMesh letterLabel; public float shakeAmplitude; public float scaleTo; public char Letter { get { return letterLabel.text[0]; } } float startY; float wait = 0.0f; float dir = 0.0f; void Start() { startY = transform.position.y; } public void Activate() { if ( gameObject.activeSelf ) { Debug.LogWarning("Mole double activation!"); } gameObject.SetActive(true); dir = 1.0f; wait = 0.0f; } public void SetLetter(char letter) { letterLabel.text = letter.ToString(); } public void Hit() { MoveDown(); StartCoroutine(HitEffect()); } public void Miss() { MoveDown(); StartCoroutine(MissEffect()); } void Update() { if ( wait > 0.0f ) { wait -= Time.deltaTime; } else { transform.Translate(Vector3.up * dir * (moveDistance/moveTime) * Time.deltaTime); if ( dir > 0.0f && transform.position.y >= startY + moveDistance ) { MoveDown(); } else if ( dir < 0.0f && transform.position.y <= startY ) { gameObject.SetActive(false); } } } void MoveDown() { wait = waitTime; dir = -1.0f; } IEnumerator HitEffect() { float t = 0.0f; while ( t <= 1.0f ) { t += Time.deltaTime / waitTime; transform.rotation = Quaternion.Euler(0.0f, 0.0f, Random.Range(-shakeAmplitude, shakeAmplitude)); yield return null; } transform.rotation = Quaternion.identity; } IEnumerator MissEffect() { float t = 0.0f; Vector3 scaleStart = transform.localScale; Vector3 scaleEnd = scaleStart * scaleTo; while ( t <= 1.0f ) { t += Time.deltaTime / (waitTime/2.0f); transform.localScale = Vector3.Lerp(scaleStart, scaleEnd, t); yield return null; } t = 0.0f; while ( t <= 1.0f ) { t += Time.deltaTime / (waitTime/2.0f); transform.localScale = Vector3.Lerp(scaleEnd, scaleStart, t); yield return null; } } }
using GrocerySupplyManagementApp.DTOs; namespace GrocerySupplyManagementApp.Repositories.Interfaces { public interface ICapitalRepository { decimal GetMemberTotalBalance(UserTransactionFilter userTransactionFilter); decimal GetSupplierTotalBalance(SupplierTransactionFilter supplierTransactionFilter); decimal GetTotalSalesAndReceipt(CapitalTransactionFilter capitalTransactionFilter); decimal GetTotalPurchaseAndPayment(CapitalTransactionFilter capitalTransactionFilter); decimal GetTotalBankTransfer(CapitalTransactionFilter capitalTransactionFilter); decimal GetTotalExpense(CapitalTransactionFilter capitalTransactionFilter); decimal GetOpeningCashBalance(string endOfDay); decimal GetOpeningCreditBalance(string endOfDay); decimal GetCashBalance(string endOfDay); decimal GetCreditBalance(string endOfDay); decimal GetTotalCashPayment(string endOfDay); decimal GetTotalChequePayment(string endOfDay); decimal GetTotalBalance(string endOfDay, string action, string actionType); } }
using YourBrand.Domain.Common; namespace YourBrand.Domain.Events; public class CommentPostedEvent : DomainEvent { public CommentPostedEvent(string itemId, string commentId) { this.ItemId = itemId; CommentId = commentId; } public string ItemId { get; } public string CommentId { get; } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Diagnostics; using System.ComponentModel; using Microsoft.Practices.EnterpriseLibrary.Validation; using ESRI.ArcLogistics.Data; using ESRI.ArcLogistics.Geocoding; using ESRI.ArcLogistics.Geometry; using ESRI.ArcLogistics.DomainObjects.Validation; using ESRI.ArcLogistics.DomainObjects.Attributes; using DataModel = ESRI.ArcLogistics.Data.DataModel; using System.Collections; namespace ESRI.ArcLogistics.DomainObjects { /// <summary> /// Class that represents a location. /// </summary> /// <remarks>Typically location is a depot or warehouse.</remarks> public class Location : DataObject, IMarkableAsDeleted, IGeocodable, ISupportOwnerCollection { #region constants /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Name of the Name property. /// </summary> public static string PropertyNameName { get { return PROP_NAME_Name; } } /// <summary> /// Name of the Comment property /// </summary> public static string PropertyNameComment { get { return PROP_NAME_Comment; } } /// <summary> /// Name of the CurbApproach property /// </summary> public static string PropertyNameCurbApproach { get { return PROP_NAME_CurbApproach; } } /// <summary> /// Name of the TimeWindow property /// </summary> public static string PropertyNameTimeWindow { get { return PROP_NAME_TimeWindow; } } /// <summary> /// Name of the TimeWindow2 property /// </summary> public static string PropertyNameTimeWindow2 { get { return PROP_NAME_TimeWindow2; } } /// <summary> /// Name of the Address property. /// </summary> public static string PropertyNameAddress { get { return PROP_NAME_Address; } } /// <summary> /// Name of the GeoLocation property /// </summary> public static string PropertyNameGeoLocation { get { return PROP_NAME_GeoLocation; } } #endregion constants #region constructors /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Initializes a new instance of the <c>Location</c> class. /// </summary> public Location() : base(DataModel.Locations.CreateLocations(Guid.NewGuid())) { // Enable address validation. IsAddressValidationEnabled = true; _Entity.CurbApproach = (int)Defaults.Instance.LocationsDefaults.CurbApproach; _timeWindow.IsWideOpen = Defaults.Instance.LocationsDefaults.TimeWindow.IsWideopen; if (!_timeWindow.IsWideOpen) { _timeWindow.From = Defaults.Instance.LocationsDefaults.TimeWindow.From; _timeWindow.To = Defaults.Instance.LocationsDefaults.TimeWindow.To; _timeWindow.Day = 0; } _UpdateTimeWindowEntityData(); _UpdateTimeWindow2EntityData(); _timeWindow.PropertyChanged += new PropertyChangedEventHandler(_TimeWindowPropertyChanged); _SubscribeToAddressEvent(); base.SetCreationTime(); } /// <summary> /// Initializes a new instance of the <c>Location</c> class. /// </summary> /// <param name="entity">Entity data.</param> internal Location(DataModel.Locations entity) : base(entity) { Debug.Assert(0 < entity.CreationTime); // NOTE: must be inited // Enable address validation. IsAddressValidationEnabled = true; // init holder objects _InitTimeWindow(entity); _InitTimeWindow2(entity); _InitAddress(entity); _InitGeoLocation(entity); } #endregion constructors #region public members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Gets the object's type title. /// </summary> public override string TypeTitle { get { return Properties.Resources.Location; } } /// <summary> /// Gets the object's globally unique identifier. /// </summary> public override Guid Id { get { return _Entity.Id; } } /// <summary> /// Gets\sets object creation time. /// </summary> /// <exception cref="T:System.ArgumentNullException">Although property can get null value /// (for backward compatibility with existent plug-ins) it is not actually supported.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException">Although property can get 0 or less value /// (for backward compatibility with existent plug-ins) it is not actually supported.</exception> public override long? CreationTime { get { Debug.Assert(0 < _Entity.CreationTime); // NOTE: must be inited return _Entity.CreationTime; } set { if (!value.HasValue) throw new ArgumentNullException(); // exception if (value.Value <= 0) throw new ArgumentOutOfRangeException(); // exception _Entity.CreationTime = value.Value; } } /// <summary> /// Location name. /// </summary> [DomainProperty("DomainPropertyNameName", true)] [DuplicateNameValidator] [NameNotNullValidator] public override string Name { get { return _Entity.Name; } set { // Save current name. var name = _Entity.Name; // Set new name. _Entity.Name = value; // Raise Property changed event for all items which // has the same name, as item's old name. if ((this as ISupportOwnerCollection).OwnerCollection != null) DataObjectValidationHelper.RaisePropertyChangedForDuplicate ((this as ISupportOwnerCollection).OwnerCollection, name); NotifyPropertyChanged(PROP_NAME_Name); } } /// <summary> /// Arbitrary text about the location. /// </summary> [DomainProperty("DomainPropertyNameComment")] public string Comment { get { return _Entity.Comment; } set { _Entity.Comment = value; NotifyPropertyChanged(PROP_NAME_Comment); } } /// <summary> /// Curb approach for the location. /// </summary> [DomainProperty("DomainPropertyNameCurbApproach")] [AffectsRoutingProperty] public CurbApproach CurbApproach { get { return (CurbApproach)_Entity.CurbApproach; } set { _Entity.CurbApproach = (int)value; NotifyPropertyChanged(PROP_NAME_CurbApproach); } } /// <summary> /// Time window when the location is opened. /// </summary> [DomainProperty("DomainPropertyNameTimeWindow")] [AffectsRoutingProperty] public TimeWindow TimeWindow { get { return _timeWindow; } set { _timeWindow.PropertyChanged -= _TimeWindowPropertyChanged; if (value != null) { _timeWindow = value; _UpdateTimeWindowEntityData(); _timeWindow.PropertyChanged += new PropertyChangedEventHandler( _TimeWindowPropertyChanged); } else { _ClearTimeWindow(); _UpdateTimeWindowEntityData(); } NotifyPropertyChanged(PROP_NAME_TimeWindow); } } /// <summary> /// Time window 2 when the location is opened. /// </summary> [TimeWindow2Validator(Tag = PRIMARY_VALIDATOR_TAG)] [DomainProperty("DomainPropertyNameTimeWindow2")] [AffectsRoutingProperty] public TimeWindow TimeWindow2 { get { return _timeWindow2; } set { _timeWindow2.PropertyChanged -= _TimeWindow2PropertyChanged; if (value != null) { _timeWindow2 = value; _UpdateTimeWindow2EntityData(); _timeWindow2.PropertyChanged += new PropertyChangedEventHandler( _TimeWindow2PropertyChanged); } else { _ClearTimeWindow2(); _UpdateTimeWindow2EntityData(); } NotifyPropertyChanged(PROP_NAME_TimeWindow2); } } #endregion public members #region IGeocodable members /// <summary> /// Address of the Location. /// </summary> [ObjectFarFromRoadValidator(MessageTemplateResourceName = "Error_LocationNotFoundOnNetworkViolationMessage", MessageTemplateResourceType = typeof(ArcLogistics.Properties.Messages), Tag = PRIMARY_VALIDATOR_TAG)] [DomainProperty] public Address Address { get { return _address; } set { _address.PropertyChanged -= Address_PropertyChanged; if (value != null) { _address = value; _UpdateAddressEntityData(); _SubscribeToAddressEvent(); } else { _ClearAddress(); _UpdateAddressEntityData(); } NotifyPropertyChanged(PROP_NAME_Address); } } /// <summary> /// Geolocation of the Location /// </summary> [DomainProperty] public Point? GeoLocation { get { return _geoLocation; } set { _geoLocation = value; if (value == null) { _Entity.X = null; _Entity.Y = null; } else { _Entity.X = _geoLocation.Value.X; _Entity.Y = _geoLocation.Value.Y; } NotifyPropertyChanged(PROP_NAME_GeoLocation); } } /// <summary> /// Returns a value based on whether or not the address has been geocoded. /// </summary> [GeocodableValidator(MessageTemplateResourceName = "Error_LocationNotGeocoded", MessageTemplateResourceType = typeof(ArcLogistics.Properties.Messages), Tag = PRIMARY_VALIDATOR_TAG)] public bool IsGeocoded { get { return _geoLocation.HasValue; } } /// <summary> /// Property which turn on/off address validation. /// </summary> public bool IsAddressValidationEnabled { get; set; } #endregion IGeocodable members #region IDataErrorInfo members /// <summary> /// Gets the error message for the property with the given name. /// </summary> /// <param name="columnName"></param> /// <returns></returns> public override string this[string columnName] { get { if (Address.IsAddressPropertyName(columnName)) return _ValidateAddress(); else return base[columnName]; } } #endregion IDataErrorInfo members #region public methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Returns the name of the location. /// </summary> /// <returns></returns> public override string ToString() { return this.Name; } #endregion public methods #region ICloneable members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns></returns> public override object Clone() { Location obj = new Location(); this.CopyTo(obj); return obj; } #endregion ICloneable members #region ICopyable members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Copies all the object's data to the target data object. /// </summary> /// <param name="obj">Target data object.</param> public override void CopyTo(DataObject obj) { Location location = obj as Location; location.Name = this.Name; location.Comment = this.Comment; location.CurbApproach = this.CurbApproach; if (null != this.TimeWindow) location.TimeWindow = (TimeWindow)this.TimeWindow.Clone(); if (null != this.TimeWindow2) location.TimeWindow2 = (TimeWindow)this.TimeWindow2.Clone(); if (null != this.Address) location.Address = (Address)this.Address.Clone(); if (GeoLocation.HasValue) location.GeoLocation = new Point(this.GeoLocation.Value.X, this.GeoLocation.Value.Y); } #endregion ICopyable members #region IMarkableAsDeleted interface members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// bool IMarkableAsDeleted.IsMarkedAsDeleted { get { return _Entity.Deleted; } set { _Entity.Deleted = value; } } #endregion IMarkableAsDeleted interface members #region ISupportOwnerCollection members /// <summary> /// Collection in which this DataObject is placed. /// </summary> IEnumerable ISupportOwnerCollection.OwnerCollection { get; set; } #endregion ISupportOwnerCollection members #region private properties /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Gets entity data. /// </summary> private DataModel.Locations _Entity { get { return (DataModel.Locations)base.RawEntity; } } #endregion private properties #region private methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Handler for TimeWindow PropertyChanged event. /// </summary> /// <param name="sender">Source of an event.</param> /// <param name="e">Event data.</param> private void _TimeWindowPropertyChanged(object sender, PropertyChangedEventArgs e) { _UpdateTimeWindowEntityData(); NotifySubPropertyChanged(PROP_NAME_TimeWindow, e.PropertyName); } /// <summary> /// Handler for TimeWindow2 PropertyChanged event. /// </summary> /// <param name="sender">Source of an event.</param> /// <param name="e">Event data.</param> private void _TimeWindow2PropertyChanged(object sender, PropertyChangedEventArgs e) { _UpdateTimeWindow2EntityData(); NotifySubPropertyChanged(PROP_NAME_TimeWindow2, e.PropertyName); } /// <summary> /// Initializes TimeWindow usind entity data. /// </summary> /// <param name="entity">Entity data.</param> private void _InitTimeWindow(DataModel.Locations entity) { if (entity.OpenFrom != null && entity.OpenTo != null) _SetTimeWindow(entity); else _ClearTimeWindow(); _timeWindow.PropertyChanged += new PropertyChangedEventHandler(_TimeWindowPropertyChanged); } /// <summary> /// Initializes TimeWindow2 usind entity data. /// </summary> /// <param name="entity">Entity data.</param> private void _InitTimeWindow2(DataModel.Locations entity) { if (entity.OpenFrom2 != null && entity.OpenTo2 != null) _SetTimeWindow2(entity); else _ClearTimeWindow2(); _timeWindow2.PropertyChanged += new PropertyChangedEventHandler(_TimeWindow2PropertyChanged); } /// <summary> /// Sets time window using data from database. /// </summary> /// <param name="entity">Entity object Locations.</param> private void _SetTimeWindow(DataModel.Locations entity) { _timeWindow = TimeWindow.CreateFromEffectiveTimes(new TimeSpan((long)entity.OpenFrom), new TimeSpan((long)entity.OpenTo)); } /// <summary> /// Sets time window 2 using data from database. /// </summary> /// <param name="entity">Entity object Locations.</param> private void _SetTimeWindow2(DataModel.Locations entity) { _timeWindow2 = TimeWindow.CreateFromEffectiveTimes(new TimeSpan((long)entity.OpenFrom2), new TimeSpan((long)entity.OpenTo2)); } /// <summary> /// Clears time window. /// </summary> private void _ClearTimeWindow() { _timeWindow.From = new TimeSpan(); _timeWindow.To = new TimeSpan(); _timeWindow.Day = 0; _timeWindow.IsWideOpen = true; } /// <summary> /// Clears time window 2. /// </summary> private void _ClearTimeWindow2() { _timeWindow2.From = new TimeSpan(); _timeWindow2.To = new TimeSpan(); _timeWindow2.Day = 0; _timeWindow2.IsWideOpen = true; } /// <summary> /// Updates data of time window in database. /// </summary> private void _UpdateTimeWindowEntityData() { if (!_timeWindow.IsWideOpen) { _Entity.OpenFrom = _timeWindow.EffectiveFrom.Ticks; _Entity.OpenTo = _timeWindow.EffectiveTo.Ticks; } else { _Entity.OpenFrom = null; _Entity.OpenTo = null; } } /// <summary> /// Updates data of time window 2 in database. /// </summary> private void _UpdateTimeWindow2EntityData() { if (!_timeWindow2.IsWideOpen) { _Entity.OpenFrom2 = _timeWindow2.EffectiveFrom.Ticks; _Entity.OpenTo2 = _timeWindow2.EffectiveTo.Ticks; } else { _Entity.OpenFrom2 = null; _Entity.OpenTo2 = null; } } /// <summary> /// Handler for Address PropertyChanged event. /// </summary> /// <param name="sender">Source of an event.</param> /// <param name="e">Event data.</param> private void Address_PropertyChanged(object sender, PropertyChangedEventArgs e) { _UpdateAddressEntityData(); NotifySubPropertyChanged(PROP_NAME_Address, e.PropertyName); } /// <summary> /// Initializes Address property using entity data. /// </summary> /// <param name="entity">Entity data.</param> private void _InitAddress(DataModel.Locations entity) { Address.FullAddress = entity.FullAddress; Address.Unit = entity.Unit; Address.AddressLine = entity.AddressLine; Address.Locality1 = entity.Locality1; Address.Locality2 = entity.Locality2; Address.Locality3 = entity.Locality3; Address.CountyPrefecture = entity.CountyPrefecture; Address.PostalCode1 = entity.PostalCode1; Address.PostalCode2 = entity.PostalCode2; Address.StateProvince = entity.StateProvince; Address.Country = entity.Country; Address.MatchMethod = entity.Locator; // ToDo rename MatchMethod _SubscribeToAddressEvent(); } /// <summary> /// Clears address property. /// </summary> private void _ClearAddress() { Address.FullAddress = string.Empty; Address.Unit = string.Empty; Address.AddressLine = string.Empty; Address.Locality1 = string.Empty; Address.Locality2 = string.Empty; Address.Locality3 = string.Empty; Address.CountyPrefecture = string.Empty; Address.PostalCode1 = string.Empty; Address.PostalCode2 = string.Empty; Address.StateProvince = string.Empty; Address.Country = string.Empty; Address.MatchMethod = string.Empty; } /// <summary> /// Updates Address entity data. /// </summary> private void _UpdateAddressEntityData() { _Entity.FullAddress = Address.FullAddress; _Entity.Unit = Address.Unit; _Entity.AddressLine = Address.AddressLine; _Entity.Locality1 = Address.Locality1; _Entity.Locality2 = Address.Locality2; _Entity.Locality3 = Address.Locality3; _Entity.CountyPrefecture = Address.CountyPrefecture; _Entity.PostalCode1 = Address.PostalCode1; _Entity.PostalCode2 = Address.PostalCode2; _Entity.StateProvince = Address.StateProvince; _Entity.Country = Address.Country; _Entity.Locator = Address.MatchMethod; // ToDo rename MatchMethod } /// <summary> /// Initializes geo location using entity data. /// </summary> /// <param name="entity">Entity data.</param> private void _InitGeoLocation(DataModel.Locations entity) { if (entity.X != null && entity.Y != null) _geoLocation = new Point(entity.X.Value, entity.Y.Value); } /// <summary> /// Sets event handler for the PropertyChanged event of Address. /// </summary> private void _SubscribeToAddressEvent() { _address.PropertyChanged += new PropertyChangedEventHandler(Address_PropertyChanged); } /// <summary> /// Validates address. /// </summary> /// <returns></returns> private string _ValidateAddress() { // If we turned off validation - do nothing. if (!IsAddressValidationEnabled) return string.Empty; GeocodableValidator validator = new GeocodableValidator(Properties.Messages.Error_LocationNotGeocoded); ValidationResults results = validator.Validate(IsGeocoded); // If validation result is valid - check match method. If it is "Edited X/Y far from road" - address is not valid. if (results.IsValid) { ObjectFarFromRoadValidator objectFarFromRoadValidator = new ObjectFarFromRoadValidator(Properties.Messages.Error_LocationNotFoundOnNetworkViolationMessage); results = objectFarFromRoadValidator.Validate(Address); } string message = string.Empty; if (!results.IsValid) { foreach (ValidationResult result in results) { message = result.Message; break; } } return message; } #endregion private methods #region private constants /// <summary> /// Name of Name Property. /// </summary> private const string PROP_NAME_Name = "Name"; /// <summary> /// Name of Comment Property. /// </summary> private const string PROP_NAME_Comment = "Comment"; /// <summary> /// Name of CurbApproach Property. /// </summary> public const string PROP_NAME_CurbApproach = "CurbApproach"; /// <summary> /// Name of TimeWindow Property. /// </summary> private const string PROP_NAME_TimeWindow = "TimeWindow"; /// <summary> /// Name of TimeWindow2 Property. /// </summary> private const string PROP_NAME_TimeWindow2 = "TimeWindow2"; /// <summary> /// Name of Address Property. /// </summary> private const string PROP_NAME_Address = "Address"; /// <summary> /// Name of GeoLocation Property. /// </summary> private const string PROP_NAME_GeoLocation = "GeoLocation"; #endregion private constants #region private members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// First time window. /// </summary> private TimeWindow _timeWindow = new TimeWindow(); /// <summary> /// Second time window. /// </summary> private TimeWindow _timeWindow2 = new TimeWindow(); /// <summary> /// Address. /// </summary> private Address _address = new Address(); /// <summary> /// Geo location point. /// </summary> private Point? _geoLocation; #endregion private members } }
// // NSMutableData.cs: // Author: // Miguel de Icaza // Copyright 2010, Novell, Inc. // Copyright 2013-2014 Xamarin Inc (http://www.xamarin.com) using System; using ObjCRuntime; using System.IO; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; namespace Foundation { public partial class NSMutableData : IEnumerable, IEnumerable<byte> { public override byte this [nint idx] { set { if (idx < 0 || (ulong) idx > Length) throw new ArgumentException ("idx"); Marshal.WriteByte (new IntPtr (((long) Bytes) + idx), value); } } public void AppendBytes (byte [] bytes) { if (bytes == null) throw new ArgumentNullException ("bytes"); unsafe { fixed (byte *p = &bytes[0]){ AppendBytes ((IntPtr) p, (nuint) bytes.Length); } } } public void AppendBytes (byte [] bytes, nint start, nint len) { if (bytes == null) throw new ArgumentNullException ("bytes"); if (start < 0 || start > bytes.Length) throw new ArgumentException ("start"); if (start+len > bytes.Length) throw new ArgumentException ("len"); unsafe { fixed (byte *p = &bytes[start]){ AppendBytes ((IntPtr) p, (nuint) len); } } } IEnumerator IEnumerable.GetEnumerator () { IntPtr source = Bytes; nuint top = Length; for (nuint i = 0; i < top; i++){ if (source == Bytes && top == Length) yield return Marshal.ReadByte (source, (int)i); else throw new InvalidOperationException ("The NSMutableData has changed"); } } IEnumerator<byte> IEnumerable<byte>.GetEnumerator () { IntPtr source = Bytes; nuint top = Length; for (nuint i = 0; i < top; i++){ if (source == Bytes && top == Length) yield return Marshal.ReadByte (source, (int)i); else throw new InvalidOperationException ("The NSMutableData has changed"); } } } }
namespace CodeBoss.MultiTenant { /// <summary> /// Determines which tenant is currently active /// </summary> public interface ITenantIdentificationService { ITenant CurrentTenant(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AssemblySharp { public class MEM { public MEM Byte => new MEM(_register, MemoryStructureType.Byte); public MEM Word => new MEM(_register, MemoryStructureType.Word); public MEM DWord => new MEM(_register, MemoryStructureType.DWord); public MEM QWord => new MEM(_register, MemoryStructureType.QWord); public MEM TByte => new MEM(_register, MemoryStructureType.TByte); protected REG _register; protected MemoryStructureType _type; public MEM(REG reg, MemoryStructureType type = MemoryStructureType.DWord) { if (!IsValidRegistry(reg)) throw new ArgumentException(); _register = reg; _type = type; } private static bool IsValidRegistry(REG reg) => reg.IsValidExpressionForMemory(); public override string ToString() { return $"{_type.ToString().ToLower()} ptr [{_register.ExpressionToString()}]"; } } }
using UnityEngine; namespace MiniHexMap { public static class HexMetrics { public const float outerRadius = 10f; public const float innerRadius = outerRadius * 0.866025404f; public const float elevationStep = 5f; public const float solidFactor = 0.85f; public const float edgeFactor = 1f - solidFactor; public static Vector3[] corners = { new Vector3(0f, 0f, outerRadius), new Vector3(innerRadius, 0f, 0.5f * outerRadius), new Vector3(innerRadius, 0f, -0.5f * outerRadius), new Vector3(0f, 0f, -outerRadius), new Vector3(-innerRadius, 0f, -0.5f * outerRadius), new Vector3(-innerRadius, 0f, 0.5f * outerRadius), new Vector3(0f, 0f, outerRadius) }; public static Vector3[] edges = { new Vector3(innerRadius * -.5f, 0f, innerRadius), // NE new Vector3(innerRadius * .5f, 0f, innerRadius), // E new Vector3(innerRadius, 0f, 0f), // SE new Vector3(innerRadius * .5f, 0f, -innerRadius), // SW new Vector3(innerRadius * -.5f, 0f, -innerRadius), // W new Vector3(-innerRadius, 0f, 0f), // NW }; public static Vector3 GetBridge(HexDirection direction) { return (corners[(int)direction] + corners[(int)direction + 1]) * 0.5f * edgeFactor; } } }
namespace Inforigami.CLI { using System; using System.Collections.Generic; public interface ICommandTypeProvider { IEnumerable<Type> GetCommandTypes(); } }
using System; using System.Xml.Serialization; using AnotherCM.Library.Common; namespace AnotherCM.Library.Import.Common { public class ReferencedObject : NamedValueElement { [XmlElement] public string Description { get; set; } // TODO: doesn't really belong this deep [XmlElement] public string DefenseName { get; set; } [XmlElement] public string ID { get; set; } // TODO: doesn't really belong this deep [XmlElement("URL")] public string Url { get; set; } } public class ReferencedObjectWrapper { [XmlElement] public ReferencedObject ReferencedObject { get; set; } public string Description { get { return this.ReferencedObject.Description; } } public string Name { get { return this.ReferencedObject.Name; } } public ReferencedObjectWrapper () { this.ReferencedObject = new ReferencedObject(); } public override string ToString () { return this.ReferencedObject.ToString(); } } // to be used when the element has xsi:type="ObjectReference" public class ObjectReference : ReferencedObjectWrapper { } public class DefenseReference : ReferencedObjectWrapper { public Defense Defense { get { Defense def; Enum.TryParse(this.ReferencedObject.DefenseName, true, out def); return def; } } } }
using YourBrand.Payments.Domain.Common; namespace YourBrand.Payments.Domain.Events; public class PaymentCancelled : DomainEvent { public PaymentCancelled(string paymentId) { PaymentId = paymentId; } public string PaymentId { get; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Tests.Common { using System; using System.Collections.Generic; using Microsoft.DocAsCode.Common; public class TestListenerScope : IDisposable { private readonly TestLoggerListener _listener; private readonly LoggerPhaseScope _scope; public TestListenerScope(string phaseName) { _listener = TestLoggerListener.CreateLoggerListenerWithPhaseStartFilter(phaseName); Logger.RegisterListener(_listener); _scope = new LoggerPhaseScope(phaseName); } public void Dispose() { _scope.Dispose(); Logger.UnregisterListener(_listener); _listener.Dispose(); } public List<ILogItem> Items => _listener.Items; } }
using System; using System.Collections.Generic; using XEngine; using XEngineActor; namespace XEngineCommand { public class BulletFXCmd : BaseCommand { public int fxID; public float scale; public XPoint point; public int bulletLife; public Action<Actor, XPoint, ActorParent> collisionCallback; public bool useY; public List<int> offset; } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Web; using Qiwi.BillPayments.Exception; using Qiwi.BillPayments.Model; using Qiwi.BillPayments.Model.In; using Qiwi.BillPayments.Model.Out; using Qiwi.BillPayments.Web; namespace Qiwi.BillPayments.Client { /// <summary> /// QIWI Universal Payment Protocol API client. /// https://developer.qiwi.com/en/bill-payments/ /// </summary> [ComVisible(true)] public class BillPaymentsClient { /// <summary> /// The API base URL. /// </summary> public const string BillsUrl = "https://api.qiwi.com/partner/bill/v1/bills/"; /// <summary> /// The API dateTime format. /// </summary> public const string DateTimeFormat = "yyyy-MM-ddTHH\\:mm\\:ss.fffzzz"; /// <summary> /// The API client fingerprint. /// </summary> private readonly IFingerprint _fingerprint; /// <summary> /// The HTTP headers dictionary. /// </summary> private readonly Dictionary<string, string> _headers; /// <summary> /// The request mapping intercessor. /// </summary> private readonly RequestMappingIntercessor _requestMappingIntercessor; /// <summary> /// The constructor. /// </summary> /// <param name="secretKey">The merchant secret key.</param> /// <param name="requestMappingIntercessor">The API request mapper.</param> /// <param name="fingerprint">The client Fingerprint.</param> public BillPaymentsClient( string secretKey, RequestMappingIntercessor requestMappingIntercessor, IFingerprint fingerprint ) { _headers = new Dictionary<string, string> { {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"Authorization", "Bearer " + secretKey} }; _requestMappingIntercessor = requestMappingIntercessor; _fingerprint = fingerprint; } /// <summary> /// Append success URL parameter to payment URL in invoice. /// </summary> /// <param name="response">The invoice.</param> /// <param name="successUrl">The success URL.</param> /// <returns>New invoice witch updated payment URL.</returns> [ComVisible(true)] public static BillResponse AppendSuccessUrl(BillResponse response, Uri successUrl) { return AppendSuccessUrl<BillResponse>(response, successUrl); } /// <summary> /// Append success URL parameter to payment URL in invoice. /// </summary> /// <param name="response">The invoice.</param> /// <param name="successUrl">The success URL.</param> /// <typeparam name="T">The result invoice type.</typeparam> /// <returns>New invoice witch updated payment URL.</returns> [ComVisible(true)] public static T AppendSuccessUrl<T>(BillResponse response, Uri successUrl) where T : BillResponse { var uriBuilder = new UriBuilder(response.PayUrl); var parameters = HttpUtility.ParseQueryString(uriBuilder.Query); parameters["successUrl"] = successUrl.ToString(); uriBuilder.Query = parameters.ToString(); return response.WithPayUrl<T>(uriBuilder.Uri); } /// <summary> /// Get API client fingerprint. /// </summary> /// <returns>The fingerprint.</returns> [ComVisible(true)] public IFingerprint GetFingerprint() { return _fingerprint; } /// <summary> /// Invoice Issue on Pay Form. /// https://developer.qiwi.com/en/bill-payments/#http /// </summary> /// <param name="paymentInfo">The invoice data.</param> /// <param name="customFields">The additional info.</param> /// <returns>The pay form URL.</returns> /// <exception cref="UrlEncodingException"></exception> [ComVisible(true)] public Uri CreatePaymentForm(PaymentInfo paymentInfo, CustomFields customFields = null) { var additional = customFields ?? new CustomFields(); additional.ApiClient = _fingerprint.GetClientName(); additional.ApiClientVersion = _fingerprint.GetClientVersion(); var uriBuilder = new UriBuilder("https://oplata.qiwi.com/create"); try { var parameters = HttpUtility.ParseQueryString(uriBuilder.Query); parameters["amount"] = paymentInfo.Amount.ValueString; foreach (var keyValuePair in additional.ToDictionary()) if (null != keyValuePair.Value) parameters["customFields[" + keyValuePair.Key + "]"] = keyValuePair.Value.ToString(); parameters["publicKey"] = paymentInfo.PublicKey; parameters["billId"] = paymentInfo.BillId; if (null != paymentInfo.SuccessUrl) parameters["successUrl"] = paymentInfo.SuccessUrl.ToString(); uriBuilder.Query = parameters.ToString(); return uriBuilder.Uri; } catch (System.Exception e) { throw new UrlEncodingException(e); } } /// <summary> /// Invoice issue by API. /// https://developer.qiwi.com/en/bill-payments/#create /// </summary> /// <param name="info">The invoice data.</param> /// <param name="customFields">The additional fields.</param> /// <returns>The invoice.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public BillResponse CreateBill(CreateBillInfo info, CustomFields customFields = null) { return CreateBillAsync<BillResponse>(info, customFields).Result; } /// <summary> /// Invoice issue by API. /// https://developer.qiwi.com/en/bill-payments/#create /// </summary> /// <param name="info">The invoice data.</param> /// <param name="customFields">The additional info.</param> /// <typeparam name="T">The result invoice type.</typeparam> /// <returns>The invoice.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public T CreateBill<T>(CreateBillInfo info, CustomFields customFields = null) where T : BillResponse { return CreateBillAsync<T>(info, customFields).Result; } /// <summary> /// Invoice issue by API asynchronously. /// https://developer.qiwi.com/en/bill-payments/#create /// </summary> /// <param name="info">The invoice data.</param> /// <param name="customFields">The additional fields.</param> /// <returns>The invoice.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public async Task<BillResponse> CreateBillAsync(CreateBillInfo info, CustomFields customFields = null) { return await CreateBillAsync<BillResponse>(info, customFields); } /// <summary> /// Invoice issue by API asynchronously. /// https://developer.qiwi.com/en/bill-payments/#create /// </summary> /// <param name="info">The invoice data.</param> /// <param name="customFields">The additional info.</param> /// <typeparam name="T">The result invoice type.</typeparam> /// <returns>The invoice.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> public async Task<T> CreateBillAsync<T>(CreateBillInfo info, CustomFields customFields = null) where T : BillResponse { var additional = customFields ?? new CustomFields(); additional.ApiClient = _fingerprint.GetClientName(); additional.ApiClientVersion = _fingerprint.GetClientVersion(); var response = await _requestMappingIntercessor.RequestAsync<T>( "PUT", BillsUrl + info.BillId, _headers, info.GetCreateBillRequest(additional) ); return null != info.SuccessUrl ? AppendSuccessUrl<T>(response, info.SuccessUrl) : response; } /// <summary> /// Checking the invoice status. /// https://developer.qiwi.com/en/bill-payments/#invoice-status /// </summary> /// <param name="billId">The invoice identifier.</param> /// <returns>The invoice.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public BillResponse GetBillInfo(string billId) { return GetBillInfoAsync<BillResponse>(billId).Result; } /// <summary> /// Checking the invoice status. /// https://developer.qiwi.com/en/bill-payments/#invoice-status /// </summary> /// <param name="billId">The invoice identifier.</param> /// <typeparam name="T">The result invoice type.</typeparam> /// <returns>The invoice.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public T GetBillInfo<T>(string billId) where T : BillResponse { return GetBillInfoAsync<T>(billId).Result; } /// <summary> /// Checking the invoice status asynchronously. /// https://developer.qiwi.com/en/bill-payments/#invoice-status /// </summary> /// <param name="billId">The invoice identifier.</param> /// <returns>The invoice.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public async Task<BillResponse> GetBillInfoAsync(string billId) { return await GetBillInfoAsync<BillResponse>(billId); } /// <summary> /// Checking the invoice status asynchronously. /// https://developer.qiwi.com/en/bill-payments/#invoice-status /// </summary> /// <param name="billId">The invoice identifier.</param> /// <typeparam name="T">The result invoice type.</typeparam> /// <returns>The invoice.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public async Task<T> GetBillInfoAsync<T>(string billId) where T : BillResponse { return await _requestMappingIntercessor.RequestAsync<T>( "GET", BillsUrl + billId, _headers ); } /// <summary> /// Cancelling the invoice. /// https://developer.qiwi.com/en/bill-payments/#cancel /// </summary> /// <param name="billId">The invoice identifier.</param> /// <returns>The invoice.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public BillResponse CancelBill(string billId) { return CancelBillAsync<BillResponse>(billId).Result; } /// <summary> /// Cancelling the invoice. /// https://developer.qiwi.com/en/bill-payments/#cancel /// </summary> /// <param name="billId">The invoice identifier.</param> /// <typeparam name="T">The result invoice type.</typeparam> /// <returns>The invoice.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public T CancelBill<T>(string billId) where T : BillResponse { return CancelBillAsync<T>(billId).Result; } /// <summary> /// Cancelling the invoice asynchronously. /// https://developer.qiwi.com/en/bill-payments/#cancel /// </summary> /// <param name="billId">The invoice identifier.</param> /// <returns>The invoice.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public async Task<BillResponse> CancelBillAsync(string billId) { return await CancelBillAsync<BillResponse>(billId); } /// <summary> /// Cancelling the invoice asynchronously. /// https://developer.qiwi.com/en/bill-payments/#cancel /// </summary> /// <param name="billId">The invoice identifier.</param> /// <typeparam name="T">The result invoice type.</typeparam> /// <returns>The invoice.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public async Task<T> CancelBillAsync<T>(string billId) where T : BillResponse { return await _requestMappingIntercessor.RequestAsync<T>( "POST", BillsUrl + billId + "/reject", _headers, "" ); } /// <summary> /// Refund issue by API. /// https://developer.qiwi.com/en/bill-payments/#refund /// Method is not available for individuals /// </summary> /// <param name="billId">The invoice identifier.</param> /// <param name="refundId">The refund identifier.</param> /// <param name="amount">The refund amount.</param> /// <returns>The refund.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public RefundResponse RefundBill(string billId, string refundId, MoneyAmount amount) { return RefundBillAsync<RefundResponse>(billId, refundId, amount).Result; } /// <summary> /// Refund issue by API. /// https://developer.qiwi.com/en/bill-payments/#refund /// Method is not available for individuals /// </summary> /// <param name="billId">The invoice identifier.</param> /// <param name="refundId">The refund identifier.</param> /// <param name="amount">The refund amount.</param> /// <typeparam name="T">The result refund type.</typeparam> /// <returns>The refund.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public T RefundBill<T>(string billId, string refundId, MoneyAmount amount) where T : RefundResponse { return RefundBillAsync<T>(billId, refundId, amount).Result; } /// <summary> /// Refund issue by API asynchronously. /// https://developer.qiwi.com/en/bill-payments/#refund /// Method is not available for individuals /// </summary> /// <param name="billId">The invoice identifier.</param> /// <param name="refundId">The refund identifier.</param> /// <param name="amount">The refund amount.</param> /// <returns>The refund.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public async Task<RefundResponse> RefundBillAsync(string billId, string refundId, MoneyAmount amount) { return await RefundBillAsync<RefundResponse>(billId, refundId, amount); } /// <summary> /// Refund issue by API asynchronously. /// https://developer.qiwi.com/en/bill-payments/#refund /// Method is not available for individuals /// </summary> /// <param name="billId">The invoice identifier.</param> /// <param name="refundId">The refund identifier.</param> /// <param name="amount">The refund amount.</param> /// <typeparam name="T">The result refund type.</typeparam> /// <returns>The refund.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public async Task<T> RefundBillAsync<T>(string billId, string refundId, MoneyAmount amount) where T : RefundResponse { return await _requestMappingIntercessor.RequestAsync<T>( "PUT", BillsUrl + billId + "/refunds/" + refundId, _headers, new RefundBillRequest { Amount = amount } ); } /// <summary> /// Checking the refund status. /// https://developer.qiwi.com/en/bill-payments/#refund-status /// Method is not available for individuals /// </summary> /// <param name="billId">The invoice identifier.</param> /// <param name="refundId">The refund identifier.</param> /// <returns>The refund.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public RefundResponse GetRefundInfo(string billId, string refundId) { return GetRefundInfoAsync<RefundResponse>(billId, refundId).Result; } /// <summary> /// Checking the refund status. /// https://developer.qiwi.com/en/bill-payments/#refund-status /// Method is not available for individuals /// </summary> /// <param name="billId">The invoice identifier.</param> /// <param name="refundId">The refund identifier.</param> /// <typeparam name="T">The result refund type.</typeparam> /// <returns>The refund.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public T GetRefundInfo<T>(string billId, string refundId) where T : RefundResponse { return GetRefundInfoAsync<T>(billId, refundId).Result; } /// <summary> /// Checking the refund status asynchronously. /// https://developer.qiwi.com/en/bill-payments/#refund-status /// Method is not available for individuals /// </summary> /// <param name="billId">The invoice identifier.</param> /// <param name="refundId">The refund identifier.</param> /// <returns>The refund.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public async Task<RefundResponse> GetRefundInfoAsync(string billId, string refundId) { return await GetRefundInfoAsync<RefundResponse>(billId, refundId); } /// <summary> /// Checking the refund status asynchronously. /// https://developer.qiwi.com/en/bill-payments/#refund-status /// Method is not available for individuals /// </summary> /// <param name="billId">The invoice identifier.</param> /// <param name="refundId">The refund identifier.</param> /// <typeparam name="T">The result refund type.</typeparam> /// <returns>The refund.</returns> /// <exception cref="SerializationException">On request body serialization fail.</exception> /// <exception cref="HttpClientException">On request fail.</exception> /// <exception cref="BadResponseException">On response parse fail.</exception> /// <exception cref="BillPaymentsServiceException">On API return error message.</exception> [ComVisible(true)] public async Task<T> GetRefundInfoAsync<T>(string billId, string refundId) where T : RefundResponse { return await _requestMappingIntercessor.RequestAsync<T>( "GET", BillsUrl + billId + "/refunds/" + refundId, _headers ); } } }
using Microsoft.VisualStudio.Shell; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Text; namespace EasyBuildManager.Model { [DataContract] class CustomConfiguration { public string Name { get; set; } [DataMember] public IList<string> Projects { get; set; } = new List<string>(); } [DataContract] class CustomConfigurationList { [DataMember] public IList<CustomConfiguration> Configurations { get; set; } = new List<CustomConfiguration>(); } class CustomConfigurationManager { public CustomConfigurationList UserConfigurations { get; set; } = new CustomConfigurationList(); private readonly Solution solution; public CustomConfigurationManager(Solution solution) { ThreadHelper.ThrowIfNotOnUIThread(); this.solution = solution; var conf = new CustomConfiguration(); foreach (Project project in this.solution.Projects.Where(p => p.ShouldBuild)) { conf.Projects.Add(project.FullName); } UserConfigurations.Configurations.Add(conf); SaveToFile(UserConfigurations, GetUserConfigFilename()); } public string GetUserConfigFilename() { var solutionDir = Path.GetDirectoryName(this.solution.FilePath); var solutionName = Path.GetFileNameWithoutExtension(this.solution.FilePath); return Path.Combine(solutionDir, solutionName + ".user.slnc"); } public void LoadFromFile(ref CustomConfigurationList configurationsList, string filename) { if (!File.Exists(filename)) return; DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(CustomConfigurationList)); using (var stream = File.OpenRead(filename)) { configurationsList = js.ReadObject(stream) as CustomConfigurationList; } } public void SaveToFile(CustomConfigurationList configurationsList, string filename) { using (var stream = File.Create(filename)) { using (var writer = JsonReaderWriterFactory.CreateJsonWriter( stream, Encoding.UTF8, true, true, " ")) { var serializer = new DataContractJsonSerializer(typeof(CustomConfigurationList)); serializer.WriteObject(writer, configurationsList); writer.Flush(); } } } } }
using System.Collections.Generic; using NUnit.Framework; using Unity.MARS.MARSHandles.Picking; using UnityEngine; using UnityEngine.TestTools.Constraints; using Is = NUnit.Framework.Is; namespace Unity.MARS.MARSHandles.Tests.Picking { internal sealed class LinePickingTargetTests { LinePickingTarget m_Target; public sealed class TestCase { public readonly Vector3[] points; public TestCase(Vector3[] points) { this.points = points; } public override string ToString() { return string.Format("{0} Point{1}", points.Length, points.Length > 1 ? "s" : ""); } } static IEnumerable<TestCase> testCases { get { yield return new TestCase(new [] { Vector3.zero }); yield return new TestCase(new [] { Vector3.zero, new Vector3(0, 0, 1) }); yield return new TestCase(new [] { Vector3.zero, new Vector3(0, 0, 1), new Vector3(0, 1, 1) }); } } [SetUp] public void SetUp() { m_Target = new GameObject("Target").AddComponent<LinePickingTarget>(); } [TearDown] public void TearDown() { Object.DestroyImmediate(m_Target.gameObject); } [Test] [TestCaseSource(nameof(testCases))] public void CheckPickingData_IsValid(TestCase testCase) { m_Target.points = testCase.points; var pickingData = m_Target.GetPickingData(); Assert.IsTrue(pickingData.valid); } [Test] [TestCaseSource(nameof(testCases))] public void CheckPickingData_ValidTRS(TestCase testCase) { m_Target.points = testCase.points; var pickingData = m_Target.GetPickingData(); Assume.That(pickingData.valid); Assert.IsTrue(pickingData.matrix.ValidTRS()); } [Test] [TestCaseSource(nameof(testCases))] public void CheckMesh_OnlyOneSubMesh(TestCase testCase) { m_Target.points = testCase.points; var pickingData = m_Target.GetPickingData(); Assume.That(pickingData.valid); Assert.AreEqual(pickingData.mesh.subMeshCount, 1); } [Test] [TestCaseSource(nameof(testCases))] public void CheckTopology_OnePointIsPointTopology_MoreIsLineStripTopology(TestCase testCase) { m_Target.points = testCase.points; var pickingData = m_Target.GetPickingData(); Assume.That(pickingData.valid); Assert.AreEqual( testCase.points.Length > 1 ? MeshTopology.LineStrip : MeshTopology.Points, pickingData.mesh.GetTopology(0)); } [Test] [TestCaseSource(nameof(testCases))] public void CheckIndices_IsEqualToNumberOfPoints(TestCase testCase) { m_Target.points = testCase.points; var pickingData = m_Target.GetPickingData(); Assume.That(pickingData.valid); var indices = pickingData.mesh.GetIndices(0); Assume.That(indices != null); Assert.AreEqual(indices.Length, testCase.points.Length); } [Test] [TestCaseSource(nameof(testCases))] public void CheckVertices_AreSameAsGivenValue(TestCase testCase) { m_Target.points = testCase.points; var pickingData = m_Target.GetPickingData(); Assume.That(pickingData.valid); var vertices = pickingData.mesh.vertices; Assert.AreEqual(vertices.Length, testCase.points.Length); for (int i = 0; i < vertices.Length; ++i) { Assert.AreEqual(testCase.points[i], vertices[i]); } } [Test] [TestCaseSource(nameof(testCases))] public void GetPickingMesh_DoesntAllocate(TestCase testCase) { m_Target.points = testCase.points; Assert.That(TestScope, Is.Not.AllocatingGCMemory()); void TestScope() { m_Target.GetPickingData(); } } } }
using System; using Cysharp.Threading.Tasks; namespace toio { public interface BLEServiceInterface { void RequestDevice(Action<BLEDeviceInterface> action); void DisconnectAll(); UniTask Enable(bool enable, Action action); } }
using UnityEditor; using UnityEngine; using UnityTemplateProjects; namespace EditorUISamples { public class EditorWindowSceneView : EditorWindow { [MenuItem(menuItemRoot + "Scene View - kinda")] static void ShowWindow() { var window = GetWindow<EditorWindowSceneView>(); } protected const string menuItemRoot = "My UI Samples/"; protected Camera camera; protected GameObject camGameObject; protected SimpleCameraController simpleCameraController; protected Rect camRect = new Rect(0, 0, 1000, 1000); private void OnEnable() { camRect = new Rect(0f, 0f, position.width, position.height); SceneView.duringSceneGui += SceneGUI; } void SceneGUI(SceneView sceneView) { // This will have scene events including mouse down on scenes objects Event cur = Event.current; } private void OnFocus() { var components = new System.Type[] { typeof(Camera), typeof(SimpleCameraController) }; camGameObject = EditorUtility.CreateGameObjectWithHideFlags( "camGameObject", HideFlags.HideInHierarchy, components ); camera = camGameObject.GetComponent<Camera>(); camera.transform.position = new Vector3(2.32f, 1.2f, 3.71f); camera.transform.rotation = Quaternion.Euler(20.14f, 195.09f, 0.001f); simpleCameraController = camGameObject.GetComponent<SimpleCameraController>(); if (simpleCameraController == null) { throw new System.ArgumentNullException("SimpleCameraController"); } } private void OnLostFocus() { if (this.camera != null) { Object.DestroyImmediate(this.camera.gameObject); this.camera = null; } } private void OnGUI() { if (camera == null) return; if (camRect.width != position.width || camRect.height != position.height) { camRect.width = position.width; camRect.height = position.height; } Handles.BeginGUI(); Handles.SetCamera(camRect, camera); Handles.DrawCamera(camRect, camera, DrawCameraMode.Normal, true); Handles.EndGUI(); } private void OnDestroy() { this.OnLostFocus(); } } }
using NUnit.Framework; namespace Outracks.CodeNinja.Tests.Tests { public class TryCatch : Test { [Test] public void TryCatch00() { AssertCode( @"using Uno; class b { public void derp() { try { int i = 5; } catch($(Exception,IndexOutOfRangeException,InvalidCastException,InvalidOperationException,!int,!float,!double,!bool) } }" ); } [Test] public void TryCatch01() { AssertCode( @"using Uno; class b { public void derp() { try { int i = 5; } catch(Exception e) { } } public void Foo() { int test = 20; $(test) } }" ); } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.NetworkInformation; using System.Text; using System.Text.RegularExpressions; using UnityEditor; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace XT { public class XText : Text, IPointerClickHandler { public bool IsRefreshData; public TextAsset texData; private bool isDirty; /// <summary> /// 表情text里面的数据 /// </summary> Dictionary<string, EmojiInfoText> EmojiInfos; /// <summary> /// 在文字中匹配到的表情数据,key 是文本被替换后的网格索引,比如:[E1]333,则第一个就是的key就是0 /// </summary> Dictionary<int, EmojiInfoData> EmojiInfoDatas; /// <summary> /// key是第几个网格 /// </summary> Dictionary<int, HyperLinkInfo> HyperLinksDataDic; Dictionary<int, HyperLinkInfo> m_tempHyperLinksDataDic; /// <summary> /// 网格值 /// </summary> private Dictionary<int, int> HyperIdxs; MatchResultData matchResult = new MatchResultData(); const string regexPatten = "\\[(u%|d%)?(E[0-9]+|Link)?(#[a-fA-F0-9]{6}#)?([\u4e00-\u9fa5_a-zA-Z0-9]+)?\\]"; StringBuilder sBuilder = new StringBuilder(); UIVertex[] m_TempVerts = new UIVertex[4]; /// <summary> /// 下划线的宽度 /// </summary> public int lineWidth = 1; /// <summary> /// 匹配字符的总长度 /// </summary> int tempMatchValueLength = 0; private string m_outText = ""; /// <summary> /// 文本 /// </summary> public override string text { get => m_Text; set { if (EmojiInfos == null || IsRefreshData) InitEmojiData(); m_tempHyperLinksDataDic = new Dictionary<int, HyperLinkInfo>(); ParseText(value); base.text = value; //Debug.Log("---设置文字内容-----"); isDirty = true; } } public override float preferredWidth { get { if (m_outText != m_Text) m_outText = m_Text; var settings = GetGenerationSettings(Vector2.zero); return cachedTextGeneratorForLayout.GetPreferredWidth(m_outText, settings) / pixelsPerUnit; } } public override float preferredHeight { get { if (m_outText != m_Text) m_outText = m_Text; var settings = GetGenerationSettings(new Vector2(rectTransform.rect.size.x, 0.0f)); return cachedTextGeneratorForLayout.GetPreferredHeight(m_outText, settings) / pixelsPerUnit; } } protected void InitEmojiData() { if (texData != null) { EmojiInfos = new Dictionary<string, EmojiInfoText>(); string[] lines = texData.text.Split('\n'); for (int i = 1; i < lines.Length - 1; i++) { string[] data = lines[i].Split('\t'); EmojiInfoText emojiInfo = new EmojiInfoText() { name = data[0], totalFrame = int.Parse(data[1]), idx = int.Parse(data[2]) }; EmojiInfos[emojiInfo.name] = emojiInfo; } } } public void OnPointerClick(PointerEventData eventData) { if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out Vector2 localPos)) { if (HyperLinksDataDic != null) { foreach (var links in HyperLinksDataDic) { for (int i = 0; i < links.Value.clickArea.Count; i++) { if (links.Value.clickArea[i].Contains(localPos)) { if (links.Value.ClickFunc != null) links.Value.ClickFunc(links.Value.customInfo); } } } } } } protected override void OnPopulateMesh(VertexHelper toFill) { //Debug.Log("刷新网格"); if (font == null) return; if (EmojiInfos == null || IsRefreshData) InitEmojiData(); ParseText(m_Text); // We don't care if we the font Texture changes while we are doing our Update. // The end result of cachedTextGenerator will be valid for this instance. // Otherwise we can get issues like Case 619238. m_DisableFontTextureRebuiltCallback = true; Vector2 extents = rectTransform.rect.size; var settings = GetGenerationSettings(extents); //cachedTextGenerator.PopulateWithErrors(m_Text, settings, gameObject); cachedTextGenerator.PopulateWithErrors(m_outText, settings, gameObject); //Debug.Log("----" + m_outText); // Apply the offset to the vertices IList<UIVertex> verts = cachedTextGenerator.verts; float unitsPerPixel = 1 / pixelsPerUnit; int vertCount = verts.Count; // We have no verts to process just return (case 1037923) if (vertCount <= 0) { toFill.Clear(); return; } Vector2 roundingOffset = new Vector2(verts[0].position.x, verts[0].position.y) * unitsPerPixel; roundingOffset = PixelAdjustPoint(roundingOffset) - roundingOffset; toFill.Clear(); if (roundingOffset != Vector2.zero) { for (int i = 0; i < vertCount; ++i) { int tempVertsIndex = i & 3; m_TempVerts[tempVertsIndex] = verts[i]; m_TempVerts[tempVertsIndex].position *= unitsPerPixel; m_TempVerts[tempVertsIndex].position.x += roundingOffset.x; m_TempVerts[tempVertsIndex].position.y += roundingOffset.y; if (tempVertsIndex == 3) toFill.AddUIVertexQuad(m_TempVerts); } } else { int quadIdx = 0; for (int i = 0; i < vertCount; ++i) { quadIdx = i / 4; int tempVertsIndex = i & 3; m_TempVerts[tempVertsIndex] = verts[i]; if (EmojiInfoDatas != null && EmojiInfoDatas.TryGetValue(quadIdx, out EmojiInfoData data)) { //Debug.Log("表情的顶点开始索引:" + i); m_TempVerts[tempVertsIndex].uv0.x += data.emojiInfoText.idx * 10; m_TempVerts[tempVertsIndex].uv0.y += data.emojiInfoText.totalFrame * 10; } else if (HyperLinksDataDic != null && HyperLinksDataDic.TryGetValue(quadIdx, out HyperLinkInfo hyperData)) { if (hyperData.clickArea.Count <= 0) { CalculateClickRect(i, hyperData, verts); SetVertsColor(i, toFill, hyperData, verts); i += hyperData.wordLength * 4 - 1; //Debug.Log("连接的顶点结束索引:" + i); } } m_TempVerts[tempVertsIndex].position *= unitsPerPixel; if (tempVertsIndex == 3) toFill.AddUIVertexQuad(m_TempVerts); } DrawLine(toFill, m_TempVerts); } if (isDirty) { RefreshData(); isDirty = false; } m_DisableFontTextureRebuiltCallback = false; } protected void ParseText(string inputText) { m_outText = inputText; // if (!Application.isPlaying) // return; EmojiInfoDatas = new Dictionary<int, EmojiInfoData>(); HyperLinksDataDic = new Dictionary<int, HyperLinkInfo>(); HyperIdxs = new Dictionary<int, int>(); tempMatchValueLength = 0; MatchCollection matches = Regex.Matches(m_outText, regexPatten); for (int i = 0; i < matches.Count; i++) { sBuilder.Clear(); if (matches[i].Success && matches[i].Groups.Count > 0) { var match = matches[i]; matchResult.Reset(); matchResult.ParseData(match); if (matchResult.matchType == MatchType.Emoji) { if (EmojiInfos != null) AnalyseEmojiData(match); else { Debug.LogWarning("----没有生成表情数据-----"); continue; } } else if (matchResult.matchType == MatchType.Link || matchResult.matchType == MatchType.Line) { AnalyseLinkData(match); } else { } } } } protected void AnalyseEmojiData(Match match) { sBuilder.Append($"<quad size={fontSize} width=1 />"); m_outText = m_outText.Replace(match.Groups[0].Value, sBuilder.ToString()); if (!EmojiInfos.ContainsKey(match.Groups[2].Value)) { Debug.LogError("表情与txt的不匹配,检查表情拼写,或者重新生成表情数据"); } else { EmojiInfoDatas[match.Index - tempMatchValueLength] = new EmojiInfoData() { emojiInfoText = EmojiInfos[match.Groups[2].Value] }; //Debug.Log("表情的网格-----" + (match.Index - tempMatchValueLength)); tempMatchValueLength += match.Groups[0].Length - 1; } } protected void AnalyseLinkData(Match match) { HyperLinkInfo hyperLinkInfo = new HyperLinkInfo(); hyperLinkInfo.color = color; if (!string.IsNullOrEmpty(matchResult.hyperColor)) if (ColorUtility.TryParseHtmlString(matchResult.hyperColor, out hyperLinkInfo.color)) tempMatchValueLength += match.Groups[3].Length; if (matchResult.matchType == MatchType.Link) { tempMatchValueLength += match.Groups[2].Length + 1; hyperLinkInfo.ClickFunc = s => Debug.Log("点击到了" + s); hyperLinkInfo.lineType = LineType.None; hyperLinkInfo.startIdx = match.Groups[4].Index - tempMatchValueLength; // Debug.Log("Link---是第几个网格--" + hyperLinkInfo.startIdx); tempMatchValueLength++; } else if (matchResult.matchType == MatchType.Line) { tempMatchValueLength += match.Groups[1].Length + 1; hyperLinkInfo.ClickFunc = s => Debug.Log("点击到了" + s); hyperLinkInfo.lineType = match.Groups[1].Value == "u%" ? LineType.Underline : LineType.Delete; hyperLinkInfo.lineArea = new List<Rect>(); hyperLinkInfo.startIdx = match.Groups[4].Index - tempMatchValueLength; // Debug.Log("下划线开始网格:" + hyperLinkInfo.startIdx + " 结束网格:" + // (hyperLinkInfo.startIdx + match.Groups[4].Length)); tempMatchValueLength++; } //m_Text = m_Text.Replace(match.Groups[0].Value, match.Groups[4].Value); m_outText = m_outText.Replace(match.Groups[0].Value, match.Groups[4].Value); hyperLinkInfo.id = HyperLinksDataDic.Count + 1; hyperLinkInfo.wordLength = match.Groups[4].Length; hyperLinkInfo.clickArea = new List<Rect>(); hyperLinkInfo.word = match.Groups[4].Value; hyperLinkInfo.customInfo = hyperLinkInfo.word; HyperLinksDataDic[hyperLinkInfo.startIdx] = hyperLinkInfo; HyperIdxs[HyperLinksDataDic.Count] = hyperLinkInfo.startIdx; } protected void DrawLine(VertexHelper toFill, UIVertex[] m_TempVerts) { if (HyperLinksDataDic != null) { var verts = cachedTextGenerator.verts; foreach (var lineInfo in HyperLinksDataDic) { if (lineInfo.Value.lineType == LineType.None) continue; for (int i = 0; i < lineInfo.Value.lineArea.Count; i++) { Rect rect = lineInfo.Value.lineArea[i]; for (int j = 0; j < 4; j++) { m_TempVerts[j] = verts[lineInfo.Value.startIdx * 4 + j]; m_TempVerts[j].uv0 = -10f * Vector4.one; m_TempVerts[j].color = lineInfo.Value.color; m_TempVerts[0].position = j == 0 ? new Vector3(rect.xMin, rect.yMax) : m_TempVerts[0].position; m_TempVerts[1].position = j == 1 ? new Vector3(rect.xMax, rect.yMax) : m_TempVerts[1].position; m_TempVerts[2].position = j == 2 ? new Vector3(rect.xMax, rect.yMin) : m_TempVerts[2].position; m_TempVerts[3].position = j == 3 ? new Vector3(rect.xMin, rect.yMin) : m_TempVerts[3].position; if (j == 3) toFill.AddUIVertexQuad(m_TempVerts); } } } } } protected void CalculateClickRect(int vertsIdx, HyperLinkInfo hyperLinkInfo, IList<UIVertex> verts) { Vector2 minPos = verts[vertsIdx + 3].position; Vector2 maxPos = verts[vertsIdx + 1].position; while (vertsIdx / 4 < hyperLinkInfo.startIdx + hyperLinkInfo.wordLength) { Vector2 vertsPos = verts[vertsIdx + 1].position; if (vertsPos.x > maxPos.x) maxPos.x = vertsPos.x; if (vertsPos.y > maxPos.y) maxPos.y = vertsPos.y; if (vertsPos.y < minPos.y) { // Debug.Log("--------换行了-----------------"); CalculateClickRect(vertsIdx, hyperLinkInfo, verts); break; } vertsIdx += 4; } hyperLinkInfo.clickArea.Add(new Rect {min = minPos, max = maxPos}); if (hyperLinkInfo.lineType == LineType.Underline) { minPos = new Vector2(minPos.x, minPos.y - lineWidth); maxPos = new Vector2(maxPos.x, minPos.y + lineWidth); } else if (hyperLinkInfo.lineType == LineType.Delete) { minPos = new Vector2(minPos.x, minPos.y + (maxPos.y - minPos.y) * 0.5f - lineWidth * 0.5f); maxPos = new Vector2(maxPos.x, minPos.y + lineWidth); } if (hyperLinkInfo.lineType != LineType.None) hyperLinkInfo.lineArea.Add(new Rect {min = minPos, max = maxPos}); } protected void SetVertsColor(int vertIdx, VertexHelper toFill, HyperLinkInfo hyperLinkInfo, IList<UIVertex> verts) { int startVertIdx = vertIdx; float unitsPerPixel = 1 / pixelsPerUnit; while (vertIdx < startVertIdx + hyperLinkInfo.wordLength * 4) { int tempVertsIndex = vertIdx & 3; m_TempVerts[tempVertsIndex] = verts[vertIdx]; m_TempVerts[tempVertsIndex].color = hyperLinkInfo.color; m_TempVerts[tempVertsIndex].position *= unitsPerPixel; if (tempVertsIndex == 3) toFill.AddUIVertexQuad(m_TempVerts); vertIdx++; } } /*---------可点击区域----------*/ public void SetHyperData(int id, Action<string> func, string customInfo, string lineType = "0", string hyperColor = "#FFFFFF") { HyperLinkInfo hyperLinkInfo = GetLinkInfoByIdx(id); if (hyperLinkInfo != null) { hyperLinkInfo.ClickFunc = func; hyperLinkInfo.customInfo = customInfo; hyperLinkInfo.lineType = (LineType) Enum.Parse(typeof(LineType), lineType); ColorUtility.TryParseHtmlString(hyperColor, out hyperLinkInfo.color); m_tempHyperLinksDataDic[HyperIdxs[id]] = hyperLinkInfo; Debug.Log("-----自定义成功!!!------"); } } private void RefreshData() { foreach (var hyperInfo in m_tempHyperLinksDataDic) { HyperLinksDataDic[hyperInfo.Key].color = hyperInfo.Value.color; HyperLinksDataDic[hyperInfo.Key].customInfo = hyperInfo.Value.customInfo; HyperLinksDataDic[hyperInfo.Key].ClickFunc = hyperInfo.Value.ClickFunc; HyperLinksDataDic[hyperInfo.Key].lineType = hyperInfo.Value.lineType; } } private int GetLinkMeshKeyByIdx(int idx) { if (HyperIdxs == null || !HyperIdxs.ContainsKey(idx)) return -1; else return HyperIdxs[idx]; } private HyperLinkInfo GetLinkInfoByIdx(int idx) { int meshKey = GetLinkMeshKeyByIdx(idx); if (meshKey != -1) { if (HyperLinksDataDic == null || !HyperLinksDataDic.ContainsKey(meshKey)) return null; else return HyperLinksDataDic[HyperIdxs[idx]]; } else return null; } } [Serializable] public struct EmojiInfoText { public string name; //该图片的名字 public int totalFrame; //该图片的总共帧数 public int idx; //该图片的索引,有可能不是连续的 } public struct EmojiInfoData { public EmojiInfoText emojiInfoText; } public class HyperLinkInfo { public LineType lineType; public int id; public string customInfo; public int startIdx; public int wordLength; public string word; public Action<string> ClickFunc; public Color color; public List<Rect> clickArea; //防止换行的情况 public List<Rect> lineArea; } public class MatchResultData { public string prefix; public MatchType matchType; public string hyperColor; public void Reset() { prefix = string.Empty; matchType = MatchType.None; hyperColor = null; } public void ParseData(Match match) { if (match.Groups.Count == 5) { prefix = match.Groups[2].Value; if (!string.IsNullOrEmpty(prefix)) { if (prefix == "Link") { if (!string.IsNullOrEmpty(match.Groups[3].Value)) { matchType = MatchType.Link; } } else { matchType = MatchType.Emoji; } } else matchType = MatchType.None; if (!string.IsNullOrEmpty(match.Groups[1].Value) && string.IsNullOrEmpty(match.Groups[2].Value) && !string.IsNullOrEmpty(match.Groups[4].Value)) matchType = MatchType.Line; if (!string.IsNullOrEmpty(match.Groups[3].Value)) { hyperColor = match.Groups[3].Value.Substring(0, 7); } } } } public enum MatchType { None, Emoji, Link, Line } public enum LineType { None, Delete, Underline } }
using GameSharp.Core.Native.Offsets; namespace GameSharp.Core.Memory { public class PEB { public bool IsValid => _pebPointer.IsValid; private readonly MemoryPointer _pebPointer; private readonly IPebOffsets _pebOffsets; public PEB(IProcess process) { _pebPointer = process.GetPebAddress(); if (process.Is64Bit) { _pebOffsets = new PebOffsets64(); } else { _pebOffsets = new PebOffsets32(); } } public bool BeingDebugged { get => _pebPointer.Read<bool>(_pebOffsets.BeingDebugged); set => _pebPointer.Write(value, _pebOffsets.BeingDebugged); } public long NtGlobalFlag { get => _pebPointer.Read<long>(_pebOffsets.NtGlobalFlag); set => _pebPointer.Write(value, _pebOffsets.NtGlobalFlag); } } }
using LBH.AdultSocialCare.Api.V1.Domain.Common; using System.Collections.Generic; using System.Threading.Tasks; using LBH.AdultSocialCare.Data.Entities.Common; using LBH.AdultSocialCare.Data.Extensions; using LBH.AdultSocialCare.Data.RequestFeatures.Parameters; namespace LBH.AdultSocialCare.Api.V1.Gateways.Common.Interfaces { public interface ISupplierGateway { public Task<SupplierDomain> GetAsync(int supplierId); public Task<SupplierDomain> CreateAsync(Supplier supplier); public Task<SupplierDomain> UpdateAsync(SupplierDomain supplier); public Task<PagedList<SupplierDomain>> ListAsync(RequestParameters parameters, string supplierName); } }
// ------------------------------------------------------------ // 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.Hub.Clients { using Microsoft.Azure.IIoT.Exceptions; using Microsoft.Azure.IIoT.Hub.Models; using System; using System.Text; using System.Threading.Tasks; /// <summary> /// Method client using twin services /// </summary> public class IoTHubTwinMethodClient : IJsonMethodClient { /// <inheritdoc/> public int MaxMethodPayloadCharacterCount => 120 * 1024; /// <summary> /// Create client /// </summary> /// <param name="twin"></param> public IoTHubTwinMethodClient(IIoTHubTwinServices twin) { _twin = twin ?? throw new ArgumentNullException(nameof(twin)); } /// <inheritdoc/> public async Task<string> CallMethodAsync(string deviceId, string moduleId, string method, string payload, TimeSpan? timeout = null) { var result = await _twin.CallMethodAsync(deviceId, moduleId, new MethodParameterModel { Name = method, ResponseTimeout = timeout, JsonPayload = payload }); if (result.Status != 200) { throw new MethodCallStatusException( Encoding.UTF8.GetBytes(result.JsonPayload), result.Status); } return result.JsonPayload; } private readonly IIoTHubTwinServices _twin; } }
using System; using System.Collections.Generic; using System.Linq; public class StudentsByFirstAndLastName { public static void Main() { string input; var students = new List<string>(); while ((input = Console.ReadLine()) != "END") { var tokens = input .Split(); students.Add($"{tokens[0]} {tokens[1]}"); } var filtredNames = students .Select(s => { var tokens = s.Split(); var firstName = tokens[0]; var secondName = tokens[1]; return new { firstName, secondName }; }) .Where(x => x.firstName.CompareTo(x.secondName) == -1) .ToList(); foreach (var student in filtredNames) { Console.WriteLine($"{student.firstName} {student.secondName}"); } } }
using Mono.Cecil; using Mono.Cecil.Cil; using OTAPI.Patcher.Engine.Extensions; using OTAPI.Patcher.Engine.Modification; using System; using System.Linq; using Mono.Collections.Generic; using OTAPI.Patcher.Engine.Extensions.ILProcessor; using Terraria; using Terraria.Localization; namespace OTAPI.Patcher.Engine.Modifications.Hooks.Net { [Ordered(7)] public class SendDataNetworkText : ModificationBase { public override System.Collections.Generic.IEnumerable<string> AssemblyTargets => new[] { "Terraria, Version=1.3.0.7, Culture=neutral, PublicKeyToken=null", "TerrariaServer, Version=1.3.0.7, Culture=neutral, PublicKeyToken=null" }; public override string Description => "Add NetworkText overloading of SendData..."; public override void Run() { var netMessage = SourceDefinition.Type<NetMessage>(); var sendData = netMessage.Method("SendData"); // Create new method var overloading = new MethodDefinition(sendData.Name, sendData.Attributes, sendData.ReturnType); foreach (var p in sendData.Parameters) { var prm = new ParameterDefinition(p.Name, p.Attributes, p.ParameterType); prm.Constant = p.Constant; if (prm.ParameterType == SourceDefinition.MainModule.TypeSystem.String) { prm.ParameterType = Type<NetworkText>(); prm.Constant = NetworkText.Empty; } overloading.Parameters.Add(prm); } // Create method body var ilprocessor = overloading.Body.GetILProcessor(); ParameterDefinition text = null; for (int i = 0; i < overloading.Parameters.Count; i++) { ilprocessor.Append(Instruction.Create(OpCodes.Ldarg, overloading.Parameters[i])); if (overloading.Parameters[i].ParameterType == Type<NetworkText>()) { text = overloading.Parameters[i]; ilprocessor.Append(Instruction.Create(OpCodes.Callvirt, Type<NetworkText>().Method("ToString"))); } } ilprocessor.Append(Instruction.Create(OpCodes.Call, sendData)); ilprocessor.Append(Instruction.Create(OpCodes.Ret)); foreach (var i in new [] { Instruction.Create(OpCodes.Ldarg, text), Instruction.Create(OpCodes.Brtrue_S, overloading.Body.Instructions[0]), Instruction.Create(OpCodes.Ldsfld, Type<NetworkText>().Field("Empty")), Instruction.Create(OpCodes.Starg, text), }.Reverse()) { ilprocessor.InsertBefore(overloading.Body.Instructions[0], i); } netMessage.Methods.Add(overloading); } } }
// This file was automatically generated and may be regenerated at any // time. To ensure any changes are retained, modify the tool with any segment/component/group/field name // or type changes. namespace Machete.HL7Schema.V26 { using System; using HL7; /// <summary> /// OM1 (Segment) - General Segment /// </summary> public interface OM1 : HL7V26Segment { /// <summary> /// OM1-1: Sequence Number - Test/Observation Master File /// </summary> Value<decimal> SequenceNumberTestObservationMasterFile { get; } /// <summary> /// OM1-2: Producer's Service/Test/Observation ID /// </summary> Value<CWE> ProducerSServiceTestObservationId { get; } /// <summary> /// OM1-3: Permitted Data Types /// </summary> ValueList<string> PermittedDataTypes { get; } /// <summary> /// OM1-4: Specimen Required /// </summary> Value<string> SpecimenRequired { get; } /// <summary> /// OM1-5: Producer ID /// </summary> Value<CWE> ProducerId { get; } /// <summary> /// OM1-6: Observation Description /// </summary> Value<TX> ObservationDescription { get; } /// <summary> /// OM1-7: Other Service/Test/Observation IDs for the Observation /// </summary> Value<CWE> OtherServiceTestObservationIdsForObservation { get; } /// <summary> /// OM1-8: Other Names /// </summary> ValueList<string> OtherNames { get; } /// <summary> /// OM1-9: Preferred Report Name for the Observation /// </summary> Value<string> PreferredReportNameForObservation { get; } /// <summary> /// OM1-10: Preferred Short Name or Mnemonic for Observation /// </summary> Value<string> PreferredShortNameOrMnemonicForObservation { get; } /// <summary> /// OM1-11: Preferred Long Name for the Observation /// </summary> Value<string> PreferredLongNameForObservation { get; } /// <summary> /// OM1-12: Orderability /// </summary> Value<string> Orderability { get; } /// <summary> /// OM1-13: Identity of Instrument Used to Perform this Study /// </summary> ValueList<CWE> IdentityOfInstrumentUsedToPerformThisStudy { get; } /// <summary> /// OM1-14: Coded Representation of Method /// </summary> ValueList<CWE> CodedRepresentationOfMethod { get; } /// <summary> /// OM1-15: Portable Device Indicator /// </summary> Value<string> PortableDeviceIndicator { get; } /// <summary> /// OM1-16: Observation Producing Department/Section /// </summary> ValueList<CWE> ObservationProducingDepartmentSection { get; } /// <summary> /// OM1-17: Telephone Number of Section /// </summary> Value<XTN> TelephoneNumberOfSection { get; } /// <summary> /// OM1-18: Nature of Service/Test/Observation /// </summary> Value<string> NatureOfServiceTestObservation { get; } /// <summary> /// OM1-19: Report Subheader /// </summary> Value<CWE> ReportSubheader { get; } /// <summary> /// OM1-20: Report Display Order /// </summary> Value<string> ReportDisplayOrder { get; } /// <summary> /// OM1-21: Date/Time Stamp for any change in Definition for the Observation /// </summary> Value<DateTimeOffset> DateTimeStampForAnyChangeInDefinitionForObservation { get; } /// <summary> /// OM1-22: Effective Date/Time of Change /// </summary> Value<DateTimeOffset> EffectiveDateTimeOfChange { get; } /// <summary> /// OM1-23: Typical Turn-Around Time /// </summary> Value<decimal> TypicalTurnAroundTime { get; } /// <summary> /// OM1-24: Processing Time /// </summary> Value<decimal> ProcessingTime { get; } /// <summary> /// OM1-25: Processing Priority /// </summary> ValueList<string> ProcessingPriority { get; } /// <summary> /// OM1-26: Reporting Priority /// </summary> Value<string> ReportingPriority { get; } /// <summary> /// OM1-27: Outside Site(s) Where Observation may be Performed /// </summary> ValueList<CWE> OutsideSiteSWhereObservationMayBePerformed { get; } /// <summary> /// OM1-28: Address of Outside Site(s) /// </summary> ValueList<XAD> AddressOfOutsideSiteS { get; } /// <summary> /// OM1-29: Phone Number of Outside Site /// </summary> Value<XTN> PhoneNumberOfOutsideSite { get; } /// <summary> /// OM1-30: Confidentiality Code /// </summary> Value<CWE> ConfidentialityCode { get; } /// <summary> /// OM1-31: Observations Required to Interpret the Observation /// </summary> Value<CWE> ObservationsRequiredToInterpretObservation { get; } /// <summary> /// OM1-32: Interpretation of Observations /// </summary> Value<TX> InterpretationOfObservations { get; } /// <summary> /// OM1-33: Contraindications to Observations /// </summary> Value<CWE> ContraindicationToObservations { get; } /// <summary> /// OM1-34: Reflex Tests/Observations /// </summary> ValueList<CWE> ReflexTestsObservations { get; } /// <summary> /// OM1-35: Rules that Trigger Reflex Testing /// </summary> Value<TX> RuleThatTriggerReflexTesting { get; } /// <summary> /// OM1-36: Fixed Canned Message /// </summary> Value<CWE> FixedCannedMessage { get; } /// <summary> /// OM1-37: Patient Preparation /// </summary> Value<TX> PatientPreparation { get; } /// <summary> /// OM1-38: Procedure Medication /// </summary> Value<CWE> ProcedureMedication { get; } /// <summary> /// OM1-39: Factors that may Affect the Observation /// </summary> Value<TX> FactorsThatMayAffectObservation { get; } /// <summary> /// OM1-40: Service/Test/Observation Performance Schedule /// </summary> ValueList<string> ServiceTestObservationPerformanceSchedule { get; } /// <summary> /// OM1-41: Description of Test Methods /// </summary> Value<TX> DescriptionOfTestMethods { get; } /// <summary> /// OM1-42: Kind of Quantity Observed /// </summary> Value<CWE> KindOfQuantityObserved { get; } /// <summary> /// OM1-43: Point Versus Interval /// </summary> Value<CWE> PointVersusInterval { get; } /// <summary> /// OM1-44: Challenge Information /// </summary> Value<TX> ChallengeInformation { get; } /// <summary> /// OM1-45: Relationship Modifier /// </summary> Value<CWE> RelationshipModifier { get; } /// <summary> /// OM1-46: Target Anatomic Site Of Test /// </summary> Value<CWE> TargetAnatomicSiteOfTest { get; } /// <summary> /// OM1-47: Modality Of Imaging Measurement /// </summary> Value<CWE> ModalityOfImagingMeasurement { get; } } }
using System.Collections.Generic; using Kudu.Contracts.Infrastructure; using Newtonsoft.Json; namespace Kudu.Contracts.Diagnostics { public class ProcessEnvironmentInfo : Dictionary<string, string>, INamedObject { private readonly string _name; public ProcessEnvironmentInfo() { } public ProcessEnvironmentInfo(string name, Dictionary<string, string> values) : base(values) { _name = name; } [JsonProperty(PropertyName = "name")] string INamedObject.Name { get { return _name; } } } }
// ReSharper disable once CheckNamespace namespace System.Threading.Tasks { static class TaskEx { public static Task CompletedTask { get; } = Task.FromResult(0); } }
// Copyright (c) Jeroen van Pienbroek. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. namespace AdvancedInputFieldPlugin { public interface INativeKeyboardCallback { void OnTextEditUpdate(string text, int selectionStartPosition, int selectionEndPosition); void OnKeyboardShow(); void OnKeyboardHide(); void OnKeyboardDone(); void OnKeyboardNext(); void OnKeyboardCancel(); void OnKeyboardHeightChanged(int height); void OnHardwareKeyboardChanged(bool connected); } }
using System; namespace Minimax.Chess { public enum Piece : byte { NULL = 0, WHITE_PAWN = 1, WHITE_ROOK = 2, WHITE_KNIGHT = 3, WHITE_BISHOP = 4, WHITE_QUEEN = 5, WHITE_KING = 6, BLACK_PAWN = 7, BLACK_ROOK = 8, BLACK_KNIGHT = 9, BLACK_BISHOP = 10, BLACK_QUEEN = 11, BLACK_KING = 12 } public enum Color : byte { WHITE = 0, BLACK = 6 } public static class PieceExtensions { public static double Value(this Piece piece) { return piece switch { Piece.NULL => 0, Piece.WHITE_PAWN => 1, Piece.BLACK_PAWN => -1, Piece.WHITE_ROOK => 5, Piece.BLACK_ROOK => -5, Piece.WHITE_KNIGHT => 3, Piece.BLACK_KNIGHT => -3, Piece.WHITE_BISHOP => 3, Piece.BLACK_BISHOP => -3, Piece.WHITE_QUEEN => 9, Piece.BLACK_QUEEN => -9, Piece.WHITE_KING => 0, Piece.BLACK_KING => 0, _ => throw new System.Exception() }; } public static Color Color(this Piece piece) { switch (piece) { case Piece.WHITE_PAWN: case Piece.WHITE_ROOK: case Piece.WHITE_KNIGHT: case Piece.WHITE_BISHOP: case Piece.WHITE_QUEEN: case Piece.WHITE_KING: return Chess.Color.WHITE; case Piece.BLACK_PAWN: case Piece.BLACK_ROOK: case Piece.BLACK_KNIGHT: case Piece.BLACK_BISHOP: case Piece.BLACK_QUEEN: case Piece.BLACK_KING: return Chess.Color.BLACK; case Piece.NULL: throw new Exception("Cannot get color of empty square."); } throw new Exception(); } } }
#region Using using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using NLib; using NLib.Design; using NLib.Reflection; using SQLite; using SQLiteNetExtensions.Attributes; using SQLiteNetExtensions.Extensions; // required for JsonIgnore attribute. using Newtonsoft.Json; using Newtonsoft.Json.Bson; using System.Reflection; #endregion namespace DMT.Models { #region PlazaGroup /// <summary> /// The PlazaGroup Data Model class. /// </summary> [TypeConverter(typeof(PropertySorterSupportExpandableTypeConverter))] [Serializable] [JsonObject(MemberSerialization.OptOut)] //[Table("Plaza")] public class PlazaGroup : NTable<PlazaGroup> { #region Intenral Variables private string _PlazaGroupId = string.Empty; private string _PlazaGroupNameEN = string.Empty; private string _PlazaGroupNameTH = string.Empty; private string _Direction = string.Empty; private string _TSBId = string.Empty; private string _TSBNameEN = string.Empty; private string _TSBNameTH = string.Empty; #endregion #region Constructor /// <summary> /// Constructor. /// </summary> public PlazaGroup() : base() { } #endregion #region Public Proprties #region Common /// <summary> /// Gets or sets PlazaId. /// </summary> [Category("Plaza Group")] [Description("Gets or sets PlazaId.")] [PrimaryKey, MaxLength(10)] [PropertyMapName("PlazaGroupId")] public string PlazaGroupId { get { return _PlazaGroupId; } set { if (_PlazaGroupId != value) { _PlazaGroupId = value; this.Raise(() => this.PlazaGroupId); } } } /// <summary> /// Gets or sets PlazaGroupNameEN /// </summary> [Category("Plaza Group")] [Description("Gets or sets PlazaGroupNameEN")] [MaxLength(100)] [PropertyMapName("PlazaGroupNameEN")] public string PlazaGroupNameEN { get { return _PlazaGroupNameEN; } set { if (_PlazaGroupNameEN != value) { _PlazaGroupNameEN = value; this.Raise(() => this.PlazaGroupNameEN); } } } /// <summary> /// Gets or sets PlazaGroupNameTH /// </summary> [Category("Plaza Group")] [Description("Gets or sets PlazaGroupNameTH")] [MaxLength(100)] [PropertyMapName("PlazaGroupNameTH")] public string PlazaGroupNameTH { get { return _PlazaGroupNameTH; } set { if (_PlazaGroupNameTH != value) { _PlazaGroupNameTH = value; this.Raise(() => this.PlazaGroupNameTH); } } } /// <summary> /// Gets or sets Direction /// </summary> [Category("Plaza Group")] [Description("Gets or sets Direction")] [MaxLength(10)] [PropertyMapName("Direction")] public string Direction { get { return _Direction; } set { if (_Direction != value) { _Direction = value; this.Raise(() => this.Direction); } } } #endregion #region TSB /// <summary> /// Gets or sets TSBId. /// </summary> [Category("TSB")] [Description("Gets or sets TSBId.")] [ReadOnly(true)] [NotNull] [Indexed] [MaxLength(10)] [PropertyMapName("TSBId")] public string TSBId { get { return _TSBId; } set { if (_TSBId != value) { _TSBId = value; this.Raise(() => this.TSBId); } } } /// <summary> /// Gets or sets TSB Name EN. /// </summary> [Category("TSB")] [Description("Gets or sets TSB Name EN.")] [ReadOnly(true)] [Ignore] [PropertyMapName("TSBNameEN")] public virtual string TSBNameEN { get { return _TSBNameEN; } set { if (_TSBNameEN != value) { _TSBNameEN = value; this.Raise(() => this.TSBNameEN); } } } /// <summary> /// Gets or sets TSB Name TH. /// </summary> [Category("TSB")] [Description("Gets or sets TSB Name TH.")] [ReadOnly(true)] [Ignore] [PropertyMapName("TSBNameTH")] public virtual string TSBNameTH { get { return _TSBNameTH; } set { if (_TSBNameTH != value) { _TSBNameTH = value; this.Raise(() => this.TSBNameTH); } } } #endregion #endregion #region Internal Class /// <summary> /// The internal FKs class for query data. /// </summary> public class FKs : PlazaGroup, IFKs<PlazaGroup> { #region TSB /// <summary> /// Gets or sets TSB Name EN. /// </summary> [MaxLength(100)] [PropertyMapName("TSBNameEN")] public override string TSBNameEN { get { return base.TSBNameEN; } set { base.TSBNameEN = value; } } /// <summary> /// Gets or sets TSB Name TH. /// </summary> [MaxLength(100)] [PropertyMapName("TSBNameTH")] public override string TSBNameTH { get { return base.TSBNameTH; } set { base.TSBNameTH = value; } } #endregion } #endregion #region Static Methods #region Get PlazaGroups (all TSBs) /// <summary> /// Gets PlazaGroups. /// </summary> /// <param name="db">The database connection.</param> /// <returns>Returns List of PlazaGroup.</returns> public static NDbResult<List<PlazaGroup>> GetPlazaGroups(SQLiteConnection db) { var result = new NDbResult<List<PlazaGroup>>(); if (null == db) { result.DbConenctFailed(); return result; } lock (sync) { MethodBase med = MethodBase.GetCurrentMethod(); try { string cmd = string.Empty; cmd += "SELECT * "; cmd += " FROM PlazaGroupView "; var rets = NQuery.Query<FKs>(cmd).ToList(); var results = rets.ToModels(); result.Success(results); } catch (Exception ex) { med.Err(ex); result.Error(ex); } return result; } } /// <summary> /// Gets PlazaGroups. /// </summary> /// <returns>Returns List of PlazaGroup.</returns> public static NDbResult<List<PlazaGroup>> GetPlazaGroups() { lock (sync) { SQLiteConnection db = Default; return GetPlazaGroups(db); } } #endregion #region Get PlazaGroup By PlazaGroupId /// <summary> /// Gets PlazaGroup (By PlazaGroupId). /// </summary> /// <param name="db">The database connection.</param> /// <param name="plazaGroupId">The Plaza Group Id.</param> /// <returns>Returns PlazaGroup instance.</returns> public static NDbResult<PlazaGroup> GetPlazaGroup(SQLiteConnection db, string plazaGroupId) { var result = new NDbResult<PlazaGroup>(); if (null == db) { result.DbConenctFailed(); return result; } lock (sync) { MethodBase med = MethodBase.GetCurrentMethod(); try { string cmd = string.Empty; cmd += "SELECT * "; cmd += " FROM PlazaGroupView "; cmd += " WHERE PlazaGroupId = ? "; var ret = NQuery.Query<FKs>(cmd, plazaGroupId).FirstOrDefault(); var data = (null != ret) ? ret.ToModel() : null; result.Success(data); } catch (Exception ex) { med.Err(ex); result.Error(ex); } return result; } } /// <summary> /// Gets PlazaGroup (By PlazaGroupId). /// </summary> /// <param name="plazaGroupId">The Plaza Group Id</param> /// <returns>Returns PlazaGroup instance.</returns> public static NDbResult<PlazaGroup> GetPlazaGroup(string plazaGroupId) { lock (sync) { SQLiteConnection db = Default; return GetPlazaGroup(db, plazaGroupId); } } #endregion #region Get PlazaGroups By TSB/TSBId /// <summary> /// Gets PlazaGroups (By TSB). /// </summary> /// <param name="value">The TSB instance.</param> /// <returns>Returns List of PlazaGroup.</returns> public static NDbResult<List<PlazaGroup>> GetTSBPlazaGroups(TSB value) { var result = new NDbResult<List<PlazaGroup>>(); SQLiteConnection db = Default; if (null == db) { result.DbConenctFailed(); return result; } lock (sync) { return GetTSBPlazaGroups(value.TSBId); } } /// <summary> /// Gets PlazaGroups (By TSBId). /// </summary> /// <param name="tsbId">The TSB Id.</param> /// <returns>Returns List of PlazaGroup.</returns> public static NDbResult<List<PlazaGroup>> GetTSBPlazaGroups(string tsbId) { var result = new NDbResult<List<PlazaGroup>>(); lock (sync) { MethodBase med = MethodBase.GetCurrentMethod(); try { string cmd = string.Empty; cmd += "SELECT * "; cmd += " FROM PlazaGroupView "; cmd += " WHERE TSBId = ? "; var rets = NQuery.Query<FKs>(cmd, tsbId).ToList(); var results = rets.ToModels(); result.Success(results); } catch (Exception ex) { med.Err(ex); result.Error(ex); } return result; } } #endregion #region Save PlazaGroup /// <summary> /// Save PlazaGroup. /// </summary> /// <param name="value">The PlazaGroup instance.</param> /// <returns>Returns PlazaGroup instance.</returns> public static NDbResult<PlazaGroup> SavePlazaGroup(PlazaGroup value) { var result = new NDbResult<PlazaGroup>(); SQLiteConnection db = Default; if (null == db) { result.DbConenctFailed(); return result; } lock (sync) { MethodBase med = MethodBase.GetCurrentMethod(); try { result = Save(value); } catch (Exception ex) { med.Err(ex); result.Error(ex); } return result; } } #endregion #endregion } #endregion }
using Engine.Drawing_Objects; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using StillDesign.PhysX; namespace Requiem.Entities { /// <summary>The base abstract for all game-type objects</summary> /// <author>Gabrial Dubois, modified by Daniel Cuccia</author> public abstract class GameEntity : Object3D { public string Name { set; get; } /// <summary>Default CTOR </summary> /// <param name="device">reference to graphics device</param> /// <param name="world">reference to the world manger</param> public GameEntity() : base() { this.collidable = true; } public abstract void Initialize(ContentManager content); #region Unused public override sealed void CreateFromXML(ContentManager content, XMLMedium inputXml) { } public override sealed Object3D GetCopy(ContentManager content) { return null; } public override sealed XMLMedium GetXML() { return null; } public override sealed void RenderImplicit(Effect effect) { } #endregion } }
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() //100/100 { Dictionary<string, Dictionary<string, long>> dic = new Dictionary<string, Dictionary<string, long>>(); while (true) { string x = Console.ReadLine(); if (x == "stop the game") { break; } string[] current = x.Split('|'); string team = current[1]; string player = current[0]; int pointsMade = int.Parse(current[2]); if (dic.ContainsKey(team)) { if (dic[team].Values.Count < 3) { if (dic[team].ContainsKey(player)) { dic[team][player] += pointsMade; } else { dic[team].Add(player, pointsMade); } } } if (!dic.ContainsKey(team)) { dic[team] = new Dictionary<string, long>(); dic[team].Add(player, pointsMade); } } dic = dic.OrderByDescending(x => x.Value.Values.Sum()).ToDictionary(xa => xa.Key, xs => xs.Value); int counter = 1; foreach (KeyValuePair<string, Dictionary<string, long>> team in dic) { if (team.Value.Count == 3) { Console.WriteLine("{0}. {1}; Players:", counter, team.Key); foreach (KeyValuePair<string, long> pleyear in team.Value.OrderByDescending(x => x.Value)) { Console.WriteLine("###{0}: {1}", pleyear.Key, pleyear.Value); } counter++; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace OfficePS.Models { public class FeedBack { public FeedBack() { } public int FeedBackId { get; set; } public string Titulo { get; set; } public string Descricao { get; set; } public string Email { get; set; } public bool Ativo { get; set; } public DateTime Data { get; set; } public int ClientesId { get; set; } public virtual Clientes Cliente { get; set; } } }
using System; using System.Collections.Generic; namespace Dibix.Dapper.Tests { internal class StructuredType_Int : StructuredType_IntStringDecimal { public void Add(int intValue) => base.Add(intValue, String.Empty, default); public static StructuredType_Int From(IEnumerable<int> source, Action<StructuredType_Int, int> addItemFunc) { Guard.IsNotNull(source, nameof(source)); Guard.IsNotNull(addItemFunc, nameof(addItemFunc)); StructuredType_Int type = new StructuredType_Int(); foreach (int item in source) { addItemFunc(type, item); } return type; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Lib; namespace UnsupervisedLearning.KMeans { /// <summary> /// Implementação de <see cref="IMovieClassification"/> para o algoritmo <see cref="StandardKMeans"/>. /// </summary> public class KMeansMovieClassification : IMovieClassification { public Movie movie { get; private set; } public Cluster cluster { get; private set; } public IClassLabel label { get { return cluster; } } public KMeansMovieClassification(Movie movie, Cluster cluster) { if (movie == null) throw new ArgumentException("movie"); if (cluster == null) throw new ArgumentException("cluster"); this.movie = movie; this.cluster = cluster; } public string print() { return movie.id + "," + cluster.id; } } }
using System.Collections.Generic; using UnityEngine; using UnityEngine.Audio; namespace AdrianKovatana { public class AudioManager : MonoBehaviour { //Singleton requirements protected AudioManager() { } // guarantee this will be always a singleton only - can't use the constructor! public static AudioManager Instance { get; private set; } //Components private MusicSourceController _audioSourceMusic; #pragma warning disable [SerializeField] private ObjectPool _musicSourcePool; [SerializeField] private ObjectPool _audioSourcePool; //Data [SerializeField] private AudioMixer _audioMixer; #pragma warning restore public List<MixerGroupVolumeData> volumeData; public float musicFadeOutDuration = 1f; public float musicFadeInDuration = 1f; private void Awake() { //Singleton requirements if(Instance != null && Instance != this) { Destroy(gameObject); return; } else { Instance = this; } //Persist through scene changes DontDestroyOnLoad(gameObject); } private void Start() { foreach(MixerGroupVolumeData data in volumeData) { _audioMixer.SetFloat(data.ExposedParameter, data.volume); } } public void PlayMusic(MusicClipData data) { _audioSourceMusic = _musicSourcePool.GetObject().GetComponent<MusicSourceController>(); _audioSourceMusic.Init(data, true); if(musicFadeInDuration > 0f) { _audioSourceMusic.FadeIn(musicFadeInDuration); } else { _audioSourceMusic.Play(); } } public void StopMusic() { if(_audioSourceMusic) { _audioSourceMusic.FadeOut(musicFadeOutDuration); } } public void PlayClipFromData(AudioClipData data) { _audioSourcePool.GetObject() .GetComponent<AudioSourceController>() .Play(data, false); } public void UpdateVolume(string name, float value) { _audioMixer.SetFloat(name, value); } } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace watchtower.Code.ExtensionMethods { public static class JTokenExtensionMethods { public static string GetString(this JToken ext, string name, string def) { return ext.Value<string?>(name) ?? def; } public static string? NullableString(this JToken ext, string name) { return ext.Value<string?>(name); } public static DateTime CensusTimestamp(this JToken ext, string field) { return DateTimeOffset.FromUnixTimeSeconds(ext.Value<int?>(field) ?? 0).UtcDateTime; } } }
using System.Collections; namespace UnitTests.Iniect.io.TestDomain.Constructor { public interface ICtorA { IExtraProperty ExtraProperty { get; } } internal class CtorA : ICtorA { public CtorA(IExtraProperty extraProperty) { ExtraProperty = extraProperty; } public CtorA(IExtraProperty extraProperty, IEnumerable unrelated) { ExtraProperty = extraProperty; } public IExtraProperty ExtraProperty { get; } } }
using System.ComponentModel.DataAnnotations.Schema; using Abp.Domain.Entities.Auditing; using Emarketing.Authorization.Users; namespace Emarketing.BusinessObjects { public class UserWithdrawDetail : FullAuditedEntity<long> { public UserWithdrawDetail() { } [ForeignKey("UserId")] public User User { get; set; } public long UserId { get; set; } public WithdrawType WithdrawTypeId { get; set; } public string AccountTitle { get; set; } public string AccountIBAN { get; set; } public string JazzCashNumber { get; set; } public string EasyPaisaNumber { get; set; } public bool IsPrimary { get; set; } } }
namespace SingletonExample.AOP { [Singleton] public class AnotherOneClass { public static AnotherOneClass Instance { get; set; } private AnotherOneClass() {} } }
using UnityEngine; public abstract class GameState { protected GameStateMachine _gameStateMachine; protected GameState _nextState; protected GameState(GameStateMachine gameStateMachine) { _nextState = null; _gameStateMachine = gameStateMachine; } public virtual void UpdateState() { } public virtual void EnterState() { } public virtual void ExitState() { } public GameState GetNext() { return _nextState; } public virtual void AlienReachedBottom() { } public virtual void StopChase() { } public virtual void ItemClicked(ItemBehaviour item) { } public virtual void ItemDriftedOff(ItemBehaviour item) { } public virtual void BottomScreenPressed() { } public virtual void PositionInSpacePressed(Vector2 pos) { } public virtual void AstronautActivated() { } public virtual void TransmitterReady() { } public virtual void AnyKeyPressed() { } }
using Crocodal.Transpiler.Tests.Core; using Crocodal.Transpiler.Tests.Fixtures; using System; using Xunit; namespace Crocodal.Transpiler.Tests { public class TupleDeclarationTranslationTests : IClassFixture<CompilerFixture> { private readonly StatementTranslator _translator = new StatementTranslator(); private readonly CompilerFixture _fixture; public TupleDeclarationTranslationTests(CompilerFixture fixture) { _fixture = fixture; } [Fact] public void ShouldParse_TupleDeclaration_Explicit_WithInitializer() { // Arrange var unit = _fixture.Compile("Tuple<int, int> x = (5, 6);"); // Act var expression = _translator.Translate(unit); // Assert var binaryExpression = ExpressionAssert.AsBinaryAssign(expression); ExpressionAssert.Declaration(binaryExpression.Left, typeof(Tuple<int, int>), "x"); var rightExpression = ExpressionAssert.AsTuple(binaryExpression.Right); Assert.Equal(2, rightExpression.Rank); ExpressionAssert.Constant(rightExpression.Expressions[0], 5); ExpressionAssert.Constant(rightExpression.Expressions[1], 6); } [Fact] public void ShouldParse_TupleDeclaration_AsVar_WithInitializer() { // Arrange var unit = _fixture.Compile("var x = (5, 6);"); // Act var expression = _translator.Translate(unit); // Assert var binaryExpression = ExpressionAssert.AsBinaryAssign(expression); ExpressionAssert.Declaration(binaryExpression.Left, typeof(Tuple<int, int>), "x"); var rightExpression = ExpressionAssert.AsTuple(binaryExpression.Right); Assert.Equal(2, rightExpression.Rank); ExpressionAssert.Constant(rightExpression.Expressions[0], 5); ExpressionAssert.Constant(rightExpression.Expressions[1], 6); } [Fact] public void ShouldParse_TupleDeclaration_Upacked_WithExplicitTypesInside_WithInitializer() { // Arrange var unit = _fixture.Compile("(int x, int y) = (5, 6);"); // Act var expression = _translator.Translate(unit); // Assert var binaryExpression = ExpressionAssert.AsBinaryAssign(expression); var leftExpression = ExpressionAssert.AsTuple(binaryExpression.Left); Assert.Equal(2, leftExpression.Rank); ExpressionAssert.Declaration(leftExpression.Expressions[0], typeof(int), "x"); ExpressionAssert.Declaration(leftExpression.Expressions[1], typeof(int), "y"); var rightExpression = ExpressionAssert.AsTuple(binaryExpression.Right); Assert.Equal(2, rightExpression.Rank); ExpressionAssert.Constant(rightExpression.Expressions[0], 5); ExpressionAssert.Constant(rightExpression.Expressions[1], 6); } [Fact] public void ShouldParse_TupleDeclaration_Upacked_WithVarsInside_WithInitializer() { // Arrange var unit = _fixture.Compile("(var x, var y) = (5, 6);"); // Act var expression = _translator.Translate(unit); // Assert var binaryExpression = ExpressionAssert.AsBinaryAssign(expression); var leftExpression = ExpressionAssert.AsTuple(binaryExpression.Left); Assert.Equal(2, leftExpression.Rank); ExpressionAssert.Declaration(leftExpression.Expressions[0], typeof(int), "x"); ExpressionAssert.Declaration(leftExpression.Expressions[1], typeof(int), "y"); var rightExpression = ExpressionAssert.AsTuple(binaryExpression.Right); Assert.Equal(2, rightExpression.Rank); ExpressionAssert.Constant(rightExpression.Expressions[0], 5); ExpressionAssert.Constant(rightExpression.Expressions[1], 6); } [Fact] public void ShouldParse_TupleDeclaration_Upacked_WithExplicitTypeOutside_WithInitializer() { // Arrange var unit = _fixture.Compile("int (x, y) = (5, 6);"); // Act var expression = _translator.Translate(unit); // Assert var binaryExpression = ExpressionAssert.AsBinaryAssign(expression); var leftExpression = ExpressionAssert.AsTuple(binaryExpression.Left); Assert.Equal(2, leftExpression.Rank); ExpressionAssert.Declaration(leftExpression.Expressions[0], typeof(int), "x"); ExpressionAssert.Declaration(leftExpression.Expressions[1], typeof(int), "y"); var rightExpression = ExpressionAssert.AsTuple(binaryExpression.Right); Assert.Equal(2, rightExpression.Rank); ExpressionAssert.Constant(rightExpression.Expressions[0], 5); ExpressionAssert.Constant(rightExpression.Expressions[1], 6); } [Fact] public void ShouldParse_TupleDeclaration_Upacked_WithVarOutside_WithInitializer() { // Arrange var unit = _fixture.Compile("var (x, y) = (5, 6);"); // Act var expression = _translator.Translate(unit); // Assert var binaryExpression = ExpressionAssert.AsBinaryAssign(expression); var leftExpression = ExpressionAssert.AsTuple(binaryExpression.Left); Assert.Equal(2, leftExpression.Rank); ExpressionAssert.Declaration(leftExpression.Expressions[0], typeof(int), "x"); ExpressionAssert.Declaration(leftExpression.Expressions[1], typeof(int), "y"); var rightExpression = ExpressionAssert.AsTuple(binaryExpression.Right); Assert.Equal(2, rightExpression.Rank); ExpressionAssert.Constant(rightExpression.Expressions[0], 5); ExpressionAssert.Constant(rightExpression.Expressions[1], 6); } } }
using GrainInterfaces; using Orleans; using System.Threading.Tasks; namespace HelloGrains { /// <summary> /// Grain implementation class Grain1. /// </summary> internal class HelloGrain : Grain, IHello { public Task<string> SayHello(string msg) { return Task.FromResult(string.Format("You said {0}, I say: Hello!", msg)); } } }
using TeeSquare.Reflection; namespace TeeSquare.Tests.Reflection.FakeDomain { public class Circle { public int Radius { get; set; } [TypeDiscriminator] public string Kind => nameof(Circle); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RoomData : MonoBehaviour { [SerializeField] private int roomNumberInArray; [SerializeField] private RoomMovement roomControllerRoomMovement; [SerializeField] private RoomInformation thisRoom; [SerializeField] private GameObject clearedRoom; [SerializeField] private GameObject startRoom; [SerializeField] private AudioSource clearRoomSound; private GameObject spawnedRoom; private bool _isclearedRoomNotNull; void Start() { _isclearedRoomNotNull = clearedRoom != null; thisRoom = roomControllerRoomMovement.rooms[roomNumberInArray]; roomControllerRoomMovement.RoomChange += RoomCheck; } private void RoomCheck() { if (thisRoom.Name != roomControllerRoomMovement.CurrentRoom.Name) return; print(gameObject.name + " says the current room is " + thisRoom.Name); CreateRoomAssets(); } private void CreateRoomAssets() { if (startRoom == null) return; StartCoroutine(Co_CreateRoomAssets()); } private IEnumerator Co_CreateRoomAssets() { yield return new WaitForSeconds(0.25f); if (!thisRoom.isCleared) { spawnedRoom = Instantiate(startRoom, transform); } } private void DestroyStartRoom() { if (spawnedRoom == null) return; Destroy(spawnedRoom); } public void RoomClear() { clearRoomSound.Play(); DestroyStartRoom(); if (_isclearedRoomNotNull) { Instantiate(clearedRoom, transform); } thisRoom.isCleared = true; } }
using UserIdentity.Services.Models; namespace UserIdentity.WebUI.Infrastructure.Settings { public class AppSettings { public SmtpSettings SmtpSettings { get; set; } public string UploadsFolder { get; set; } public string Domain { get; set; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Threading.Tasks; using BuildXL.Cache.ContentStore.Interfaces.Results; using Xunit; namespace BuildXL.Cache.ContentStore.InterfacesTest.Results { public class ResultsExtensionsTests { [Fact] public void RethrowIfFailurePropagatesOriginalException() { var exception = new System.InvalidOperationException(); var result = new BoolResult(exception); Assert.Throws<InvalidOperationException>(() => result.RethrowIfFailure()); } [Fact] public async Task ThenAsyncIsCalledOnSuccessCase() { var success = Task.FromResult(Result.Success(1)); bool thenAsyncCalled = false; var result = await success.ThenAsync( async r => { thenAsyncCalled = true; await Task.Yield(); return Result.Success(2); }); Assert.True(thenAsyncCalled); Assert.Equal(2, result.Value); } [Fact] public async Task ThenAsyncIsNotCalledOnCanceled() { var canceledResult = Result.Success(1); canceledResult.MarkCancelled(); var canceled = Task.FromResult(canceledResult); bool thenAsyncCalled = false; var result = await canceled.ThenAsync( async r => { thenAsyncCalled = true; await Task.Yield(); return Result.Success(2); }); Assert.False(thenAsyncCalled); Assert.True(result.IsCancelled); } [Fact] public async Task ThenAsyncIsNotCalledOnError() { var originalResult = Task.FromResult(Result.FromErrorMessage<int>("Error")); bool thenAsyncCalled = false; var result = await originalResult.ThenAsync( async r => { thenAsyncCalled = true; await Task.Yield(); return Result.Success(2); }); Assert.False(thenAsyncCalled); Assert.False(result.Succeeded); Assert.Equal("Error", result.ErrorMessage); } } }
using System; using System.Threading.Tasks; namespace Lykke.Job.BlockchainOperationsExecutor.Core.Domain.OperationExecutions { public interface IActiveTransactionsRepository { Task<Guid> GetOrStartTransactionAsync(Guid operationId, Func<Guid> newTransactionIdFactory); Task EndTransactionAsync(Guid operationId, Guid transactionId); } }
@model UserModel @{ ViewBag.Title = "Register"; } <h1>Account <span>Creation</span></h1> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <div> <div class="editor-field"> @Html.EditorFor(m => m.User.Email) @Html.ValidationMessageFor(m => m.User.Email) </div> <div class="editor-field"> @Html.EditorFor(m => m.User.FirstName) @Html.ValidationMessageFor(m => m.User.FirstName) @Html.EditorFor(m => m.User.LastName) @Html.ValidationMessageFor(m => m.User.LastName) </div> <div class="editor-field"> @Html.EditorFor(m => m.User.LastName) @Html.ValidationMessageFor(m => m.User.LastName) </div> <div class="editor-field"> @Html.DropDownList("User.ClientID", (SelectList) ViewBag.ClientList, "None") @Html.ValidationMessageFor(m => m.User.ClientID) </div> <div class="editor-field"> @Html.EditorFor(m => m.Password) @Html.ValidationMessageFor(m => m.Password) </div> <div class="editor-field"> @Html.EditorFor(m => m.ConfirmPassword) @Html.ValidationMessageFor(m => m.ConfirmPassword) </div> <div class="editor-field"> @Html.ListBoxFor(m=>m.User.Roles, (SelectList) ViewBag.RoleList) @Html.ValidationMessageFor(m => m.User.Roles) </div> <p> <input type="submit" value="Register" /> </p> </div> } <div> @Html.ActionLink("Back to List", "Index") </div>
using Audio; using Buildings; using MapElements.Buildings; using UnityEngine; namespace Game { public class BottomUI : IMapUI { public void ShowPanelMessage(string text) { OnMapUI.Get().bottomButtonText.color = Color.white; OnMapUI.Get().bottomButtonText.text = text; } public void ShowPanelMessageError(string text) { OnMapUI.Get().bottomButtonText.color = Color.magenta; OnMapUI.Get().bottomButtonText.text = text; NAudio.PlayBuzzer(); } } }
using Newtonsoft.Json.Linq; using System.Collections.Generic; namespace Twitch.Base.Models.V5.Bits { /// <summary> /// Information about a tier for a Bits cheermote. /// </summary> public class BitCheermoteTierModel { /// <summary> /// The ID of the tier. /// </summary> public string id { get; set; } /// <summary> /// The color of the tier. /// </summary> public string color { get; set; } /// <summary> /// The images associated with the tier. /// </summary> public JObject images { get; set; } /// <summary> /// The minimum number of bits required to meet the tier. /// </summary> public int min_bits { get; set; } } /// <summary> /// Information about a Bits cheermote. /// </summary> public class BitCheermoteModel { /// <summary> /// The backgrounds of the cheermote. /// </summary> public List<string> background { get; set; } /// <summary> /// The prefix of the cheermote. /// </summary> public string prefix { get; set; } /// <summary> /// The scale amounts of the cheermote. /// </summary> public List<string> scales { get; set; } /// <summary> /// The states of the cheermote. /// </summary> public List<string> states { get; set; } /// <summary> /// The tiers of the cheermote. /// </summary> public List<BitCheermoteTierModel> tiers { get; set; } } }