content
stringlengths
23
1.05M
namespace StyleChecker { using Microsoft.CodeAnalysis; /// <summary> /// Provides utility methods for <c>ISymbol</c>s. /// </summary> public static class Symbols { /// <summary> /// Gets whether the specified symbols are equal. /// </summary> /// <param name="s1"> /// The symbol. /// </param> /// <param name="s2"> /// The other symbol. /// </param> /// <returns> /// <c>true</c> if <paramref name="s1"/> is equal to <paramref name="s2"/>, /// otherwise <c>false</c>. /// </returns> public static bool AreEqual(ISymbol s1, ISymbol? s2) { return SymbolEqualityComparer.Default .Equals(s1, s2); } } }
using System.Net; using System.Threading.Tasks; using NSubstitute; using Xunit; namespace Nanophone.Core.Tests { public class DnsHelperShould { [Fact] public async Task GetIpv4AddressAsync() { var address = await DnsHelper.GetIpAddressAsync(new DnsHostEntryProvider()); Assert.NotEmpty(address); } [Fact] public async Task GetIpv6AddressAsync() { var address = await DnsHelper.GetIpAddressAsync(new DnsHostEntryProvider(), ipv4: false); Assert.NotEmpty(address); } [Fact] public async Task BeEmptyWhenNoAddresses() { var hostEntryProvider = Substitute.For<IHostEntryProvider>(); hostEntryProvider.GetHostEntryAsync().Returns(new IPHostEntry()); var address = await DnsHelper.GetIpAddressAsync(hostEntryProvider); Assert.Empty(address); } } }
using System.Collections.Generic; using System.Linq; using Naif.Blog.Models; namespace Naif.Blog.Services { public class FileTagRepository : ITagRepository { private readonly IPostRepository _postRepository; public FileTagRepository(IPostRepository postRepository) { _postRepository = postRepository; } public IList<Tag> GetTags(string blogId) { var result = _postRepository.GetAllPosts(blogId).Where(Post.SearchPredicate) .SelectMany(post => post.Tags) .GroupBy(tag => tag.Name, (tagName, items) => new Tag { Name = tagName, Count = items.Count() }) .OrderBy(x => x.Name) .ToList(); return result; } } }
#nullable disable namespace PasPasPas.Typings.Serialization { internal partial class TypeReader { public T ReadTag<T>(T tag) where T : Tag { var kind = ReadUint(); tag.ReadData(kind, this); if (tag.Kind != kind) throw new TypeReaderWriteException(); return tag; } } internal partial class TypeWriter { /// <summary> /// write a tag /// </summary> /// <param name="tag"></param> /// <param name="reference"></param> public void WriteTag(Tag tag, Reference reference = default) { var v = tag.Kind; if (reference != default) WriteReferenceValue(reference); WriteUint(v); tag.WriteData(this); } } }
using RandomMediaPlayer.Core.Displayers; namespace RandomMediaPlayer.Actions { public interface IAutoAction { IAutoAction Register(IDisplayer displayer); IAutoAction Unregister(); } }
using DisruptorNetRedis.Networking; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace DisruptorNetRedis.DisruptorRedis { internal class RingBufferSlot { // populated by Translator public ClientSession Session = null; public List<byte[]> Data; // Populated by ClientRequestParser public Func<List<byte[]>, byte[]> Command; // populated by ResponseHandler public byte[] Response = null; } }
using UnityEngine; public class CameraControl : MonoBehaviour { public GameObject target; public Vector3 initialCameraPosition = new Vector3(0, 0, -1000); public float rotateSpeed = 10f; public float translateSpeed = 50f; public float scaleSpeed = 10f; private float scale = 1f; void Start() { Camera.main.transform.localPosition = this.initialCameraPosition; Camera.main.transform.localRotation = this.transform.rotation; } void Update() { if (Input.GetMouseButton(0)) { this.transform.localPosition += new Vector3( Input.GetAxis("Mouse X") * -this.translateSpeed, Input.GetAxis("Mouse Y") * -this.translateSpeed, 0); } if (Input.GetMouseButton(1)) { this.target.transform.eulerAngles += new Vector3( Input.GetAxis("Mouse Y") * this.rotateSpeed, Input.GetAxis("Mouse X") * -this.rotateSpeed, 0); } var scroll = Input.GetAxis("Mouse ScrollWheel"); if (scroll != 0) { this.scale += scroll * this.scaleSpeed; if (this.scale < 0) { this.scale = 0f; } this.target.transform.localScale = new Vector3(this.scale, this.scale, this.scale); } } }
using System; using UnityEngine; public class RightPanel : MonoBehaviour { public UIScrollView rightScrollView; public UIGrid rightGrid; public GameObject getAwardBtn; public GameObject haveGet; public GameObject skip; public GameObject time; public UILabel actityTime; public UILabel actitAwardType; public UISprite titleName; public GameObject NoAward; public LangeuageLabel btnDes; public UICenterOnChild centerChild; public GameObject OnlineTimeBtn; public UILabel OnlineTimeLabel; public GameObject cantGet; }
using System; using System.Collections.Generic; using System.Linq; namespace DotCore.Core { public interface IIdentifiable { ulong Id { get; } } public interface IIdentified { uint Id { get; } } }
using PatchesAndAreasApi.V1.Domain; using PatchesAndAreasApi.V1.Infrastructure; namespace PatchesAndAreasApi.V1.Factories { public static class EntityFactory { public static PatchEntity ToDomain(this PatchesDb databaseEntity) { return new PatchEntity { Id = databaseEntity.Id, ParentId = databaseEntity.ParentId, Name = databaseEntity.Name, Domain = databaseEntity.Domain, PatchType = databaseEntity.PatchType, ResponsibleEntities = databaseEntity.ResponsibleEntities, VersionNumber = databaseEntity.VersionNumber }; } public static PatchesDb ToDatabase(this PatchEntity entity) { return new PatchesDb { Id = entity.Id, ParentId = entity.ParentId, Name = entity.Name, Domain = entity.Domain, PatchType = entity.PatchType, ResponsibleEntities = entity.ResponsibleEntities.ToListOrEmpty(), VersionNumber = entity.VersionNumber }; } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Abp; using Abp.Application.Services; using Abp.Domain.Repositories; using Abp.AutoMapper; using System.Linq; using Abp.Authorization; using Abp.Localization; using Abp.Application.Services.Dto; using Abp.Configuration; using Abp.Runtime.Caching; namespace Fostor.Ginkgo.Sys { public class SysSettingAppService : GinkgoAppServiceBase,ISysSettingAppService { public ISettingStore SettingStore { get; set; } private readonly ITypedCache<string, Dictionary<string, SettingInfo>> _applicationSettingCache; private readonly ITypedCache<int, Dictionary<string, SettingInfo>> _tenantSettingCache; public SysSettingAppService(ICacheManager cacheManager) { SettingStore = DefaultConfigSettingStore.Instance; _applicationSettingCache = cacheManager.GetApplicationSettingsCache(); _tenantSettingCache = cacheManager.GetTenantSettingsCache(); } public async Task<string> GetTenantSettingValue(string name) { string val = ""; var list = await GetTenantAllSettings(); foreach(var x in list) { if (x.Name == name) { val = x.Value; } } return val; } public async Task<IReadOnlyList<ISettingValue>> GetTenantAllSettings() { if (AbpSession.TenantId.HasValue) { return await SettingManager.GetAllSettingValuesForTenantAsync(AbpSession.TenantId.Value); } else { return await SettingManager.GetAllSettingValuesForApplicationAsync(); } } public async Task UpdateTenantSetting(string name, string value) { if (AbpSession.TenantId.HasValue) { await SettingStore.UpdateAsync(new SettingInfo { TenantId = AbpSession.TenantId.Value, Name = name, Value = value }); await _tenantSettingCache.ClearAsync(); } else { await SettingStore.UpdateAsync(new SettingInfo { Name = name, Value = value }); await _applicationSettingCache.ClearAsync(); } } public async Task CreateTenantSetting(string name, string value) { if (AbpSession.TenantId.HasValue) { await SettingStore.CreateAsync(new SettingInfo { TenantId = AbpSession.TenantId.Value, Name = name, Value = value }); await _tenantSettingCache.ClearAsync(); } else { await SettingStore.CreateAsync(new SettingInfo { Name = name, Value = value }); await _applicationSettingCache.ClearAsync(); } } public async Task DeleteTenantSetting(string name, string value) { if (AbpSession.TenantId.HasValue) { await SettingStore.DeleteAsync(new SettingInfo { TenantId = AbpSession.TenantId.Value, Name = name, Value = value }); await _tenantSettingCache.ClearAsync(); } else { await SettingStore.DeleteAsync(new SettingInfo { Name = name, Value = value }); await _applicationSettingCache.ClearAsync(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PZModels; namespace ApplicationServices { interface IPZService { List<Restaurant> GetAllRestaurants(); List<Review> GetAllReviews(); Restaurant GetRestaurantById(int id); Restaurant GetRestaurantByName(string name); List<Review> GetAllReviewsForRestaurant(string restaurant); void UpdateAverageRating(Restaurant restaurant); List<Restaurant> GetTopThreeRestaurants(); List<Restaurant> GetRestaurantsByOrder(string order); List<Restaurant> GetRestaurantBySearch(string search); void AddRestaurant(Restaurant restaurant); void RemoveRestaurant(int id); void UpdateRestaurant(Restaurant restaurant); void AddReview(Review review); void RemoveReview(int id); void RemoveAllReviews(ICollection<Review> reviews); void UpdateReview(Review review); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Ocean : MonoBehaviour { MeshFilter myMeshFilter; Vector3[] vertices; Color[] colors; bool[] ignore; List<Collider> myBoatColliders; const float FoamReductionRate = 0.05f; private void Awake() { myMeshFilter = GetComponent<MeshFilter>(); } void Start() { vertices = myMeshFilter.mesh.vertices; colors = myMeshFilter.mesh.colors; ignore = new bool[vertices.Length]; myBoatColliders = new List<Collider>(); for (int i = 0; i < vertices.Length; ++i) { vertices[i] = transform.localToWorldMatrix.MultiplyPoint3x4(vertices[i]); if (colors[i].g > 0f) { ignore[i] = true; } else { ignore[i] = false; } } } private void OnEnable() { } private void OnDisable() { } private void Update() { for (int i = 0; i < vertices.Length; ++i) { for (int j = 0; j < myBoatColliders.Count; ++j) { if (myBoatColliders[j].bounds.Contains(vertices[i])) { if (!ignore[i]) { colors[i].g = 1f; } } else { if (!ignore[i]) { colors[i].g = Mathf.Clamp01(colors[i].g - Time.deltaTime * FoamReductionRate); } } } } myMeshFilter.mesh.colors = colors; } }
using Havit.Blazor.Components.Web.Infrastructure; using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Havit.Blazor.Components.Web.Bootstrap { /// <summary> /// Displays the content of the component as "in progress". /// </summary> public partial class HxProgressIndicator { private bool progressIndicatorVisible; private CancellationTokenSource delayCancellationTokenSource; /// <summary> /// Default debounce delay in miliseconds to be used when <see cref="Delay"/> not set. /// Default DefaultDelay is <c>300 ms</c>. /// </summary> public static int DefaultDelay { get; set; } = 300; /// <summary> /// Indicates whether the content should be displayed as "in progress". /// </summary> [Parameter] public bool InProgress { get; set; } /// <summary> /// Debounce delay in miliseconds. If not set, uses the <see cref="DefaultDelay"/>. /// </summary> [Parameter] public int? Delay { get; set; } /// <summary> /// Wrapped content. /// </summary> [Parameter] public RenderFragment ChildContent { get; set; } protected EventCallback<bool> ProgressIndicatorVisibleChanged { get; set; } protected override async Task OnParametersSetAsync() { await base.OnParametersSetAsync(); bool shouldBeProgressIndicatorVisible = InProgress; if (shouldBeProgressIndicatorVisible && !progressIndicatorVisible) { // start showing progress indicator (when not already started) StartInProgressWithDelay(); } else if (!shouldBeProgressIndicatorVisible) { if (progressIndicatorVisible) { // hide progress indicator if visible progressIndicatorVisible = false; await ProgressIndicatorVisibleChanged.InvokeAsync(progressIndicatorVisible); } if (delayCancellationTokenSource != null) { // cancel showing progress indicator delayCancellationTokenSource.Cancel(); delayCancellationTokenSource = null; } } } private void StartInProgressWithDelay() { if (delayCancellationTokenSource == null) { delayCancellationTokenSource = new CancellationTokenSource(); CancellationToken cancellationToken = delayCancellationTokenSource.Token; Task.Run(async () => { try { await Task.Delay(Delay ?? HxProgressIndicator.DefaultDelay, cancellationToken); } catch (TaskCanceledException) { // NOOP } if (!cancellationToken.IsCancellationRequested) { await InvokeAsync(async () => { progressIndicatorVisible = true; await ProgressIndicatorVisibleChanged.InvokeAsync(progressIndicatorVisible); StateHasChanged(); }); } }); } } } }
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* NonCloseableStreamReader.cs -- non-closeable stream reader * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System; using System.IO; using System.Text; using JetBrains.Annotations; #endregion namespace AM.IO { /// <summary> /// Non-closeable stream reader. /// </summary> [PublicAPI] public class NonCloseableStreamReader : StreamReader, IDisposable { #region Construction /// <summary> /// Constructor. /// </summary> public NonCloseableStreamReader ( [NotNull] Stream stream ) : base(stream) { } #if !UAP /// <summary> /// Constructor. /// </summary> public NonCloseableStreamReader ( [NotNull] string path ) : base(path) { } #endif /// <summary> /// Constructor. /// </summary> public NonCloseableStreamReader ( [NotNull] Stream stream, bool detectEncodingFromByteOrderMarks ) : base(stream, detectEncodingFromByteOrderMarks) { } /// <summary> /// Constructor. /// </summary> public NonCloseableStreamReader ( [NotNull] Stream stream, [NotNull] Encoding encoding ) : base(stream, encoding) { } #if !UAP /// <summary> /// Constructor. /// </summary> public NonCloseableStreamReader ( [NotNull] string path, bool detectEncodingFromByteOrderMarks ) : base(path, detectEncodingFromByteOrderMarks) { } /// <summary> /// Constructor. /// </summary> public NonCloseableStreamReader ( [NotNull] string path, [NotNull] Encoding encoding ) : base(path, encoding) { } #endif /// <summary> /// Constructor. /// </summary> public NonCloseableStreamReader ( [NotNull] Stream stream, [NotNull] Encoding encoding, bool detectEncodingFromByteOrderMarks ) : base(stream, encoding, detectEncodingFromByteOrderMarks) { } #if !UAP /// <summary> /// Constructor. /// </summary> public NonCloseableStreamReader ( [NotNull] string path, [NotNull] Encoding encoding, bool detectEncodingFromByteOrderMarks ) : base(path, encoding, detectEncodingFromByteOrderMarks) { } #endif /// <summary> /// Constructor. /// </summary> /// <param name="reader">The reader.</param> public NonCloseableStreamReader ( [NotNull] StreamReader reader ) : base(reader.BaseStream, reader.CurrentEncoding) { } #endregion #region Public methods /// <summary> /// Really close the reader. /// </summary> public virtual void ReallyClose() { BaseStream.Dispose(); } #endregion #region StreamReader members /// <summary> /// NOT closes the <see cref="T:System.IO.StreamReader"></see> /// object and the underlying stream, and releases any system resources /// associated with the reader. /// </summary> public #if !UAP override #endif void Close() { // Nothing to do actually } /// <inheritdoc cref="StreamReader.Dispose(bool)" /> protected override void Dispose(bool disposing) { // Nothing to do actually } #endregion #region IDisposable Members /// <inheritdoc cref="IDisposable.Dispose" /> void IDisposable.Dispose() { // Nothing to do actually } #endregion } }
using System.Runtime.CompilerServices; using System.Reflection; [assembly: AssemblyTitle("GGQL Core")]
namespace AMA.SchoolManagementSystem.Services { using AMA.SchoolManagementSystem.Data.Contracts; using AMA.SchoolManagementSystem.Data.Model; using AMA.SchoolManagementSystem.Services.Contracts; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class UserService : IUserService { private ISaveContext saveContext; public UserService(ISaveContext saveContext) { this.saveContext = saveContext; } public void AddPrincipal(UserAuthModel userAuthModel) { var roleStore = new RoleStore<IdentityRole>(saveContext.Context); var roleManager = new RoleManager<IdentityRole>(roleStore); if (!roleManager.RoleExists("Principal")) { var role = new IdentityRole { Name = "Principal" }; roleManager.Create(role); } var userStore = new UserStore<User>(saveContext.Context); var userManager = new UserManager<User>(userStore); var user = new User { UserName = userAuthModel.Email, Email = userAuthModel.Email, EmailConfirmed = true }; userManager.Create(user, userAuthModel.Password); userManager.AddToRole(user.Id, "Principal"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using lm.Comol.Core.DomainModel; using lm.Comol.Core.BaseModules.NoticeBoard.Business; using lm.Comol.Core.BaseModules.NoticeBoard.Domain; using lm.Comol.Core.Business; using lm.Comol.Core.BaseModules.Editor; using lm.Comol.Core.BaseModules.Editor.Business; namespace lm.Comol.Core.BaseModules.NoticeBoard.Presentation { public class CreateThumbnailPresenter : lm.Comol.Core.DomainModel.Common.DomainPresenter { #region "Init / Default" private int _ModuleID; private ServiceNoticeBoard _Service; private int ModuleID { get { if (_ModuleID <= 0) { _ModuleID = this.Service.ServiceModuleID(); } return _ModuleID; } } protected virtual BaseModuleManager CurrentManager { get; set; } protected virtual IViewCreateThumbnail View { get { return (IViewCreateThumbnail)base.View; } } private ServiceNoticeBoard Service { get { if (_Service == null) _Service = new ServiceNoticeBoard(AppContext); return _Service; } } #endregion public CreateThumbnailPresenter(iApplicationContext oContext) : base(oContext) { this.CurrentManager = new BaseModuleManager(oContext); } public CreateThumbnailPresenter(iApplicationContext oContext, IViewCreateThumbnail view) : base(oContext, view) { this.CurrentManager = new BaseModuleManager(oContext); } public void InitView(long idMessage, Int32 idCommunity){ View.GenerateThumbnail(idMessage, idCommunity); } } }
using System.Diagnostics; // Segment counts const int ZERO_COUNT = 6; // 0, 6, 9 const int ONE_COUNT = 2; const int THREE_COUNT = 5; // 2, 3, 5 const int FOUR_COUNT = 4; const int SEVEN_COUNT = 3; const int EIGHT_COUNT = 7; static int P1(IEnumerable<string> lines) { return lines.Select(s => s.Split('|')[1].Split(' ').Where(digit => { var l = digit.Trim().Length; return l == ONE_COUNT || l == FOUR_COUNT || l == SEVEN_COUNT || l == EIGHT_COUNT; }).Count()).Sum(); } var test = @"be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce".Split('\n'); Debug.Assert(P1(test) == 26); var input = File.ReadLines("input.txt"); Debug.Assert(P1(input) == 381); static IList<HashSet<char>> FindDigits(string line) { var digits = line.Trim().Split(' ').Select(s => s.ToHashSet()).ToArray(); var one = digits.Where(s => s.Count == ONE_COUNT).Single(); var four = digits.Where(s => s.Count == FOUR_COUNT).Single(); var seven = digits.Where(s => s.Count == SEVEN_COUNT).Single(); var eight = digits.Where(s => s.Count == EIGHT_COUNT).Single(); var nine = digits.Where(s => s.Count == ZERO_COUNT && s.IsProperSupersetOf(four)).Single(); var zero = digits.Where(s => s.Count == ZERO_COUNT && s != nine && s.IsProperSupersetOf(seven)).Single(); var three = digits.Where(s => s.Count == THREE_COUNT && s.IsProperSupersetOf(seven)).Single(); var six = digits.Where(s => s.Count == ZERO_COUNT && s != zero && s != nine).Single(); var five = digits.Where(s => s.Count == THREE_COUNT && s.IsProperSubsetOf(six)).Single(); var two = digits.Where(s => s.Count == THREE_COUNT && s != three && s != five).Single(); return new List<HashSet<char>> { zero, one, two, three, four, five, six, seven, eight, nine }; } static int P2(IEnumerable<string> lines) { var res = 0; foreach (var line in lines) { var input = line.Split('|'); var digits = FindDigits(input[0]); var output = input[1].Trim().Split(' ').Reverse(); foreach (var (outDigit, idx) in output.Select((s, idx) => (s.ToHashSet(), idx))) { foreach (var (digit, num) in digits.Select((s, i) => (s, i))) { if (digit.SetEquals(outDigit)) { res += num * (int)Math.Pow(10, idx); break; } } } } return res; } Debug.Assert(P2(test) == 61229); Debug.Assert(P2(input) == 1023686);
using EmailDaemon.Auth; using EmailDaemon.EmailDatabase; using EmailDaemon.Graph; using System; using System.Threading; namespace EmailDaemon { /// <summary> /// Program which syncs microsoft outlook email using Microsoft Graph and saves the results /// using EFCore. /// </summary> class Program { static void Main(string[] args) { using (var db = new EmailContext()) { // Create a new app this will also log the user in. var authApp = new AuthApp(); // Create a new email handler for retrieving emails using MS Graph. var graphEmailClient = new GraphEmailHandler(authApp); // Database handler. var dbHandler = new EmailDbStorage(authApp.UserAccount.Username, db); // Handler for syncing emails with the database. var emailHandler = new EmailHandler.EmailHandler(graphEmailClient, dbHandler); Console.WriteLine("Syncing email database..."); // Complete the initial sync with the database. emailHandler.InitialEmailsSyncAsync(); while(! Console.KeyAvailable) { Console.WriteLine("Updating email db..."); // Sync the emails until a key is pressed. emailHandler.SyncEmailsAsync(); // Sleep so that the db is not updated more than every 30s. // TODO: make this async. Thread.Sleep(30000); } } } } }
namespace Resonance.Data.Models { public enum Role { Administrator = 0, Playback = 1, Settings = 2, Download = 3 } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using EventSourcing.Poc.EventSourcing.Jobs; using EventSourcing.Poc.EventSourcing.Wrapper; using EventSourcing.Poc.Messages; using JetBrains.Annotations; namespace EventSourcing.Poc.EventSourcing.Command { public interface ICommandDispatcher { Task<IJob> Send([NotNull] ICommand command, [CanBeNull] TimeSpan? timeout = null); Task<IJob> Send([NotNull] IReadOnlyCollection<ICommand> commands, [CanBeNull] TimeSpan? timeout = null); } public interface IActionDispatcher { Task Send([NotNull] IEventWrapper eventParent, [NotNull] IAction action); Task Send([NotNull] IEventWrapper eventParent, [NotNull] IReadOnlyCollection<IAction> actions); } }
using System; namespace Bytewizer.TinyCLR.DigitalPortal { public static class DateTimeExtensions { //public static int ToUnixTimestamp(this DateTime date) //{ // return (int)Math.Truncate(date.ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds); //} //private static DateTime ConvertTimestampToDate(string timestamp) //{ // var getDate = new DateTime(1970, 1, 1, 0, 0, 0, 0); // return getDate.AddSeconds(int.Parse(timestamp)); //} } }
using System.ComponentModel.DataAnnotations; namespace Forum.Backend.Web.Endpoints.AccountEndpoints { public class LoginRequest { public const string Route = "/Accounts"; [Required] public string Email { get; set; } [Required] public string Password { get; set; } } }
namespace NaftanRailway.UnitTests.SOLID { using System; internal class MicroAccount : Account { // Preconditions - conditions can't be able to stressed by subclass. // Subclasses can't make additional conditional, than in base class. public override void SetCapital(int money) { if (money < 0) { throw new Exception("Нельзя положить на счет меньше 0"); } // Mistake (additional condition compare to base class. if (money > 100) { throw new Exception("Нельзя положить на счет больше 100"); } this.Capital = money; } public override decimal GetInterest(decimal sum, int month, int rate) { if (sum < 0 || month > 12 || month < 1 || rate < 0) { throw new Exception("Wrong data"); } decimal result = sum; for (int i = 0; i < month; i++) { // Postcondition ( loosen ). result += result * rate / 100; } return result; } } }
using ChocolArm64.Instruction; using ChocolArm64.Memory; using ChocolArm64.State; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Reflection.Emit; namespace ChocolArm64.Decoder { static class ADecoder { private delegate object OpActivator(AInst Inst, long Position, int OpCode); private static ConcurrentDictionary<Type, OpActivator> OpActivators; static ADecoder() { OpActivators = new ConcurrentDictionary<Type, OpActivator>(); } public static ABlock DecodeBasicBlock(AThreadState State, AMemory Memory, long Start) { ABlock Block = new ABlock(Start); FillBlock(State, Memory, Block); return Block; } public static (ABlock[] Graph, ABlock Root) DecodeSubroutine( ATranslatorCache Cache, AThreadState State, AMemory Memory, long Start) { Dictionary<long, ABlock> Visited = new Dictionary<long, ABlock>(); Dictionary<long, ABlock> VisitedEnd = new Dictionary<long, ABlock>(); Queue<ABlock> Blocks = new Queue<ABlock>(); ABlock Enqueue(long Position) { if (!Visited.TryGetValue(Position, out ABlock Output)) { Output = new ABlock(Position); Blocks.Enqueue(Output); Visited.Add(Position, Output); } return Output; } ABlock Root = Enqueue(Start); while (Blocks.Count > 0) { ABlock Current = Blocks.Dequeue(); FillBlock(State, Memory, Current); //Set child blocks. "Branch" is the block the branch instruction //points to (when taken), "Next" is the block at the next address, //executed when the branch is not taken. For Unconditional Branches //(except BL/BLR that are sub calls) or end of executable, Next is null. if (Current.OpCodes.Count > 0) { bool HasCachedSub = false; AOpCode LastOp = Current.GetLastOp(); if (LastOp is AOpCodeBImm Op) { if (Op.Emitter == AInstEmit.Bl) { HasCachedSub = Cache.HasSubroutine(Op.Imm); } else { Current.Branch = Enqueue(Op.Imm); } } if (!((LastOp is AOpCodeBImmAl) || (LastOp is AOpCodeBReg)) || HasCachedSub) { Current.Next = Enqueue(Current.EndPosition); } } //If we have on the graph two blocks with the same end position, //then we need to split the bigger block and have two small blocks, //the end position of the bigger "Current" block should then be == to //the position of the "Smaller" block. while (VisitedEnd.TryGetValue(Current.EndPosition, out ABlock Smaller)) { if (Current.Position > Smaller.Position) { ABlock Temp = Smaller; Smaller = Current; Current = Temp; } Current.EndPosition = Smaller.Position; Current.Next = Smaller; Current.Branch = null; Current.OpCodes.RemoveRange( Current.OpCodes.Count - Smaller.OpCodes.Count, Smaller.OpCodes.Count); VisitedEnd[Smaller.EndPosition] = Smaller; } VisitedEnd.Add(Current.EndPosition, Current); } //Make and sort Graph blocks array by position. ABlock[] Graph = new ABlock[Visited.Count]; while (Visited.Count > 0) { ulong FirstPos = ulong.MaxValue; foreach (ABlock Block in Visited.Values) { if (FirstPos > (ulong)Block.Position) FirstPos = (ulong)Block.Position; } ABlock Current = Visited[(long)FirstPos]; do { Graph[Graph.Length - Visited.Count] = Current; Visited.Remove(Current.Position); Current = Current.Next; } while (Current != null); } return (Graph, Root); } private static void FillBlock(AThreadState State, AMemory Memory, ABlock Block) { long Position = Block.Position; AOpCode OpCode; do { //TODO: This needs to be changed to support both AArch32 and AArch64, //once JIT support is introduced on AArch32 aswell. OpCode = DecodeOpCode(State, Memory, Position); Block.OpCodes.Add(OpCode); Position += 4; } while (!(IsBranch(OpCode) || IsException(OpCode))); Block.EndPosition = Position; } private static bool IsBranch(AOpCode OpCode) { return OpCode is AOpCodeBImm || OpCode is AOpCodeBReg; } private static bool IsException(AOpCode OpCode) { return OpCode.Emitter == AInstEmit.Brk || OpCode.Emitter == AInstEmit.Svc || OpCode.Emitter == AInstEmit.Und; } public static AOpCode DecodeOpCode(AThreadState State, AMemory Memory, long Position) { int OpCode = Memory.ReadInt32(Position); AInst Inst; if (State.ExecutionMode == AExecutionMode.AArch64) { Inst = AOpCodeTable.GetInstA64(OpCode); } else { //TODO: Thumb support. Inst = AOpCodeTable.GetInstA32(OpCode); } AOpCode DecodedOpCode = new AOpCode(AInst.Undefined, Position, OpCode); if (Inst.Type != null) { DecodedOpCode = MakeOpCode(Inst.Type, Inst, Position, OpCode); } return DecodedOpCode; } private static AOpCode MakeOpCode(Type Type, AInst Inst, long Position, int OpCode) { if (Type == null) { throw new ArgumentNullException(nameof(Type)); } OpActivator CreateInstance = OpActivators.GetOrAdd(Type, CacheOpActivator); return (AOpCode)CreateInstance(Inst, Position, OpCode); } private static OpActivator CacheOpActivator(Type Type) { Type[] ArgTypes = new Type[] { typeof(AInst), typeof(long), typeof(int) }; DynamicMethod Mthd = new DynamicMethod($"Make{Type.Name}", Type, ArgTypes); ILGenerator Generator = Mthd.GetILGenerator(); Generator.Emit(OpCodes.Ldarg_0); Generator.Emit(OpCodes.Ldarg_1); Generator.Emit(OpCodes.Ldarg_2); Generator.Emit(OpCodes.Newobj, Type.GetConstructor(ArgTypes)); Generator.Emit(OpCodes.Ret); return (OpActivator)Mthd.CreateDelegate(typeof(OpActivator)); } } }
using UnityEngine; public class Push : Effect { public Push(Entity target, GoalDirection direction, int distance = 1) { name = "push"; entity = target; var directionVector = GlobalHelper.GetVectorForDirection(direction); for (var i = 0; i < distance; i++) { var targetTileCoordinates = new Vector2(target.CurrentTile.X + directionVector.x, target.CurrentTile.Y + directionVector.y); if (!target.AreaMapCanMoveLocal(targetTileCoordinates)) { break; } target.AreaMove(targetTileCoordinates); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PalvelutoriModel.Search { public class TilausData { [JsonProperty("aika")] public Aika Aika { get; set; } [JsonProperty("paiva")] public string Paiva { get; set; } [JsonProperty("paketti")] public PalveluPaketti Paketti { get; set; } [JsonProperty("kohde")] public KohdeTiedot Kohde { get; set; } [JsonProperty("me")] public KayttajaTiedot Me { get; set; } [JsonProperty("yritys")] public YritysTiedot Yritys { get; set; } /// <summary> /// Hinta euroina /// </summary> [JsonProperty("hinta2")] public double Hinta2 { get; set; } /// <summary> /// Kesto tunteina /// </summary> [JsonProperty("kesto")] public double Kesto { get; set; } [JsonProperty("lisatiedot")] public string Lisatiedot { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Console; using System.IO; namespace Importer { public class LeveeList { #region Notes // Created By: $username$ // Created Date: $time$ #endregion #region Fields private Levee _Levee; private SortedList<string, Levee> _LeveeListSort = new SortedList<string, Levee>(); #endregion #region Properties public SortedList<string, Levee> Levees { get { return _LeveeListSort; } } public long IdCurrent { get; set; } #endregion #region Constructors public LeveeList() { } #endregion #region Voids public void Add(Levee theLevee) { Levee aLevee = ObjectCopier.Clone(theLevee); WriteLine($"Add Levee to SortList. Name: {aLevee.Name}"); _LeveeListSort.Add(aLevee.Name.Trim(), aLevee); if(GlobalVariables.mp_fdaStudy._TraceConvertLevel > 19) aLevee.Print(); } public void Print() { Levee aLevee; WriteLine($"Number of Levees {_LeveeListSort.Count}"); for (int i = 0; i < _LeveeListSort.Count; i++) { aLevee = _LeveeListSort.ElementAt(i).Value; aLevee.Print(); } } public void PrintToFile() { Levee aLevee; WriteLine($"Number of Levees {_LeveeListSort.Count}"); for (int i = 0; i < _LeveeListSort.Count; i++) { aLevee = _LeveeListSort.ElementAt(i).Value; aLevee.PrintToFile(); } } public void Export(StreamWriter wr, char delimt) { Levee aLevee; for (int i = 0; i < _LeveeListSort.Count; i++) { aLevee = _LeveeListSort.ElementAt(i).Value; aLevee.Export(wr, delimt); } } #endregion #region Functions public long getNextId() { IdCurrent = GlobalVariables.mp_fdaStudy.GetNextIdMgr().getNextObjIdLevData(); return IdCurrent; } public long getCurrentId() { IdCurrent = GlobalVariables.mp_fdaStudy.GetNextIdMgr().getCurrentObjIdLevData(); return IdCurrent; } public Levee GetLevee(string nameLevee) { int ix = _LeveeListSort.IndexOfKey(nameLevee); _Levee = _LeveeListSort.ElementAt(ix).Value; WriteLine($"Did I find the {nameLevee} Levee, name = {_Levee.Name}"); return _Levee; } public string GetName(long theId) { string name = ""; bool found = false; Levee aFunc = null; for (int i = 0; i < _LeveeListSort.Count && !found; i++) { aFunc = _LeveeListSort.ElementAt(i).Value; if (theId == aFunc.Id) { found = true; name = aFunc.Name; } } return name; } #endregion } }
//<unit_header> //---------------------------------------------------------------- // // Martin Korneffel: IT Beratung/Softwareentwicklung // Stuttgart, den 4.4.2017 // // Projekt.......: KeplerBI.MVC // Name..........: CfgLengthRng.cs // Aufgabe/Fkt...: Model für Konfiguration von Längenbereichen // // // // // //<unit_environment> //------------------------------------------------------------------ // Zielmaschine..: PC // Betriebssystem: Windows 7 mit .NET 4.5 // Werkzeuge.....: Visual Studio 2013 // Autor.........: Martin Korneffel (mko) // Version 1.0...: // // </unit_environment> // //<unit_history> //------------------------------------------------------------------ // // Version.......: 1.1 // Autor.........: Martin Korneffel (mko) // Datum.........: // Änderungen....: // //</unit_history> //</unit_header> using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace KeplerBI.MVC.Models { /// <summary> /// Model für Konfiguration von Längenbereichen /// </summary> public class CfgLengthRng: CfgDblRange { public CfgLengthRng( string colName, bool viewCol, string rpnOri, string Controller, string Action, Cfg.SortDirection sort, mko.BI.Bo.Interval<double> range, mko.BI.Bo.Interval<double> subRange, double beginMeasure, string beginUnit, double endMeasure, string endUnit) : base(colName, viewCol, rpnOri, Controller, Action, sort, range, subRange) { } /// <summary> /// Liste der Maßeinheiten /// </summary> public IEnumerable<string> Units { get { yield return "m"; yield return "KM"; yield return "AU"; } } public double BeginMeasure { get; } public string BeginUnit { get; } public double EndMeasure { get; } public string EndUnit { get; } } }
using System; namespace desafio_3 { class Desafio { static void Main() { const int totalConvidados = 5; int[] convidados = {300, 1500, 600, 1000, 150}; int total = 225; for (int i = 0; i < totalConvidados; i++) { total += (convidados[i] * StrToIntDef(Console.ReadLine(), 1)); } Console.WriteLine(total); Console.ReadLine(); } public static int StrToIntDef(string value, int @default) { if (int.TryParse(value, out int number)) return number; return @default; } } }
using DateModel; using Microsoft.EntityFrameworkCore; using OperateService.Iservice; using PlatData; using PlatData.SysTable; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace OperateService.Service { /// <summary> /// 数据库基础操作类 /// </summary> public class BaseOperateDbService<T> : BaseService, IBaseOperateDbService<T> where T : SysObject { private readonly IUnitOfWork _unitofwork; /// <summary> /// 构造注入 /// </summary> /// <param name="unitOfWork"></param> public BaseOperateDbService(IUnitOfWork unitOfWork) { _unitofwork = unitOfWork; } /// <summary> /// 数据表 /// </summary> public virtual DbSet<T> Table => _unitofwork.GetDbContext().Set<T>(); public async Task<Message> CreateNew(T table) { try { var addinsult= await _unitofwork.GetDbContext().Set<T>().AddAsync(table); } catch (Exception e) { base.MessageDate.IsSucess = false; base.MessageDate.MessageStr = e.Message; } return base.MessageDate; } public Message DeleteTable(T table) { try { var reletresult = _unitofwork.GetDbContext().Set<T>().Remove(table); } catch (Exception e) { base.MessageDate.IsSucess = false; base.MessageDate.MessageStr = e.Message; } return base.MessageDate; } public IEnumerable<T> Getenumablelist(Expression<Func<T, bool>> whereLambda) { return _unitofwork.GetDbContext().Set<T>().Where(whereLambda).ToList(); } public IQueryable<T> GetQuery(Expression<Func<T, bool>> whereLambda) { return _unitofwork.GetDbContext().Set<T>().Where(whereLambda); } public async Task<List<T>> Select(Expression<Func<T, bool>> whereLambda) { return await _unitofwork.GetDbContext().Set<T>().Where(whereLambda).AsNoTracking().ToListAsync(); } public T First(Expression<Func<T, bool>> whereLambda) { return _unitofwork.GetDbContext().Set<T>().FirstOrDefault(whereLambda); } public T FirstNoTrack(Expression<Func<T, bool>> whereLambda) { return _unitofwork.GetDbContext().Set<T>().AsNoTracking().FirstOrDefault(whereLambda); } public Message Update(T entity) { try { var upresult = _unitofwork.GetDbContext().Set<T>().Update(entity); } catch (Exception e) { base.MessageDate.IsSucess = false; base.MessageDate.MessageStr = e.Message; } return base.MessageDate; } /// <summary> /// 保存所有track修改 /// </summary> /// <returns></returns> public async Task<Message<int>> SaveTrackAsync() { try { var savecount = await _unitofwork.SaveChangesAsync(); return new Message<int>(savecount); } catch (Exception e) { return new Message<int>(false, e.Message); } } } }
using System; using System.Collections.Generic; using System.Linq; using QuranX.Persistence.Models; using QuranX.Persistence.Services.Repositories; using QuranX.Shared.Models; using QuranX.Web.Models; namespace QuranX.Web.Factories { public interface ICommentariesForVerseFactory { CommentariesForVerse Create(int chapterNumber, int verseNumber); CommentariesForVerse Create(string commentatorCode, int chapterNumber, int verseNumber); } public class CommentariesForVerseFactory : ICommentariesForVerseFactory { private readonly IChapterRepository ChapterRepository; private readonly ICommentatorRepository CommentatorRepository; private readonly ICommentaryRepository CommentaryRepository; public CommentariesForVerseFactory( IChapterRepository chapterRepository, ICommentatorRepository commentatorRepository, ICommentaryRepository commentaryRepository) { ChapterRepository = chapterRepository; CommentatorRepository = commentatorRepository; CommentaryRepository = commentaryRepository; } public CommentariesForVerse Create(int chapterNumber, int verseNumber) => Create(commentatorCode: null, chapterNumber: chapterNumber, verseNumber: verseNumber); public CommentariesForVerse Create(string commentatorCode, int chapterNumber, int verseNumber) { Dictionary<string, Commentator> commentatorByCode = CommentatorRepository.GetAll() .ToDictionary(x => x.Code, StringComparer.InvariantCultureIgnoreCase); Chapter chapter = ChapterRepository.Get(chapterNumber); IEnumerable<Commentary> commentaries; if (string.IsNullOrEmpty(commentatorCode)) commentaries = CommentaryRepository.GetForVerse(chapterNumber, verseNumber); else { commentaries = new Commentary[] { CommentaryRepository.GetForVerse(commentatorCode, chapterNumber, verseNumber) } .Where(x => x != null); } IEnumerable<CommentatorAndCommentary> commentatorsAndCommentaries = commentaries .OrderBy(x => x.CommentatorCode) .Select( x => new CommentatorAndCommentary( commentator: commentatorByCode[x.CommentatorCode], commentary: x) ); var selectChapterAndVerse = new SelectChapterAndVerse( selectedChapterNumber: chapterNumber, selectedVerseNumber: verseNumber, url: "/Tafsirs"); var viewModel = new CommentariesForVerse( chapter: chapter, verseNumber: verseNumber, selectChapterAndVerse: selectChapterAndVerse, commentaries: commentatorsAndCommentaries); return viewModel; } } }
using System.Diagnostics.CodeAnalysis; using HarmonyLib; using SolastaCommunityExpansion.CustomDefinitions; namespace SolastaCommunityExpansion.Patches.Insertion; internal static class RulesetCharacterPatcher { [HarmonyPatch(typeof(RulesetCharacter), "IsSubjectToAttackOfOpportunity")] [SuppressMessage("Minor Code Smell", "S101:Types should be named in PascalCase", Justification = "Patch")] internal static class IsSubjectToAttackOfOpportunity { // ReSharper disable once RedundantAssignment internal static void Postfix(RulesetCharacter __instance, ref bool __result, RulesetCharacter attacker) { __result = AttacksOfOpportunity.IsSubjectToAttackOfOpportunity(__instance, attacker, __result); } } }
using System.Collections.Generic; using Sfa.Tl.Matching.Data.UnitTests.Repositories.Constants; namespace Sfa.Tl.Matching.Data.UnitTests.Repositories.EmailHistory.Builders { public class ValidEmailHistoryListBuilder { public IList<Domain.Models.EmailHistory> Build() => new List<Domain.Models.EmailHistory> { new() { Id = 1, OpportunityId = 1, EmailTemplateId = 2, SentTo = "recipient@test.com", CreatedBy = EntityCreationConstants.CreatedByUser, CreatedOn = EntityCreationConstants.CreatedOn, ModifiedBy = EntityCreationConstants.ModifiedByUser, ModifiedOn = EntityCreationConstants.ModifiedOn }, new() { Id = 2, OpportunityId = 3, EmailTemplateId = 4, SentTo = "recipient@test.com", CreatedBy = EntityCreationConstants.CreatedByUser, CreatedOn = EntityCreationConstants.CreatedOn, ModifiedBy = EntityCreationConstants.ModifiedByUser, ModifiedOn = EntityCreationConstants.ModifiedOn } }; } }
// Copyright (c) 2017 Leacme (http://leac.me). View LICENSE.md for more information. using System.Collections.Generic; using Avalonia; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Threading; using Leacme.Lib.Laugger; namespace Leacme.App.Laugger { public class AppUI { private StackPanel rootPan = (StackPanel)Application.Current.MainWindow.Content; private Library lib = new Library(); public AppUI() { var blb1 = App.TextBlock; blb1.TextAlignment = TextAlignment.Center; blb1.Text = "Loading... Local System Logs"; rootPan.Children.AddRange(new List<IControl> { blb1 }); Dispatcher.UIThread.InvokeAsync(async () => { var gridScroll = App.ScrollViewer; gridScroll.Height = App.Current.MainWindow.Height - 70; gridScroll.Background = Brushes.Transparent; App.Current.MainWindow.PropertyChanged += (z, zz) => { if (zz.Property.Equals(Window.HeightProperty)) { gridScroll.Height = App.Current.MainWindow.Height - 70; } }; var gridHolder = new StackPanel() { Margin = new Thickness(10, 0) }; gridScroll.Content = gridHolder; var logs = await lib.GetLocalLogs(); foreach (var log in logs) { var dg = App.DataGrid; dg.Height = 300; dg.SetValue(DataGrid.WidthProperty, AvaloniaProperty.UnsetValue); dg.AutoGeneratingColumn += (z, zz) => { zz.Column.Header = log.logName; }; dg.Items = log.logMessages; gridHolder.Children.Add(dg); } rootPan.Children.AddRange(new List<IControl> { gridScroll }); blb1.Text = "Loaded - Local System Logs"; }); } } }
using System; using System.Runtime.InteropServices; using SAM.API.Types; namespace SAM.API.Wrappers { public class SteamClient018 : NativeWrapper<ISteamClient018> { #region GetSteamUser012 public SteamUser012 GetSteamUser012(int user, int pipe) { return GetISteamUser<SteamUser012>(user, pipe, "SteamUser012"); } #endregion #region GetSteamUserStats007 public SteamUserStats007 GetSteamUserStats006(int user, int pipe) { return GetISteamUserStats<SteamUserStats007>(user, pipe, "STEAMUSERSTATS_INTERFACE_VERSION007"); } #endregion #region GetSteamUtils004 public SteamUtils005 GetSteamUtils004(int pipe) { return GetISteamUtils<SteamUtils005>(pipe, "SteamUtils005"); } #endregion #region GetSteamApps001 public SteamApps001 GetSteamApps001(int user, int pipe) { return GetISteamApps<SteamApps001>(user, pipe, "STEAMAPPS_INTERFACE_VERSION001"); } #endregion #region GetSteamApps008 public SteamApps008 GetSteamApps008(int user, int pipe) { return GetISteamApps<SteamApps008>(user, pipe, "STEAMAPPS_INTERFACE_VERSION008"); } #endregion #region CreateSteamPipe [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate int NativeCreateSteamPipe(IntPtr self); public int CreateSteamPipe() { return Call<int, NativeCreateSteamPipe>(Functions.CreateSteamPipe, ObjectAddress); } #endregion #region ReleaseSteamPipe [UnmanagedFunctionPointer(CallingConvention.ThisCall)] [return: MarshalAs(UnmanagedType.I1)] private delegate bool NativeReleaseSteamPipe(IntPtr self, int pipe); public bool ReleaseSteamPipe(int pipe) { return Call<bool, NativeReleaseSteamPipe>(Functions.ReleaseSteamPipe, ObjectAddress, pipe); } #endregion #region ReleaseSteamPipe [UnmanagedFunctionPointer(CallingConvention.ThisCall)] [return: MarshalAs(UnmanagedType.I1)] private delegate bool NativeShutdownIfAllPipesClosed(IntPtr self); public bool ShutdownIfAllPipesClosed() { return Call<bool, NativeShutdownIfAllPipesClosed>(Functions.ShutdownIfAllPipesClosed, ObjectAddress); } #endregion #region CreateLocalUser [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate int NativeCreateLocalUser(IntPtr self, ref int pipe, AccountType type); public int CreateLocalUser(ref int pipe, AccountType type) { var call = GetFunction<NativeCreateLocalUser>(Functions.CreateLocalUser); return call(ObjectAddress, ref pipe, type); } #endregion #region ConnectToGlobalUser [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate int NativeConnectToGlobalUser(IntPtr self, int pipe); public int ConnectToGlobalUser(int pipe) { return Call<int, NativeConnectToGlobalUser>( Functions.ConnectToGlobalUser, ObjectAddress, pipe); } #endregion #region ReleaseUser [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeReleaseUser(IntPtr self, int pipe, int user); public void ReleaseUser(int pipe, int user) { Call<NativeReleaseUser>(Functions.ReleaseUser, ObjectAddress, pipe, user); } #endregion #region SetLocalIPBinding [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeSetLocalIPBinding(IntPtr self, uint host, ushort port); public void SetLocalIPBinding(uint host, ushort port) { Call<NativeSetLocalIPBinding>(Functions.SetLocalIPBinding, ObjectAddress, host, port); } #endregion #region GetISteamUser [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate IntPtr NativeGetISteamUser(IntPtr self, int user, int pipe, IntPtr version); private TClass GetISteamUser<TClass>(int user, int pipe, string version) where TClass : INativeWrapper, new() { using var nativeVersion = NativeStrings.StringToStringHandle(version); var address = Call<IntPtr, NativeGetISteamUser>( Functions.GetISteamUser, ObjectAddress, user, pipe, nativeVersion.Handle); var result = new TClass(); result.SetupFunctions(address); return result; } #endregion #region GetISteamUserStats [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate IntPtr NativeGetISteamUserStats(IntPtr self, int user, int pipe, IntPtr version); private TClass GetISteamUserStats<TClass>(int user, int pipe, string version) where TClass : INativeWrapper, new() { using var nativeVersion = NativeStrings.StringToStringHandle(version); var address = Call<IntPtr, NativeGetISteamUserStats>( Functions.GetISteamUserStats, ObjectAddress, user, pipe, nativeVersion.Handle); var result = new TClass(); result.SetupFunctions(address); return result; } #endregion #region GetISteamUtils [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate IntPtr NativeGetISteamUtils(IntPtr self, int pipe, IntPtr version); public TClass GetISteamUtils<TClass>(int pipe, string version) where TClass : INativeWrapper, new() { using var nativeVersion = NativeStrings.StringToStringHandle(version); var address = Call<IntPtr, NativeGetISteamUtils>( Functions.GetISteamUtils, ObjectAddress, pipe, nativeVersion.Handle); var result = new TClass(); result.SetupFunctions(address); return result; } #endregion #region GetISteamApps private delegate IntPtr NativeGetISteamApps(int user, int pipe, IntPtr version); private TClass GetISteamApps<TClass>(int user, int pipe, string version) where TClass : INativeWrapper, new() { using var nativeVersion = NativeStrings.StringToStringHandle(version); var address = Call<IntPtr, NativeGetISteamApps>( Functions.GetISteamApps, user, pipe, nativeVersion.Handle); var result = new TClass(); result.SetupFunctions(address); return result; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using WProject.UiLibrary.Interfaces; using WProject.UiLibrary.Style; using WProject.UiLibrary.Theme; namespace WProject.UiLibrary.Controls { public class WpButton : Button, ISelectableControl, IStylable { #region Implementation of ISelectableControl public event SelectedChangedHandler SelectedChanged; public bool Selected { get; set; } #endregion #region Implementation of IThemeable public void ApplyStyle() { ApplyTheme(this, WpThemeReader.GetUiStyle(WpThemeConstants.WPSTYLE_BUTTON)); } #endregion #region Public methods public static void ApplyTheme(WpButton button, UiStyle style) { button.BackColor = style.NormalStyle.BackColor; button.ForeColor = style.NormalStyle.ForeColor; button.Font = style.NormalStyle.Font; } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Video; public class timer : MonoBehaviour { public Text timerText; private float startTime; public float gameTime = 60f; public playerHealth ph; public gameManager gm; public bool finalBattle = false; public float finalFightTime = 30f; public VideoPlayer vp; public RawImage rm; public AudioSource tick; public bool tickPlaying = false; // Start is called before the first frame update void Start() { startTime = Time.time+ gameTime; } // Update is called once per frame void Update() { float t = startTime - Time.time; string minutes = ((int)t / 60).ToString(); string seconds = (t % 60).ToString("f2"); timerText.text = minutes + ":" + seconds; if (t <= 0 && !gm.finalBattle) { rm.enabled = true; vp.Play(); gm.EndGame(); //ph.damage(); } if(t< 9f && !gm.finalBattle && !tickPlaying ) { tickPlaying = true; tick.Play(); } if (t <= 0 && gm.finalBattle) { gm.WinGame(); } if (!finalBattle & gm.finalBattle) { startTime = Time.time + finalFightTime; finalBattle = true; timerText.color = Color.red; } } }
using System; using System.Collections.Generic; namespace MyDotNetCoreProject { public class Program { public unsafe static void Main(string[] args) { //可简写为delegate*<int, void>,但delegate* unmanaged<int, void>不可简写 delegate* managed<int, void> action = &Foo; delegate*<int, void>[] actions = new delegate*<int, void>[1]; actions[0] = action; for (int i = 0; i < actions.Length; i++) { actions[i](5); } IntPtr intPtr = (IntPtr)action; action = (delegate*<int, void>)intPtr; action(10); Console.WriteLine("===================="); int v1 = 0b01111111_11111111_11111111_11111111; Console.WriteLine(v1); Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(v1))); Console.WriteLine(v1 << 1); Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(v1 << 1))); Console.WriteLine("===================="); v1 = -1; //0b11111111_11111111_11111111_11111111; Console.WriteLine(v1); Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(v1))); Console.WriteLine(v1 << 1); Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(v1 << 1))); Console.WriteLine("===================="); v1 = -1073741825; //0b10111111_11111111_11111111_11111111; Console.WriteLine(v1); Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(v1))); Console.WriteLine(v1 << 1); Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(v1 << 1))); Console.Read(); } private static void Foo(int value) { Console.WriteLine(value); } } }
// <copyright file="TestReflection.cs" company="Google Inc."> // Copyright (C) 2019 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Collections; using System.IO; using Google; // Class used to test method invocation. public class Greeter { private string name; public Greeter(string name) { this.name = name; } public static string GenericHello() { return "Hello"; } public static string GenericHelloWithCustomerName(string customerName) { return String.Format("{0} {1}", GenericHello(), customerName); } public static string GenericHelloWithCustomerName(int customerId) { return String.Format("{0} customer #{1}", GenericHello(), customerId); } public static string GenericHelloWithPronoun(string pronoun = "There") { return String.Format("{0} {1}", GenericHello(), pronoun); } public static string GenericHelloWithCustomerNameAndPronoun(string customerName, string pronoun = "There") { return String.Format("{0} {1}", GenericHelloWithPronoun(pronoun: pronoun), customerName); } private string MyNameIs() { return String.Format(", my name is {0}", name); } public string Hello() { return Greeter.GenericHello() + MyNameIs(); } public string HelloWithCustomerName(string customerName) { return Greeter.GenericHelloWithCustomerName(customerName) + MyNameIs(); } public string HelloWithCustomerNameAndPronoun(string customerName, string pronoun = "There") { return Greeter.GenericHelloWithCustomerNameAndPronoun(customerName, pronoun: pronoun) + MyNameIs(); } } [UnityEditor.InitializeOnLoad] public class TestReflection { /// <summary> /// Test all reflection methods. /// </summary> static TestReflection() { // Disable stack traces for more condensed logs. UnityEngine.Application.stackTraceLogType = UnityEngine.StackTraceLogType.None; // Run tests. var failures = new List<string>(); foreach (var test in new Func<bool>[] { TestFindClassWithAssemblyName, TestFindClassWithoutAssemblyName, TestInvokeStaticMethodWithNoArgs, TestInvokeStaticMethodWithStringArg, TestInvokeStaticMethodWithIntArg, TestInvokeStaticMethodWithNamedArgDefault, TestInvokeStaticMethodWithNamedArg, TestInvokeStaticMethodWithArgAndNamedArgDefault, TestInvokeStaticMethodWithArgAndNamedArg, TestInvokeInstanceMethodWithNoArgs, TestInvokeInstanceMethodWithNamedArgDefault, TestInvokeInstanceMethodWithNamedArg }) { var testName = test.Method.Name; Exception exception = null; bool succeeded = false; try { UnityEngine.Debug.Log(String.Format("Running test {0}", testName)); succeeded = test(); } catch (Exception ex) { exception = ex; succeeded = false; } if (succeeded) { UnityEngine.Debug.Log(String.Format("{0}: PASSED", testName)); } else { UnityEngine.Debug.LogError(String.Format("{0} ({1}): FAILED", testName, exception)); failures.Add(testName); } } if (failures.Count > 0) { UnityEngine.Debug.Log("Test failed"); foreach (var testName in failures) { UnityEngine.Debug.Log(String.Format("{0}: FAILED", testName)); } UnityEditor.EditorApplication.Exit(1); } UnityEngine.Debug.Log("Test passed"); UnityEditor.EditorApplication.Exit(0); } // Test searching for a class when specifying the assembly name. static bool TestFindClassWithAssemblyName() { var expectedType = typeof(UnityEditor.EditorApplication); var foundType = VersionHandler.FindClass("UnityEditor", "UnityEditor.EditorApplication"); if (expectedType != foundType) { UnityEngine.Debug.LogError(String.Format("Unexpected type {0} vs {1}", foundType, expectedType)); return false; } return true; } // Test searching for a class without specifying the assembly name. static bool TestFindClassWithoutAssemblyName() { var expectedType = typeof(UnityEditor.EditorApplication); var foundType = VersionHandler.FindClass(null, "UnityEditor.EditorApplication"); if (expectedType != foundType) { UnityEngine.Debug.LogError(String.Format("Unexpected type {0} vs {1}", foundType, expectedType)); return false; } return true; } static bool CheckValue(string expected, string value) { if (value != expected) { UnityEngine.Debug.LogError(String.Format("Unexpected value {0} vs {1}", value, expected)); return false; } return true; } // Invoke a static method with no arguments. static bool TestInvokeStaticMethodWithNoArgs() { return CheckValue("Hello", (string)VersionHandler.InvokeStaticMethod(typeof(Greeter), "GenericHello", null, null)); } // Invoke an overloaded static method with a string arg. static bool TestInvokeStaticMethodWithStringArg() { return CheckValue("Hello Jane", (string)VersionHandler.InvokeStaticMethod(typeof(Greeter), "GenericHelloWithCustomerName", new object[] { "Jane" }, null)); } // Invoke an overloaded static method with an int arg. static bool TestInvokeStaticMethodWithIntArg() { return CheckValue("Hello customer #1337", (string)VersionHandler.InvokeStaticMethod(typeof(Greeter), "GenericHelloWithCustomerName", new object[] { 1337 }, null)); } // Invoke a static method with a default value of a named arg. static bool TestInvokeStaticMethodWithNamedArgDefault() { return CheckValue("Hello There", (string)VersionHandler.InvokeStaticMethod(typeof(Greeter), "GenericHelloWithPronoun", null, null)); } // Invoke a static method with a named arg. static bool TestInvokeStaticMethodWithNamedArg() { return CheckValue("Hello Miss", (string)VersionHandler.InvokeStaticMethod( typeof(Greeter), "GenericHelloWithPronoun", null, new Dictionary<string, object> { { "pronoun", "Miss" } })); } // Invoke a static method with a positional and default value for a named arg. static bool TestInvokeStaticMethodWithArgAndNamedArgDefault() { return CheckValue("Hello There Bob", (string)VersionHandler.InvokeStaticMethod( typeof(Greeter), "GenericHelloWithCustomerNameAndPronoun", new object[] { "Bob" }, null)); } // Invoke a static method with a positional and named arg. static bool TestInvokeStaticMethodWithArgAndNamedArg() { return CheckValue("Hello Mrs Smith", (string)VersionHandler.InvokeStaticMethod( typeof(Greeter), "GenericHelloWithCustomerNameAndPronoun", new object[] { "Smith" }, new Dictionary<string, object> { { "pronoun", "Mrs" } } )); } // Invoke an instance method with no args. static bool TestInvokeInstanceMethodWithNoArgs() { return CheckValue("Hello, my name is Sam", (string)VersionHandler.InvokeInstanceMethod(new Greeter("Sam"), "Hello", null, null)); } // Invoke an instance method with an default value for a named argument. static bool TestInvokeInstanceMethodWithNamedArgDefault() { return CheckValue("Hello There Helen, my name is Sam", (string)VersionHandler.InvokeInstanceMethod( new Greeter("Sam"), "HelloWithCustomerNameAndPronoun", new object[] { "Helen" }, null)); } // Invoke an instance method with a named argument. static bool TestInvokeInstanceMethodWithNamedArg() { return CheckValue("Hello Mrs Smith, my name is Sam", (string)VersionHandler.InvokeInstanceMethod( new Greeter("Sam"), "HelloWithCustomerNameAndPronoun", new object[] { "Smith" }, new Dictionary<string, object> { { "pronoun", "Mrs" } })); } }
using System.Net.Sockets; namespace NetRpc.Common.Secruity { public interface IKeyStore<T> { byte[] Get(T client); } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Budget.Users.Domain.WriteModel.Events; using Budget.Users.Domain.WriteModel.Repositories; using Budget.Users.MongoDbAdapters.Entities; using MongoDB.Driver; using MongoDB.Bson.Serialization; namespace Budget.Users.MongoDbAdapters.Domain.WriteModel.Repositories { public class MongoDbWriteModelUserRepository : IWriteModelUserRepository { internal const string collectionName = "Users"; internal MongoDbWriteModelUserRepository( IMongoDatabase database, Budget.Users.Domain.WriteModel.Factories.WriteModelUserFactory userFactory ) { Users = database.GetCollection<User>(collectionName); UserFactory = userFactory; RegisterClassMap<Budget.Users.Domain.WriteModel.Events.UserSubscribed>(); RegisterClassMap<Budget.Users.Domain.WriteModel.Events.PasswordChanged>(); } private void RegisterClassMap<T>() { Mutex mutex = new Mutex(false, typeof(T).FullName); mutex.WaitOne(); if (! BsonClassMap.IsClassMapRegistered(typeof(T))) BsonClassMap.RegisterClassMap<T>(); mutex.ReleaseMutex(); mutex.Dispose(); } private IMongoCollection<User> Users { get; } private Budget.Users.Domain.WriteModel.Factories.WriteModelUserFactory UserFactory { get; } public async Task<Budget.Users.Domain.WriteModel.User> Get(Guid id) { Budget.Users.Domain.WriteModel.User user = null; var search = await Users.FindAsync<User>(u => u.Id == id); var dbUser = search.FirstOrDefault(); if (dbUser != null) { user = UserFactory.Load(id, dbUser.Changes); } return user; } public async Task Save(Budget.Users.Domain.WriteModel.User user) { var dbUser = new User(user); if (IsNewUser(user)) await Users.InsertOneAsync(dbUser); else await Users.FindOneAndReplaceAsync<User>(u => u.Id == dbUser.Id, dbUser); } private bool IsNewUser(Budget.Users.Domain.WriteModel.User user) { var newSubscriptions = user.NewChanges.Where( @event => @event.GetType() == typeof(UserSubscribed) ); return newSubscriptions.Any(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Emgu.Util; using System.Runtime.InteropServices; namespace Emgu.CV.OpenCL { public class OclInfo { private IntPtr _ptr; internal OclInfo(IntPtr ptr) { _ptr = ptr; } public String PlatformName { get { IntPtr ptr = OclInvoke.oclInfoGetPlatformName(_ptr); return Marshal.PtrToStringAnsi(ptr); } } public String[] DeviceNames { get { String[] names = new String[OclInvoke.oclInfoGetDeviceCount(_ptr)]; for (int i = 0; i < names.Length; i++) { names[i] = Marshal.PtrToStringAnsi(OclInvoke.oclInfoGetDeviceName(_ptr, i)); } return names; } } } public static partial class OclInvoke { [DllImport(CvInvoke.EXTERN_LIBRARY, CallingConvention = CvInvoke.CvCallingConvention)] internal static extern IntPtr oclInfoGetPlatformName(IntPtr oclInfo); [DllImport(CvInvoke.EXTERN_LIBRARY, CallingConvention = CvInvoke.CvCallingConvention)] internal static extern int oclInfoGetDeviceCount(IntPtr oclInfo); [DllImport(CvInvoke.EXTERN_LIBRARY, CallingConvention = CvInvoke.CvCallingConvention)] internal static extern IntPtr oclInfoGetDeviceName(IntPtr oclInfo, int index); } }
using System.Collections.Generic; namespace PubActiveSubService.Internals.Interfaces { public interface IChannelPersisitance { string[] LookupSubscriberUrlsByChanneNamel(string channelName, params string[] internalUrls); void PostChannelName(string channelName); IEnumerable<Models.Channel> ListChannels(Models.Search search); void Subscribe(Models.Subscribe subscribe, string defaultInternalUrl); void Unsubscribe(Models.SubscriberBinding subscriberBinding); } }
using Pandora.NetStdLibrary.Base.Interfaces; using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Pandora.NetStandard.Model.Entities { [Table("SubjectAssingments", Schema = "School")] public class SubjectAssingment : TrackedEntity { public virtual int Id { get; set; } public virtual bool Deleted { get; set; } [Required] public virtual DateTime Date { get; set; } public virtual int SubjectId { get; set; } public virtual Subject Subject { get; set; } public virtual int ClassId { get; set; } public virtual Class Class { get; set; } public virtual int? ClassRoomId { get; set; } public virtual ClassRoom ClassRoom { get; set; } public virtual int? TeacherId { get; set; } public virtual Teacher Teacher { get; set; } } }
using System.Collections.Generic; using System.Linq; using Apocryph.Ipfs.Fake; using Apocryph.Ipfs.MerkleTree; using Xunit; namespace Apocryph.Ipfs.Test { public class MerkleTreeTests { class Example { public int Number { get; set; } public override bool Equals(object? obj) => obj is Example other && Number == other.Number; public override int GetHashCode() => Number.GetHashCode(); public override string ToString() => $"Example({Number})"; } [Theory] [InlineData(3, 4)] public async void Enumerate_ReturnsItems_InOrder(int groups, int elements) { var resolver = new FakeHashResolver(); var rootHashes = new Hash<IMerkleTree<Example>>[groups]; var expected = new List<Example>(); for (var i = 0; i < groups; i++) { var groupHashes = new Hash<IMerkleTree<Example>>[elements]; for (var j = 0; j < elements; j++) { var example = new Example { Number = i * elements + j }; expected.Add(example); var leaf = new MerkleTreeLeaf<Example>(example); groupHashes[j] = await resolver.StoreAsync<IMerkleTree<Example>>(leaf, default); } var group = new MerkleTreeNode<Example>(groupHashes); rootHashes[i] = await resolver.StoreAsync<IMerkleTree<Example>>(group, default); } var root = new MerkleTreeNode<Example>(rootHashes); var result = await root.EnumerateItems(resolver).ToArrayAsync(); Assert.Equal(expected.ToArray(), result); } [Theory] [InlineData(8, 2)] [InlineData(15, 2)] [InlineData(5, 3)] [InlineData(7, 3)] public async void Builder_ReturnsItems_InOrder(int elements, int maxChildrenCount) { var resolver = new FakeHashResolver(); var expected = Enumerable.Range(0, elements).Select(x => new Example { Number = x }).ToArray(); var root = await MerkleTreeBuilder.CreateRootFromValues(resolver, expected, maxChildrenCount); var result = await root.EnumerateItems(resolver).ToArrayAsync(); Assert.Equal(expected, result); } } }
namespace CityBreaks.Models { public class Booking { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public int NumberOfGuests { get; set; } public decimal DayRate { get; set; } } }
using Verse; namespace HumanResources { public class CompShootingArea : ThingComp { private bool pending = true; private CellRect _rangeArea; public CellRect RangeArea { get { if (pending) { _rangeArea = ShootingRangeUtility.RangeArea(parent.def, parent.Position, parent.Rotation); pending = false; } return _rangeArea; } } } }
//****************************************** // Copyright (C) 2014-2015 Charles Nurse * // * // Licensed under MIT License * // (see included LICENSE) * // * // ***************************************** using System.Collections.Generic; using FamilyTreeProject.Common; // ReSharper disable once CheckNamespace namespace FamilyTreeProject { /// <summary> /// Fact is a class that represents a generic Fact (or attribute in GEDCOM) /// </summary> public class Fact : OwnedEntity { public Fact() : this(string.Empty) { } public Fact(string treeId) : base(treeId) { Citations = new List<Citation>(); } /// <summary> /// Gets or sets the Citations for the Fact /// </summary> public IList<Citation> Citations { get; set; } /// <summary> /// The date of the fact (if the fact is an event) /// </summary> public string Date { get; set; } /// <summary> /// The type of the Fact /// </summary> public FactType FactType { get; set; } /// <summary> /// The place for the fact /// </summary> public string Place { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using TgBotPillar.Bot.Input.Configuration; using TgBotPillar.Core.Interfaces; using TgBotPillar.Core.Model; using TgBotPillar.Core.Scheme; namespace TgBotPillar.Bot.Input { public class InputHandlersManager : IInputHandlersManager { private readonly Task _initialization; private readonly ILogger<InputHandlersManager> _logger; private readonly IStorageService _storageService; private IReadOnlyDictionary<string, IInputHandler> _handlers; public InputHandlersManager( ILogger<InputHandlersManager> logger, IOptions<BotInputHandlersConfiguration> options, IStorageService storageService) { _logger = logger; _storageService = storageService; _initialization = Initialize(options.Value); } private async Task Initialize(BotInputHandlersConfiguration config) { _logger.LogInformation("Initialization started"); _handlers = new[] { typeof(InputHandlersManager).Assembly.Location } .Concat(config.Assemblies) .SelectMany(assemblyName => Assembly.LoadFrom(assemblyName).GetTypes()) .Where(type => typeof(IInputHandler).IsAssignableFrom(type) && !type.IsInterface && !type.IsAbstract) .Select(type => (IInputHandler)Activator.CreateInstance(type)) .ToDictionary(handler => handler?.Name, _ => _); await Task.WhenAll(config.UserFlags .Where(_ => _.Value.Count > 0) .Select(_ => _storageService.UpdateUserFlags(_.Key, _.Value))); _logger.LogInformation("Initialization completed"); } public async Task<string> Handle(Core.Scheme.Input input, IDialogContext context, string text = null) { await _initialization; string newState = null; if (input.Handler != null) { newState = await Handle(input.Handler, context, text); } if (input.Options.Count > 0 && !string.IsNullOrEmpty(text)) { newState = input.Options.FirstOrDefault(option => option.Text == text)?.Transition; } return string.IsNullOrEmpty(newState) ? input.DefaultTransition : newState.ToLowerInvariant(); } public async Task<string> Handle(Handler handler, IDialogContext context, string text = null) { await _initialization; if (!_handlers.ContainsKey(handler.Name)) throw new ArgumentException($"Handler `{handler.Name}` not found."); var handlerResult = await _handlers[handler.Name] .Handle(_storageService, handler.Parameters, context, text); return handler.Switch.TryGetValue(handlerResult.ToLowerInvariant(), out var switchState) ? switchState : handlerResult; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System; using YamlDotNet.Core; using YamlDotNet.Serialization; namespace Microsoft.Atlas.CommandLine.Serialization { public class ByteArrayConverter : IYamlTypeConverter { public bool Accepts(Type type) { return type == typeof(byte[]); } public object ReadYaml(IParser parser, Type type) { var scalar = (YamlDotNet.Core.Events.Scalar)parser.Current; var bytes = Convert.FromBase64String(scalar.Value); parser.MoveNext(); return bytes; } public void WriteYaml(IEmitter emitter, object value, Type type) { var bytes = (byte[])value; emitter.Emit(new YamlDotNet.Core.Events.Scalar( null, "tag:yaml.org,2002:binary", Convert.ToBase64String(bytes), ScalarStyle.Plain, false, false)); } } }
using static pmcenter.Conf; namespace pmcenter { public static partial class Methods { public static void BanUser(long uid) { if (!IsBanned(uid)) { var banned = new BanObj { UID = uid }; Vars.CurrentConf.Banned.Add(banned); } } } }
using System; #if !NET4 using System.Threading.Tasks; #endif using MyMapper.Extensions; namespace MyMapper.Converters { /// <summary> /// EntityConverter : Converts an entity to another entity /// </summary> /// <typeparam name="TSource">The source entity</typeparam> /// <typeparam name="TDestination">The destination entity</typeparam> /// <exception cref="ArgumentNullException"></exception> public class EntityConverter<TSource, TDestination> : ITypeConverter<TSource, TDestination> #if !NET4 , ITypeConverterAsync<TSource, TDestination> #endif where TSource : class where TDestination : class, new() { public TDestination Convert(TSource source, TDestination destination = null) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return destination == null ? source.AsDictionary(typeof(TSource)).ToObject<TDestination>() : source.AsDictionary(typeof(TSource)).ToObject(destination); } #if !NET4 public async Task<TDestination> ConvertAsync(TSource source, TDestination destination = null) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return await Task.Run(() => this.Convert(source, destination)); } #endif } }
// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Denis Krjuchkov // Created: 2009.05.13 using System; using System.Linq.Expressions; using System.Runtime.Serialization; using Xtensive.Linq.SerializableExpressions.Internals; namespace Xtensive.Linq.SerializableExpressions { /// <summary> /// A serializable representation of <see cref="MemberInitExpression"/> /// </summary> [Serializable] public sealed class SerializableMemberInitExpression : SerializableExpression { /// <summary> /// <see cref="MemberInitExpression.NewExpression"/> /// </summary> public SerializableNewExpression NewExpression; /// <summary> /// <see cref="MemberInitExpression.Bindings"/> /// </summary> public SerializableMemberBinding[] Bindings; public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("NewExpression", NewExpression); info.AddArray("Bindings", Bindings); } public SerializableMemberInitExpression() { } public SerializableMemberInitExpression(SerializationInfo info, StreamingContext context) : base(info, context) { NewExpression = (SerializableNewExpression) info.GetValue("NewExpression", typeof (SerializableNewExpression)); Bindings = info.GetArrayFromSerializableForm<SerializableMemberBinding>("Bindings"); } } }
using System; using System.Collections.Generic; using System.Text; using RawRabbit.Configuration; namespace MessageBus.Rabbit { public class RabbitMqOptions : RawRabbitConfiguration { } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Bitrix24RestApiClient.Api.Crm.Invoices.OldInvoices.Models { /// <summary> /// Если клиент - компания, могут быть указаны ключи (все значения типа string): /// COMPANY - Название компании; /// COMPANY_ADR - Адрес; /// CONTACT_PERSON - Контактное лицо; /// EMAIL - E-mail; /// PHONE - Телефон; /// INN - ИНН; /// KPP - КПП; /// /// Если клиент - контакт: /// /// FIO - Ф.И.О.; /// ADDRESS - Адрес; /// EMAIL - E-mail; /// PHONE - Телефон; /// </summary> public class InvoiceProperty { /// <summary> /// COMPANY - Название компании; /// </summary> [JsonProperty(InvoicePropertyFields.CompanyName)] public string CompanyName { get; set; } /// <summary> /// COMPANY_ADR - Адрес; /// </summary> [JsonProperty(InvoicePropertyFields.CompanyAddress)] public string CompanyAddress { get; set; } /// <summary> /// CONTACT_PERSON - Контактное лицо; /// </summary> [JsonProperty(InvoicePropertyFields.ContactPerson)] public string ContactPerson { get; set; } /// <summary> /// EMAIL - E-mail; /// </summary> [JsonProperty(InvoicePropertyFields.Email)] public string Email { get; set; } /// <summary> /// PHONE - Телефон; /// </summary> [JsonProperty(InvoicePropertyFields.Phone)] public string Phone { get; set; } /// <summary> /// Факс /// </summary> [JsonProperty(InvoicePropertyFields.Fax)] public string Fax { get; set; } /// <summary> /// Почтовый индекс /// </summary> [JsonProperty(InvoicePropertyFields.Zip)] public string Zip { get; set; } /// <summary> /// Город /// </summary> [JsonProperty(InvoicePropertyFields.City)] public string City { get; set; } /// <summary> /// Location /// </summary> [JsonProperty(InvoicePropertyFields.Location)] public string Location { get; set; } /// <summary> /// INN - ИНН; /// </summary> [JsonProperty(InvoicePropertyFields.Inn)] public string Inn { get; set; } /// <summary> /// KPP - КПП; /// </summary> [JsonProperty(InvoicePropertyFields.Kpp)] public string Kpp { get; set; } /// <summary> /// FIO - Ф.И.О.; /// </summary> [JsonProperty(InvoicePropertyFields.Fio)] public string Fio { get; set; } /// <summary> /// ADDRESS - Адрес; /// </summary> [JsonProperty(InvoicePropertyFields.Address)] public string Address { get; set; } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace MiniMiner { class PantallaDeBienvenida { private SpriteFont fuente; private GestorDePantallas gestor; private byte[,] fondo = { {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, {1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1} }; private byte anchoFondo = 20; private byte altoFondo = 16; private short margenXFondo = 200; private byte margenYFondo = 100; private byte anchoCasillaFondo = 32; private byte altoCasillaFondo = 32; private Texture2D pared; private Texture2D suelo; public PantallaDeBienvenida(GestorDePantallas gestor) { this.gestor = gestor; } public void CargarContenidos(ContentManager Content) { fuente = Content.Load<SpriteFont>("PressStart2P"); pared = Content.Load<Texture2D>("paredNivel1"); suelo = Content.Load<Texture2D>("sueloNivel1"); } public void Actualizar(GameTime gameTime) { if (Keyboard.GetState().IsKeyDown(Keys.D1)) { gestor.modoActual = GestorDePantallas.MODO.JUEGO; } if (Keyboard.GetState().IsKeyDown(Keys.C)) { gestor.modoActual = GestorDePantallas.MODO.CREDITOS; } if (Keyboard.GetState().IsKeyDown(Keys.S)) { gestor.Terminar(); } } public void Dibujar(GameTime gameTime, SpriteBatch spritebatch) { for (int fila = 0; fila < altoFondo; fila++) // Fondo for (int col = 0; col < anchoFondo; col++) { if (fondo[fila, col] == 1) spritebatch.Draw(pared, new Rectangle( margenXFondo + col * anchoCasillaFondo, margenYFondo + fila * altoCasillaFondo, anchoCasillaFondo, altoCasillaFondo), Color.White); else if (fondo[fila, col] == 2) spritebatch.Draw(suelo, new Rectangle( margenXFondo + col * anchoCasillaFondo, margenYFondo + fila * altoCasillaFondo, anchoCasillaFondo, altoCasillaFondo), Color.White); } spritebatch.DrawString(fuente, "1. Jugar", new Vector2(400, 100), Color.White); spritebatch.DrawString(fuente, "C. Creditos", new Vector2(400, 150), Color.White); spritebatch.DrawString(fuente, "S. Salir", new Vector2(400, 200), Color.White); } } }
using EDAutomate.Utilities; using OpenQA.Selenium; using Xunit; namespace EDAutomate.UnitTests { public class MiningSearchService_Tests : WebDriverTestsBase { [Theory] [InlineData(Constants.MiningBenitoiteButtonXPath)] [InlineData(Constants.MiningVoidOpalButtonXPath)] [InlineData(Constants.MiningLtdButtonXPath)] public void MiningSearchWebElementShouldBeFoundByXPathSelector_Tests(string selector) { ChromeDriver.Url = Constants.MiningSearchUrl; Assert.True(ChromeDriver.FindElement(By.XPath(selector)).Displayed); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Xml.Linq; using NDesk.Options; using SongList; using Utility; namespace AutoLoad { static class Program { static void Main(string[] args) { // Arguments bool doTextures = false; bool forceReload = false; bool forceMeta = false; OptionSet p = new OptionSet() { { "p|path=", "The {PATH} of KFC directory.", v => Util.SetKfcPath(v) }, { "t|texture", "Do the texture replacement (which takes a long time).", v => doTextures = v != null }, { "f|force-reload", "Force reload all songs.", v => forceReload = v != null }, { "fm|force-meta", "Force reload meta DB and all songs.", v => forceMeta = v != null } }; List<string> extra; try { extra = p.Parse(args); } catch (OptionException e) { Console.Write("AutoLoad: "); Console.WriteLine(e.Message); return; } // Welcome message Util.ConsoleWrite(@" _ __ _ _________ __ | |/ / | ||__ __\ \ / / | ' / ___| |__ | | __\ \ / /____ __ | < / __| '_ \| |/ _ \ \/ / _ \ \/ / | . \\__ \ | | | | (_) \ / (_) > < March 2018. Alpha version |_|\_\___/_| |_|_|\___/ \/ \___/_/\_\ Author: NTUMG "); // Check if kfc dll exists. if (!File.Exists(Util.kfcPath + "soundvoltex.dll")) { Console.WriteLine("soundvoltex.dll not found! Please choose a valid KFC path."); Console.ReadKey(); return; } // Check if folders exist. if (!Directory.Exists(Util.kfcPath + "KshSongs\\")) Directory.CreateDirectory(Util.kfcPath + "KshSongs\\"); if (!Directory.Exists(Util.kfcPath + "data\\others\\vox\\")) Directory.CreateDirectory(Util.kfcPath + "data\\others\\vox\\"); Util.ClearCache(); // DB backup (for later restore) Util.DbBackup(); if (forceMeta) File.Delete(Util.kfcPath + "data\\others\\meta_usedId.xml"); SongList.SongList songList = new SongList.SongList(); Util.ConsoleWrite("Loading from KshSongs..."); try { if (!forceReload) songList.LoadFromDB(); songList.LoadFromKshSongs(); } catch (Exception e) { Util.ConsoleWrite("*** Exception encountered while loading from KshSongs. ***"); Util.ConsoleWrite(e.Message); Util.DbRestore(); Console.ReadKey(); return; } Util.ConsoleWrite("Saving song..."); try { // The KFC data could be corrupted here even if the exceptions are caught, // so the music_db and metaDb should be removed before abort. songList.Save(); } catch (Exception e) { Util.ConsoleWrite("*** Fatal: Exception encountered while saving ***"); Util.ConsoleWrite(e.Message); File.Delete(Util.kfcPath + "\\data\\others\\music_db.xml"); File.Delete(Util.kfcPath + "\\data\\others\\meta_usedId.xml"); Util.ConsoleWrite(@"*** Please force reload with '--f' ***"); Console.ReadKey(); return; } Util.ClearCache(); if (doTextures) { Util.ConsoleWrite("Saving texture... (This should took a while)"); try { // Chart data should be fine regardless of the result of SaveTexture. // No need to erase the DBs in exceptions. songList.SaveTexture(); } catch (Exception e) { Util.ConsoleWrite("*** Exception encountered while saving texture ***"); Util.ConsoleWrite(e.Message); Util.ConsoleWrite("The charts will still be saved. (Without the custom jackets)"); } } Util.ConsoleWrite(@" ///////////////////////////////////////////////// /// /// /// Loading Done! Press any key to proceed... /// /// /// ///////////////////////////////////////////////// "); Console.ReadKey(); } } }
namespace Phoenix.Infrastructure.Native { using System.Collections.Generic; public class DevModeComparer : IEqualityComparer<DevMode> { public bool Equals(DevMode x, DevMode y) { return x.PelsWidth == y.PelsWidth && x.PelsHeight == y.PelsHeight && x.BitsPerPel == y.BitsPerPel; } public int GetHashCode(DevMode obj) { return obj.PelsWidth.GetHashCode()*obj.PelsHeight.GetHashCode()*obj.BitsPerPel.GetHashCode(); } } }
// Cristian Pop - https://boxophobic.com/ using UnityEngine; namespace Boxophobic.StyledGUI { public class StyledRangeOptions : PropertyAttribute { public string display; public float min; public float max; public string[] options; public StyledRangeOptions(string display, float min, float max, string[] options) { this.display = display; this.min = min; this.max = max; this.options = options; } } }
using System.Net.Mime; using System.Threading.Tasks; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using NHSD.BuyingCatalogue.Capabilities.API.ViewModels; using NHSD.BuyingCatalogue.Capabilities.Contracts; namespace NHSD.BuyingCatalogue.Capabilities.API { /// <summary> /// Provides a set of endpoints for the information related to the capability entity. /// </summary> [Route("api/v1/[controller]")] [ApiController] [Produces(MediaTypeNames.Application.Json)] public sealed class CapabilitiesController : ControllerBase { private readonly IMediator mediator; /// <summary> /// Initializes a new instance of the <see cref="CapabilitiesController"/> class. /// </summary> /// <param name="mediator">The mediator instance.</param> public CapabilitiesController(IMediator mediator) => this.mediator = mediator; /// <summary> /// Gets a list of capabilities. /// </summary> /// <returns>A task representing an operation to retrieve a list of capabilities.</returns> [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task<ActionResult<ListCapabilitiesResult>> ListAsync() => Ok( new ListCapabilitiesResult(await mediator.Send(new ListCapabilitiesQuery()))); } }
using System.Collections.Generic; namespace RePKG.Core.Texture { public interface ITexImage { IList<ITexMipmap> Mipmaps { get; } ITexMipmap FirstMipmap { get; } }; }
using FluentValidation.Validators; using PhoneNumbers; namespace BlueBoard.Module.Common.Validation { public class PhoneValidator : PropertyValidator { private readonly PhoneNumberUtil util; public PhoneValidator() : base("{PropertyName} must be valid phone number.") { this.util = PhoneNumberUtil.GetInstance(); } protected override bool IsValid(PropertyValidatorContext context) { var property = context.PropertyValue as string; try { var number = this.util.Parse(property, null); return this.util.IsValidNumber(number); } catch (NumberParseException e) { return false; } } } }
using MZXRM.PSS.Connector.Database; using MZXRM.PSS.Data; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace MZXRM.PSS.DataManager { public class UserDataManager { public static User CalculateUser(User user) { return user; } #region " AuthenticateUser Function " public static User AuthenticateUser(string LoginName, string Password) { //USER OBJECT TO BE SAVED WHEN USER IS AUTHENTICATED User objUser = new User(); using (var dbc = DataFactory.GetConnection()) { IDbCommand command = CommandBuilder.CommandAuthenticateUser(dbc, LoginName, Password); if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); } var result = command.ExecuteReader(); //ROLE RELATED INFORMATION TO BE SAVED IN "USER" OBJECTED DECLARE ABOVE Role role = null; //TEAM RELATED INFORMATION TO BE SAVED IN "USER" OBJECTED DECLARE ABOVE Team team = null; objUser.Roles = new List<Role>(); objUser.Teams = new List<Team>(); while (result.Read()) { if (String.IsNullOrEmpty(result["Message"].ToString())) { objUser.Id = Guid.Parse(result["UserId"].ToString()); objUser.Status = (UserStatus)Enum.Parse(typeof(UserStatus), result["UserStatus"].ToString()); objUser.Name = Convert.ToString(result["UserName"]); objUser.Login = Convert.ToString(result["LoginName"]); objUser.Designation = Convert.ToString(result["Designation"]); objUser.Email = Convert.ToString(result["Email"]); objUser.Mobile = Convert.ToString(result["Mobile"]); objUser.Office = Convert.ToString(result["Office"]); objUser.Home = Convert.ToString(result["Home"]); objUser.Address = Convert.ToString(result["Address"]); objUser.ProfileImage = Convert.ToString(result["Picture"]); /* Role population goes here */ if (objUser.Roles.Count(x => x.Id == Guid.Parse(result["RoleId"].ToString())) <= 0) { role = new Role(); role.Id = Guid.Parse(result["RoleId"].ToString()); role.Name = result["RoleName"].ToString(); objUser.Roles.Add(role); role = null; } /* Team population goes here */ if (objUser.Teams.Count(x => x.Id == Guid.Parse(result["TeamId"].ToString())) <= 0) { team = new Team(); team.Id = Guid.Parse(result["TeamId"].ToString()); team.Name = result["TeamName"].ToString(); objUser.Teams.Add(team); team = null; } } else { objUser.Remarks = result["Message"].ToString(); } } } return objUser; } #endregion #region DB Get all functions public static DataTable GetAllUsers() { try { using (var dbc = DataFactory.GetConnection()) { IDbCommand command = CommandBuilder.CommandGetAll(dbc, "sp_GetAllUser"); if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); } IDataReader datareader = command.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(datareader); return dt; } } catch (Exception ex) { throw new Exception("Error! Get all User from DataBase", ex); } } public static DataTable GetAllRoles() { try { using (var dbc = DataFactory.GetConnection()) { IDbCommand command = CommandBuilder.CommandGetAll(dbc, "sp_GetAllUserRole"); if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); } IDataReader datareader = command.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(datareader); return dt; } } catch (Exception ex) { throw new Exception("Error! Get all User from DataBase", ex); } } public static DataTable GetAllTeams() { try { using (var dbc = DataFactory.GetConnection()) { IDbCommand command = CommandBuilder.CommandGetAll(dbc, "sp_GetAllUserTeam"); if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); } IDataReader datareader = command.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(datareader); return dt; } } catch (Exception ex) { throw new Exception("Error! Get all Team from DataBase", ex); } } #endregion } }
namespace VanillaStub.Helpers.Services.StreamLibrary.src { public unsafe class MurmurHash2Unsafe { private const uint m = 0x5bd1e995; private const int r = 24; public uint Hash(byte* data, int length) { if (length == 0) return 0; uint h = 0xc58f1a7b ^ (uint) length; int remainingBytes = length & 3; // mod 4 int numberOfLoops = length >> 2; // div 4 uint* realData = (uint*) data; while (numberOfLoops != 0) { uint k = *realData; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; numberOfLoops--; realData++; } switch (remainingBytes) { case 3: h ^= (ushort) *realData; h ^= (uint) *((byte*) realData + 2) << 16; h *= m; break; case 2: h ^= (ushort) *realData; h *= m; break; case 1: h ^= *((byte*) realData); h *= m; break; } // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >> 13; h *= m; h ^= h >> 15; return h; } } }
using System; namespace FpML.V5r3.Confirmation { public static class StepHelper { public static Step Create(DateTime stepDate, decimal stepValue) { var step = new Step {stepDate = stepDate, stepValue = stepValue}; return step; } public static Step Create(string id, DateTime stepDate, decimal stepValue) { var step = new Step {id = id, stepDate = stepDate, stepValue = stepValue}; return step; } } }
using Apizr.Mediation.Cruding.Base; using MediatR; namespace Apizr.Mediation.Cruding { public class DeleteCommand<T, TKey, TResponse> : DeleteCommandBase<T, TKey, TResponse> { public DeleteCommand(TKey key) : base(key) { } } public class DeleteCommand<T, TKey> : DeleteCommandBase<T, TKey, Unit> { public DeleteCommand(TKey key) : base(key) { } } public class DeleteCommand<T> : DeleteCommandBase<T> { public DeleteCommand(int key) : base(key) { } } }
namespace WordsManagement.AudioReactiveComponents { public interface ISoundUpdated { void SoundUpdate(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy_AI_Turtle : MonoBehaviour { public int attackDamage; Animator anim; Transform enemy; GameObject player; EnemyHealth enemyHealth; bool playerInRange; float distToPlayer, minDistPlayer, multiplyBy; private UnityEngine.AI.NavMeshAgent navAgent; GameObject castle; public GameObject particle; private void Awake () { enemy = this.transform; navAgent = this.GetComponent<UnityEngine.AI.NavMeshAgent>(); player = GameObject.FindGameObjectWithTag ("Player"); castle = GameObject.FindGameObjectWithTag ("Castle"); enemyHealth = GetComponent<EnemyHealth>(); anim = GetComponent <Animator>(); playerInRange = false; minDistPlayer = 30f; } void Update () { IsPlayerClose(); if(enemyHealth.currentHealth > 0) { navAgent.SetDestination (player.transform.position); } else { navAgent.enabled = false; } // If the timer exceeds the time between attacks, the player is in range and this enemy is alive... if(playerInRange && enemyHealth.currentHealth > 0 ) { attackDamage = 15; Shoot(); if(distToPlayer <= 7) GameManager.Instance.PlayerDamageTaken(attackDamage); } else { particle.SetActive(false); } } void IsPlayerClose() { distToPlayer = Vector3.Distance(enemy.transform.position,player.transform.position); if(distToPlayer <= minDistPlayer) { playerInRange = true; } else { playerInRange = false; } } void Shoot() { particle.SetActive(true); } void OnDestroy() { GameManager.Instance.AddScrapToCount(3); GameManager.Instance.OnAIDeath(); } }
/* Original source Farseer Physics Engine: * Copyright (c) 2014 Ian Qvist, http://farseerphysics.codeplex.com * Microsoft Permissive License (Ms-PL) v1.1 */ using System.Collections.Generic; using Microsoft.Xna.Framework; namespace tainicom.Aether.Physics2D.Fluids { public class FluidParticle { public Vector2 Position; public Vector2 PreviousPosition; public Vector2 Velocity; public Vector2 Acceleration; internal FluidParticle(Vector2 position) { Neighbours = new List<FluidParticle>(); IsActive = true; MoveTo(position); Damping = 0.0f; Mass = 1.0f; } public bool IsActive { get; set; } public List<FluidParticle> Neighbours { get; private set; } // For gameplay purposes public float Density { get; internal set; } public float Pressure { get; internal set; } // Other properties public int Index { get; internal set; } // Physics properties public float Damping { get; set; } public float Mass { get; set; } public void MoveTo(Vector2 p) { Position = p; PreviousPosition = p; Velocity = Vector2.Zero; Acceleration = Vector2.Zero; } public void ApplyForce(ref Vector2 force) { Acceleration += force * Mass; } public void ApplyImpulse(ref Vector2 impulse) { Velocity += impulse; } public void Update(float deltaTime) { Velocity += Acceleration * deltaTime; Vector2 delta = (1.0f - Damping) * Velocity * deltaTime; PreviousPosition = Position; Position += delta; Acceleration = Vector2.Zero; } public void UpdateVelocity(float deltaTime) { Velocity = (Position - PreviousPosition) / deltaTime; } } }
// Copyright (c) Daniel Crenna & Contributors. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace ExternalTestAssembly { public static class AnonymousTypeFactory { public static object Foo() { return new {Foo = "Foo"}; } public static object Bar() { return new {Bar = "Bar"}; } } }
// // Copyright (c) 2002-2019 Mirko Matytschak // (www.netdataobjects.de) // // Author: Mirko Matytschak // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.IO; using System.Windows.Forms; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.CommandBars; using System.Text.RegularExpressions; namespace NETDataObjects.NDOVSPackage { /// <summary> /// Zusammenfassung für AddAccessorCs. /// </summary> internal class AddAccessorCs { TextDocument textDoc; Document document; public AddAccessorCs(TextDocument textDoc, Document document) { this.document = document; this.textDoc = textDoc; } public void DoIt() { bool genChangeEvent = false; try { string result; int textLine = textDoc.Selection.TopLine; if (textLine != textDoc.Selection.BottomLine) return; textDoc.Selection.SelectLine(); string original = textDoc.Selection.Text; textDoc.Selection.LineUp(false, 1); textDoc.Selection.SelectLine(); string attrtext = textDoc.Selection.Text; textDoc.Selection.CharRight(false, 1); textDoc.Selection.LineDown(false, 1); int i = 0; string bl = string.Empty; while (char.IsWhiteSpace(original[i])) bl += original[i++]; string selLine = original.Trim(); Regex regex = new Regex(@"(private[\s]*|)([^\s]+(\s*<[^\s]+|))\s+([^\s^;^=]+)\s*(=|;)"); Match match = regex.Match(selLine); if (!match.Success) { MessageBox.Show("Please select a private member variable declaration"); return; } string typeStr = match.Groups[2].Value; string bigname; string name = match.Groups[4].Value; if (name.StartsWith("_")) bigname = name.Substring(1); else if (name.StartsWith("m_")) bigname = name.Substring(2); else bigname = name; bigname = bigname.Substring(0, 1).ToUpper() + bigname.Substring(1); string genericTypeStr = string.Empty; string genericArgumentType = string.Empty; string genericParameter = string.Empty; regex = new Regex(@"([^\s]+)\s*<([^>]+)>"); match = regex.Match(typeStr); if (match.Success) { genericTypeStr = match.Groups[1].Value; genericArgumentType = match.Groups[2].Value; genericParameter = "<" + genericArgumentType + '>'; } bool isContainer = (typeStr == "IList" || typeStr == "ArrayList"); if (genericTypeStr != string.Empty) { isContainer = isContainer || (genericTypeStr == "IList" || genericTypeStr == "List"); } bool isGenericList = genericTypeStr != string.Empty && isContainer; // bool isIList = (typeStr == "IList" || genericTypeStr == "IList"); if (isContainer) { attrtext = attrtext.Trim(); string elementTyp = null; if (!isGenericList) elementTyp = GetElementTyp(attrtext); else elementTyp = genericArgumentType; string relationName = GetRelationName(attrtext); if (elementTyp == null) { isContainer = false; } else { if (relationName == null) { int p = elementTyp.LastIndexOf("."); relationName = elementTyp.Substring(p + 1); } bool isComposite = (attrtext.IndexOf("RelationInfo.Composite") > -1); string parameter = elementTyp.Substring(0,1).ToLower(); result = string.Empty; if (isComposite) { result += bl + "public " + elementTyp + " New" + relationName + "()\n"; result += bl + "{\n"; result += bl + "\t" + elementTyp + " " + parameter + " = new " + elementTyp + "();\n"; result += bl + "\tthis." + name + ".Add(" + parameter + ");\n"; result += bl + "\t" + "return " + parameter + ";\n"; result += bl + "}\n"; } else { result += bl + "public void Add" + relationName + "(" + elementTyp + " " + parameter + ")\n"; result += bl + "{\n"; result += bl + "\tthis." + name + ".Add(" + parameter + ");\n"; result += bl + "}\n"; } result += bl + "public void Remove" + relationName + "(" + elementTyp + " " + parameter + ")\n"; result += bl + "{\n"; result += bl + "\tif (this." + name + ".Contains(" + parameter + "))\n"; result += bl + "\t\tthis." + name + ".Remove(" + parameter + ");\n"; result += bl + "}\n"; textDoc.Selection.Insert(result, (int)vsInsertFlags.vsInsertFlagsInsertAtStart); } } if (!isContainer) // isContainer may change in the if case, so we test it again { ConfigurationOptions options = new ConfigurationOptions(document.ProjectItem.ContainingProject); if (options.GenerateChangeEvents) { genChangeEvent = true; result = bl + "public event EventHandler " + bigname + "Changed;\n"; textDoc.Selection.Insert(result, (int)vsInsertFlags.vsInsertFlagsInsertAtStart); } } result = string.Empty; string ilistType = null; if (isGenericList) { ilistType = "IEnumerable" + genericParameter; } else ilistType = "IEnumerable"; if (isContainer) result += bl + "public " + ilistType + " " + bigname + '\n'; else result += bl + "public " + typeStr + " " + bigname + '\n'; result += bl + "{\n"; result += bl + "\tget { return this." + name + "; }\n"; if (genChangeEvent) // Set Accessor in mehreren Zeilen { result += bl + "\tset\n"; result += bl + "\t{\n"; if (isContainer) { if (!isGenericList) result += bl + "\t\tthis." + name + " = new ArrayList( (ICollection)value );\n"; else result += bl + "\t\tthis." + name + " = value.ToList();\n"; } else { result += bl + "\t\tthis." + name + " = value;\n"; } result += bl + "\t\tif (" + bigname + "Changed != null)\n"; result += bl + "\t\t\t" + bigname + "Changed(this, EventArgs.Empty);\n"; result += bl +"\t}\n"; } else // Accessor in einer Zeile { if (isContainer) if (!isGenericList) result += bl + "\tset { this." + name + " = new ArrayList( (ICollection)value ); }\n"; else result += bl + "\tset { this." + name + " = value.ToList(); }\n"; else result += bl + "\tset { this." + name + " = value; }\n"; } result += bl + "}\n"; TabProperty tp = TabProperties.Instance.CSharp; if (tp.UseSpaces) result = result.Replace("\t", tp.Indent); textDoc.Selection.Insert(result, (int)vsInsertFlags.vsInsertFlagsInsertAtStart); } catch (Exception e) { MessageBox.Show(e.Message, "Add Accessor Add-in"); } } private string GetElementTyp(string attrtext) { Regex regex = new Regex(@"\[\s*NDORelation\s*\(\s*typeof\s*\(\s*([^\s^\)]+)"); Match match = regex.Match(attrtext); if (match.Success) { return match.Groups[1].Value; } return null; } private string GetRelationName(string attrtext) { string result; Regex regex = new Regex(@"\[\s*NDORelation"); Match match = regex.Match(attrtext); if (!match.Success) return null; regex = new Regex(@"("")([^""]+)("")"); match = regex.Match(attrtext); if (match.Success) // wir haben einen Relationsnamen { result = match.Groups[2].Value; if (char.IsLower(result[0])) result = result.Substring(0, 1).ToUpper() + result.Substring(1); return result; } return null; } } }
using Autofac; using NSubstitute; using OpenTracker.Models.Markings; using OpenTracker.Models.UndoRedo.Markings; using Xunit; namespace OpenTracker.UnitTests.Models.Markings { public class MarkingTests { private readonly IChangeMarking.Factory _changeMarkingFactory = (_, _) => Substitute.For<IChangeMarking>(); private readonly Marking _sut; public MarkingTests() { _sut = new Marking(_changeMarkingFactory) { Mark = MarkType.Unknown }; } [Fact] public void Mark_ShouldRaisePropertyChanged() { Assert.PropertyChanged(_sut, nameof(IMarking.Mark), () => _sut.Mark = MarkType.HCLeft); } [Fact] public void Mark_ShouldReturnSetValue() { _sut.Mark = MarkType.HCLeft; Assert.Equal(MarkType.HCLeft, _sut.Mark); } [Fact] public void CreateChangeMarkingAction_ShouldReturnNewAction() { Assert.NotNull(_sut.CreateChangeMarkingAction(MarkType.Aga)); } [Fact] public void AutofacTest() { using var scope = ContainerConfig.Configure().BeginLifetimeScope(); var factory = scope.Resolve<IMarking.Factory>(); var sut = factory(); Assert.NotNull(sut as Marking); } } }
using DotJEM.Json.Validation.Rules; namespace DotJEM.Json.Validation.Results { public class RuleResult : Result { public override bool IsValid => Result.IsValid; public Rule Rule { get; } public Result Result { get; } public RuleResult(Rule rule, Result result) { Rule = rule; Result = result; } public override Result Optimize() { return new RuleResult(Rule, Result.Optimize()); } } /// <summary> /// Filler for simple usage of results. /// </summary> public class SimpleResult : Result { public override bool IsValid { get; } public string Explain { get; } public SimpleResult(bool value, string explain = null) { IsValid = value; Explain = explain ?? value.ToString(); } } }
using Gibe.Navigation.Umbraco.Filters; using Gibe.Navigation.Umbraco.NodeTypes; using Umbraco.Core; using Umbraco.Core.Composing; namespace Gibe.Navigation.Umbraco.Composers { public class GibeNavigationComposer : IUserComposer { public void Compose(Composition composition) { composition.Register<INavigationService, DefaultNavigationService>(); composition.Register<INodeTypeFactory, DefaultNodeTypeFactory>(); composition.Register<INavigationProvider, UmbracoNavigationProvider>(); composition.Register<IUmbracoNodeService, UmbracoNodeService>(); composition.Register<INavigationFilter, TemplateOrRedirectFilter>(); composition.Register<INodeType, SettingsNodeType>(); } } }
using Secure.SecurityDoors.Data.Enums; using System; namespace Secure.SecurityDoors.Logic.Models { /// <summary> /// DoorAction data transfer object. /// </summary> public class DoorActionDto { /// <summary> /// Identifier. /// </summary> public int Id { get; set; } /// <summary> /// DoorReader identifier. /// </summary> public int DoorReaderId { get; set; } /// <summary> /// Card identifier. /// </summary> public int CardId { get; set; } /// <summary> /// Status. /// </summary> public DoorActionStatusType Status { get; set; } /// <summary> /// Time stamp. /// </summary> public DateTime TimeStamp { get; set; } /// <summary> /// Card data transfer object. /// </summary> public CardDto Card { get; set; } /// <summary> /// DoorReader data transfer object. /// </summary> public DoorReaderDto DoorReader { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using NodaTime; using RulesDoer.Core.Expressions.FEEL.Eval; using RulesDoer.Core.Types; using RulesDoer.Core.Utils; namespace RulesDoer.Core.Runtime.Context { //TODO: move this to type namespace public class Variable : IComparable<Variable> { public DataTypeEnum ValueType { get; set; } public string InputName { get; set; } public decimal NumericVal { get; set; } public bool BoolVal { get; set; } public OffsetDateTime? DateTimeVal { get; set; } public ZonedDateTime? ZoneDateTimeVal { get; set; } public LocalDateTime? LocalDateTimeVal { get; set; } public LocalTime? LocalTimeVal { get; set; } public OffsetTime? TimeVal { get; set; } public LocalDate DateVal { get; set; } public Period DurationVal { get; set; } public string StringVal { get; set; } public object ObjectVal { get; set; } public List<Variable> ListVal { get; set; } public (Variable a, Variable b) TwoTuple { get; set; } public ContextInputs ContextInputs { get; set; } public DecisionTableResult DecisionTableResult { get; set; } public UserFunction UserFunction { get; set; } public Variable () { ValueType = DataTypeEnum.Null; } public Variable (decimal number) { NumericVal = number; ValueType = DataTypeEnum.Decimal; } public Variable (bool boolean) { BoolVal = boolean; ValueType = DataTypeEnum.Boolean; } public Variable (string str) { StringVal = str; ValueType = DataTypeEnum.String; } public Variable (OffsetDateTime dt) { DateTimeVal = dt; ValueType = DataTypeEnum.DateTime; } public Variable (LocalDateTime dt) { LocalDateTimeVal = dt; ValueType = DataTypeEnum.DateTime; } public Variable (ZonedDateTime dt) { ZoneDateTimeVal = dt; ValueType = DataTypeEnum.DateTime; } public Variable (LocalDate dt) { DateVal = dt; ValueType = DataTypeEnum.Date; } public Variable (LocalTime tm) { LocalTimeVal = tm; ValueType = DataTypeEnum.Time; } public Variable (OffsetTime tm) { TimeVal = tm; ValueType = DataTypeEnum.Time; } public Variable (Period period) { DurationVal = period; } public Variable (DataTypeEnum yrMnthDurationType, int months) { ValueType = yrMnthDurationType; NumericVal = months; } public Variable (DataTypeEnum timeType, ZonedDateTime inTime) { ValueType = timeType; ZoneDateTimeVal = inTime; } public Variable (List<Variable> lst) { ListVal = lst; ValueType = DataTypeEnum.List; } public Variable (Variable a, Variable b) { TwoTuple = (a, b); ValueType = DataTypeEnum.Tuple; } public Variable (ContextInputs context) { ContextInputs = context; ValueType = DataTypeEnum.Context; } public Variable (DecisionTableResult dtr) { DecisionTableResult = dtr; ValueType = DataTypeEnum.DecisionTableResult; } public Variable (UserFunction func) { UserFunction = func; ValueType = DataTypeEnum.Function; } static public Variable Years (int years, int months = 0) { return Months (years * 12 + months); } static public Variable Months (int months) { return new Variable (DataTypeEnum.YearMonthDuration, months); } static public Variable Time (ZonedDateTime tm) { return new Variable (DataTypeEnum.Time, tm); } static public Variable ListType (List<Variable> lVars, DataTypeEnum dType) { var vList = new Variable (lVars) { ValueType = dType }; return vList; } static public Variable DurationType (Period duration, DataTypeEnum dType) { var dur = new Variable (duration) { ValueType = dType }; return dur; } public int CompareTo (Variable variable) { switch (variable.ValueType) { case DataTypeEnum.Boolean: return BoolVal.CompareTo (variable.BoolVal); case DataTypeEnum.String: return string.CompareOrdinal (StringVal, variable.StringVal); case DataTypeEnum.DateTime: return DateAndTimeHelper.CompareDateTime (this, variable); case DataTypeEnum.Time: return DateAndTimeHelper.CompareTime (this, variable); case DataTypeEnum.Date: return DateAndTimeHelper.CompareDate (this, variable); case DataTypeEnum.Decimal: return NumericVal.CompareTo (variable.NumericVal); case DataTypeEnum.DayTimeDuration: case DataTypeEnum.YearMonthDuration: return DateAndTimeHelper.CompareDuration (this, variable); case DataTypeEnum.List: case DataTypeEnum.Context: case DataTypeEnum.Function: //TODO: comparer needs to support equal operator only. return 0; default: throw new FEELException ($"The following type {variable.ValueType} is not supported"); } } public override bool Equals (object obj) { var rightVar = obj as Variable; if (!this.IsListType () && rightVar.IsListType ()) { return false; } if (this.IsListType () && rightVar.IsListType ()) { return ListVal.SequenceEqual (rightVar.ListVal); } //TODO: need to add this as a method in override equals in ContextInputs if (ValueType == DataTypeEnum.Context && rightVar.ValueType == DataTypeEnum.Context) { var countMatch = ContextInputs.ContextDict.Keys.Count == rightVar.ContextInputs.ContextDict.Keys.Count; if (countMatch) { foreach (var item in ContextInputs.ContextDict.Keys) { ContextInputs.ContextDict.TryGetValue (item, out Variable inValVar); if (inValVar is null) { return false; } rightVar.ContextInputs.ContextDict.TryGetValue (item, out Variable compValVar); if (compValVar is null) { return false; } var match = inValVar.Equals (compValVar); if (!match) { return false; } } return true; } return false; } return CompareTo (rightVar) == 0; } public override int GetHashCode () { int hashCode = 0; switch (ValueType) { case DataTypeEnum.Boolean: hashCode = BoolVal.GetHashCode (); break; case DataTypeEnum.String: hashCode = StringVal.GetHashCode (); break; case DataTypeEnum.DateTime: hashCode = DateTimeVal.GetHashCode (); break; case DataTypeEnum.Time: hashCode = DateTimeVal.GetHashCode (); break; case DataTypeEnum.Date: hashCode = DateVal.GetHashCode (); break; case DataTypeEnum.Decimal: hashCode = NumericVal.GetHashCode (); break; case DataTypeEnum.YearMonthDuration: case DataTypeEnum.DayTimeDuration: hashCode = DurationVal.GetHashCode (); break; } return hashCode; } public static bool operator > (Variable operand1, Variable operand2) { //reason is ordinal comparison returne value greater than 1 return operand1.CompareTo (operand2) > 0; } public static bool operator < (Variable operand1, Variable operand2) { //reason is ordinal comparison returne value greater than 1 return operand1.CompareTo (operand2) < 0; } public static bool operator >= (Variable operand1, Variable operand2) { return operand1.CompareTo (operand2) >= 0; } public static bool operator <= (Variable operand1, Variable operand2) { return operand1.CompareTo (operand2) <= 0; } static public implicit operator Variable (decimal d) { return new Variable (d); } static public implicit operator Variable (bool b) { return new Variable (b); } static public implicit operator Variable (string s) { return new Variable (s); } static public implicit operator Variable (OffsetDateTime dt) { return new Variable (dt); } static public implicit operator Variable (LocalDateTime dt) { return new Variable (dt); } static public implicit operator Variable (ZonedDateTime dt) { return new Variable (dt); } static public implicit operator Variable (LocalDate dt) { return new Variable (dt); } static public implicit operator Variable (LocalTime tm) { return new Variable (tm); } static public implicit operator Variable (OffsetTime tm) { return new Variable (tm); } static public implicit operator Variable (Period ts) { return new Variable (ts); } static public implicit operator Variable (List<Variable> lst) { return new Variable (lst); } static public implicit operator Variable (ContextInputs context) { return new Variable (context); } static public implicit operator Variable (DecisionTableResult dtr) { return new Variable (dtr); } static public implicit operator Variable (UserFunction func) { return new Variable (func); } static public implicit operator bool (Variable ev) { if (ev.ValueType != DataTypeEnum.Boolean) throw new NotSupportedException ("Expected boolean value."); return ev.BoolVal; } static public implicit operator decimal (Variable ev) { if (ev.ValueType != DataTypeEnum.Decimal && ev.ValueType != DataTypeEnum.YearMonthDuration) throw new NotSupportedException ("Expected number value."); return ev.NumericVal; } static public implicit operator string (Variable ev) { if (ev.ValueType != DataTypeEnum.String) throw new NotSupportedException ("Expected string value."); return ev.StringVal; } static public implicit operator OffsetDateTime (Variable ev) { if (ev.ValueType != DataTypeEnum.DateTime && ev.ValueType != DataTypeEnum.Time) throw new NotSupportedException ("Expected Offset DateTime value."); return ev.DateTimeVal.Value; } static public implicit operator LocalDateTime (Variable ev) { if (ev.ValueType != DataTypeEnum.DateTime) throw new NotSupportedException ("Expected Local DateTime value."); return ev.LocalDateTimeVal.Value; } static public implicit operator ZonedDateTime (Variable ev) { if (ev.ValueType != DataTypeEnum.DateTime) throw new NotSupportedException ("Expected Zone Datetime value."); return ev.ZoneDateTimeVal.Value; } static public implicit operator Period (Variable ev) { if (!ev.IsDurationType ()) throw new NotSupportedException ("Expected Duration value."); return ev.DurationVal; } static public implicit operator LocalDate (Variable ev) { if (ev.ValueType != DataTypeEnum.Date) throw new NotSupportedException ("Expected Local Date value."); return ev.DateVal; } static public implicit operator LocalTime (Variable ev) { if (ev.ValueType != DataTypeEnum.Time) throw new NotSupportedException ("Expected Local Time value."); return ev.LocalTimeVal.Value; } static public implicit operator OffsetTime (Variable ev) { if (ev.ValueType != DataTypeEnum.Time) throw new NotSupportedException ("Expected Offset Time value."); return ev.TimeVal.Value; } static public implicit operator List<Variable> (Variable ev) { if (ev.ValueType != DataTypeEnum.List) throw new NotSupportedException ("Expected List value."); return ev.ListVal; } static public implicit operator ContextInputs (Variable ev) { if (ev.ValueType != DataTypeEnum.Context) throw new NotSupportedException ("Expected Context value."); return ev.ContextInputs; } static public implicit operator DecisionTableResult (Variable ev) { if (ev.ValueType != DataTypeEnum.DecisionTableResult) throw new NotSupportedException ("Expected Decision Table Result value."); return ev.DecisionTableResult; } static public implicit operator UserFunction (Variable ev) { if (ev.ValueType != DataTypeEnum.Function) throw new NotSupportedException ("Expected User Function value."); return ev.UserFunction; } public override string ToString () { switch (ValueType) { case DataTypeEnum.Boolean: return BoolVal.ToString (); case DataTypeEnum.String: return StringVal; case DataTypeEnum.DateTime: return DateAndTimeHelper.DateTimeString (this); case DataTypeEnum.Time: return DateAndTimeHelper.TimeString (this); case DataTypeEnum.Date: return DateAndTimeHelper.DateString (this); case DataTypeEnum.Decimal: return NumericVal.ToString (); case DataTypeEnum.DayTimeDuration: case DataTypeEnum.YearMonthDuration: return DateAndTimeHelper.DurationString (this); default: return "No string value"; } } } }
// ----------------------------------------------------------------- // <copyright file="MapExtensions.cs" company="2Dudes"> // Copyright (c) | Jose L. Nunez de Caceres et al. // https://linkedin.com/in/nunezdecaceres // // All Rights Reserved. // // Licensed under the MIT License. See LICENSE in the project root for license information. // </copyright> // ----------------------------------------------------------------- namespace Fibula.Mechanics.Contracts.Extensions { using System; using Fibula.Common.Contracts.Enumerations; using Fibula.Common.Contracts.Structs; using Fibula.Common.Utilities; using Fibula.Map.Contracts.Abstractions; using Fibula.Map.Contracts.Constants; /// <summary> /// Helper class for extension methods of the map. /// </summary> public static class MapExtensions { /// <summary> /// Checks if a throw between two map locations is valid. /// </summary> /// <param name="map">A reference to the map.</param> /// <param name="fromLocation">The first location.</param> /// <param name="toLocation">The second location.</param> /// <param name="checkLineOfSight">Optional. A value indicating whether to consider line of sight.</param> /// <returns>True if the throw is valid, false otherwise.</returns> public static bool CanThrowBetweenLocations(this IMap map, Location fromLocation, Location toLocation, bool checkLineOfSight = true) { map.ThrowIfNull(nameof(map)); if (fromLocation == toLocation) { return true; } if (fromLocation.Type != LocationType.Map || toLocation.Type != LocationType.Map) { return false; } // Cannot throw across the surface boundary (floor 7). if ((fromLocation.Z >= 8 && toLocation.Z <= 7) || (toLocation.Z >= 8 && fromLocation.Z <= 7)) { return false; } var deltaX = Math.Abs(fromLocation.X - toLocation.X); var deltaY = Math.Abs(fromLocation.Y - toLocation.Y); var deltaZ = Math.Abs(fromLocation.Z - toLocation.Z); // distance checks if (deltaX - deltaZ >= (MapConstants.DefaultWindowSizeX / 2) || deltaY - deltaZ >= (MapConstants.DefaultWindowSizeY / 2)) { return false; } return !checkLineOfSight || map.AreInLineOfSight(fromLocation, toLocation) || map.AreInLineOfSight(toLocation, fromLocation); } /// <summary> /// Checks if two map locations are line of sight. /// </summary> /// <param name="map">A reference to the map.</param> /// <param name="firstLocation">The first location.</param> /// <param name="secondLocation">The second location.</param> /// <returns>True if the second location is considered within the line of sight of the first location, false otherwise.</returns> public static bool AreInLineOfSight(this IMap map, Location firstLocation, Location secondLocation) { map.ThrowIfNull(nameof(map)); if (firstLocation == secondLocation) { return true; } if (firstLocation.Type != LocationType.Map || secondLocation.Type != LocationType.Map) { return false; } // Normalize so that the check always happens from 'high to low' floors. var origin = firstLocation.Z > secondLocation.Z ? secondLocation : firstLocation; var target = firstLocation.Z > secondLocation.Z ? firstLocation : secondLocation; // Define positive or negative steps, depending on where the target location is wrt the origin location. var stepX = (sbyte)(origin.X < target.X ? 1 : origin.X == target.X ? 0 : -1); var stepY = (sbyte)(origin.Y < target.Y ? 1 : origin.Y == target.Y ? 0 : -1); var a = target.Y - origin.Y; var b = origin.X - target.X; var c = -((a * target.X) + (b * target.Y)); while ((origin - target).MaxValueIn2D != 0) { var moveHorizontal = Math.Abs((a * (origin.X + stepX)) + (b * origin.Y) + c); var moveVertical = Math.Abs((a * origin.X) + (b * (origin.Y + stepY)) + c); var moveCross = Math.Abs((a * (origin.X + stepX)) + (b * (origin.Y + stepY)) + c); if (origin.Y != target.Y && (origin.X == target.X || moveHorizontal > moveVertical || moveHorizontal > moveCross)) { origin.Y += stepY; } if (origin.X != target.X && (origin.Y == target.Y || moveVertical > moveHorizontal || moveVertical > moveCross)) { origin.X += stepX; } if (map.GetTileAt(origin, out ITile tile) && tile.BlocksThrow) { return false; } } while (origin.Z != target.Z) { // now we need to perform a jump between floors to see if everything is clear (literally) if (map.GetTileAt(origin, out ITile tile) && tile.Ground != null) { return false; } origin.Z++; } return true; } } }
using System.Collections.Generic; using System.Threading.Tasks; using EasyAbp.AbpHelper.Gui.Solutions.Dtos; using JetBrains.Annotations; using Volo.Abp.Application.Dtos; using Volo.Abp.Application.Services; namespace EasyAbp.AbpHelper.Gui.Solutions { public interface ISolutionAppService : IApplicationService { Task<ListResultDto<SolutionDto>> GetListAsync(); Task<SolutionDto> UseAsync(SolutionDto input); Task DeleteAsync(SolutionDto input); Task<GetPackageDictionaryOutput> GetPackageDictionaryAsync(GetPackageDictionaryInput input); } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using ServerlessMicroservices.Models; using ServerlessMicroservices.Shared.Helpers; namespace ServerlessMicroservices.Shared.Services { public class ChangeNotifierService : IChangeNotifierService { public const string LOG_TAG = "ChangeNotifierService"; private ISettingService _settingService; private ILoggerService _loggerService; private IStorageService _storageService; public ChangeNotifierService(ISettingService setting, ILoggerService logger, IStorageService storage) { _settingService = setting; _loggerService = logger; _storageService = storage; } public async Task DriverChanged(DriverItem driver) { //TODO: React to `Driver` changes } public async Task TripCreated(TripItem trip, int activeTrips) { var error = ""; try { // Start a trip manager if (!_settingService.IsEnqueueToOrchestrators()) { var baseUrl = _settingService.GetStartTripManagerOrchestratorBaseUrl(); var key = _settingService.GetStartTripManagerOrchestratorApiKey(); if (string.IsNullOrEmpty(baseUrl) || string.IsNullOrEmpty(key)) throw new Exception("Trip manager orchestrator base URL and key must be both provided"); await Utilities.Post<dynamic, dynamic>(null, trip, $"{baseUrl}/tripmanagers?code={key}", new Dictionary<string, string>()); } else { await _storageService.Enqueue(trip); } // Send an event telemetry _loggerService.Log("Trip created", new Dictionary<string, string> { {"Code", trip.Code }, {"Passenger", $"{trip.Passenger.FirstName} {trip.Passenger.LastName}" }, {"Destination", $"{trip.Destination.Latitude} - {trip.Destination.Longitude}" }, {"Mode", $"{trip.Type}" } }); // Send a metric telemetry _loggerService.Log("Active trips", activeTrips); if (trip.Type == TripTypes.Demo) { var tripDemoState = new TripDemoState(); tripDemoState.Code = trip.Code; tripDemoState.Source = new TripLocation() { Latitude = trip.Source.Latitude, Longitude = trip.Source.Longitude }; tripDemoState.Destination = new TripLocation() { Latitude = trip.Destination.Latitude, Longitude = trip.Destination.Longitude }; if (!_settingService.IsEnqueueToOrchestrators()) { var baseUrl = _settingService.GetStartTripDemoOrchestratorBaseUrl(); var key = _settingService.GetStartTripDemoOrchestratorApiKey(); if (string.IsNullOrEmpty(baseUrl) || string.IsNullOrEmpty(key)) throw new Exception("Trip demo orchestrator base URL and key must be both provided"); await Utilities.Post<dynamic, dynamic>(null, tripDemoState, $"{baseUrl}/tripdemos?code={key}", new Dictionary<string, string>()); } else { await _storageService.Enqueue(tripDemoState); } } } catch (Exception ex) { error = $"Error while starting the trip manager: {ex.Message}"; throw new Exception(error); } finally { _loggerService.Log($"{LOG_TAG} - TripCreated - Error: {error}"); } } public async Task TripDeleted(TripItem trip) { var error = ""; try { try { // Terminate a trip manager var baseUrl = _settingService.GetTerminateTripManagerOrchestratorBaseUrl(); var key = _settingService.GetTerminateTripManagerOrchestratorApiKey(); if (string.IsNullOrEmpty(baseUrl) || string.IsNullOrEmpty(key)) throw new Exception("Trip manager orchestrator base URL and key must be both provided"); await Utilities.Post<dynamic, dynamic>(null, trip, $"{baseUrl}/tripmanagers/{trip.Code}/terminate?code={key}", new Dictionary<string, string>()); } catch (Exception) { // Report ...but do not re-throw as it is possible not to have a trip manager running //throw new Exception(error); } try { // Terminate a trip monitor var baseUrl = _settingService.GetTerminateTripMonitorOrchestratorBaseUrl(); var key = _settingService.GetTerminateTripMonitorOrchestratorApiKey(); if (string.IsNullOrEmpty(baseUrl) || string.IsNullOrEmpty(key)) throw new Exception("Trip monitor orchestrator base URL and key must be both provided"); await Utilities.Post<dynamic, dynamic>(null, trip, $"{baseUrl}/tripmonitors/{trip.Code}-M/terminate?code={key}", new Dictionary<string, string>()); } catch (Exception) { // Report ...but do not re-throw as it is possible not to have a trip monitor running //throw new Exception(error); } } catch (Exception ex) { error = ex.Message; // Report ...but do not re-throw as it is possible not to have trip manager or monitor running //throw new Exception(error); } finally { _loggerService.Log($"{LOG_TAG} - TripDeleted - Error: {error}"); } } public async Task PassengerChanged(PassengerItem trip) { //TODO: React to `Passenger` changes } } }
using System.Collections.Generic; using Bing.Datas.Sql.Builders.Core; namespace Bing.Datas.Sql.Builders { /// <summary> /// 联合操作访问器 /// </summary> public interface IUnionAccessor { /// <summary> /// 是否包含联合操作 /// </summary> bool IsUnion { get; } /// <summary> /// 联合操作项集合 /// </summary> List<BuilderItem> UnionItems { get; } } }
using UnityEngine; public class Racket : MonoBehaviour { private Rigidbody2D _racketRigid ; [SerializeField] private float speed = 10.0f; private Vector3 _startPos; private Vector2 _startVel; private float _startrot; public float getRacketAngularVelocity() { return _racketRigid.angularVelocity; } public float getRacketRotation() { return _racketRigid.rotation % 360; } private void Start() { _racketRigid = gameObject.GetComponent<Rigidbody2D>(); _startVel = _racketRigid.velocity; _startPos = _racketRigid.position; _startrot= _racketRigid.rotation; } public void Swing(float rot) { _racketRigid.AddForce(transform.right * (rot * speed), ForceMode2D.Impulse); } public void ResetPosRacket() { if (_racketRigid == null) return; _racketRigid.velocity = _startVel; _racketRigid.position = _startPos; _racketRigid.rotation = _startrot; } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UI_controller : MonoBehaviour { [SerializeField] CageView cageView; [SerializeField] Param param; public int boidCount = 100; public InputField inputBoidNumField; public Text inputBoidNumText; public InputField inputScaleField; public Text inputScaleText; // Start is called before the first frame update void Start() { cageView = cageView.GetComponent<CageView>(); inputBoidNumField = inputBoidNumField.GetComponent<InputField>(); inputBoidNumText = inputBoidNumText.GetComponent<Text>(); inputScaleField = inputScaleField.GetComponent<InputField>(); inputScaleText = inputScaleText.GetComponent<Text>(); } public void OnClick() { UpdateCondition(); } public void UpdateCondition() { //--- input # of Boids inputBoidNumText.text = inputBoidNumField.text; int n_input; Int32.TryParse(inputBoidNumText.text, out n_input); if (n_input >= 0) { this.boidCount = n_input; } //--- input scale inputScaleText.text = inputScaleField.text; float new_scale = float.Parse(inputScaleText.text); if (new_scale > 0.0f) { param.wallScale = new_scale; cageView.UpdateScale(); } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; namespace Paint { public class Settings { private static Settings _instance; private Settings() { } public static Settings GetInstance() { if (_instance == null) _instance = new Settings(); return _instance; } private Color color = Color.Black; private float thickness = 5; private DashStyle style = DashStyle.Solid; private Color borderColor = Color.Gray; private float borderThickness = 3; private DashStyle borderStyle = DashStyle.Dash; private int borderOffset = 20; private Color anchorColor = Color.CadetBlue; private int anchorSize = 16; public Color Color { get { return color; } set { color = value; } } public float Thickness { get { return thickness; } set { thickness = value; } } public DashStyle Style { get { return style; } set { style = value; } } public Color BorderColor { get { return borderColor; } set { borderColor = value; } } public float BorderThickness { get { return borderThickness; } set { borderThickness = value; } } public DashStyle BorderStyle { get { return borderStyle; } set { borderStyle = value; } } public int BorderOffset { get { return borderOffset; } set { borderOffset = value * 2; } } public Color AnchorColor { get { return anchorColor; } set { anchorColor = value; } } public int AnchorSize { get { return anchorSize; } set { anchorSize = value * 2; } } /* * It is preferred to have the following values be even numbers. * Enforcing this on the user would be great! */ } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Diagnostics.HealthChecks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Builder { public static class HealthChecksApplicationBuilderExtensions { /// <summary> /// Enable usage of the basic liveness check that returns 200 http status code. /// Default registered health check is self. /// </summary> /// <param name="builder"></param> /// <param name="healthCheckPath"></param> /// <param name="healthCheckOptions"></param> /// <returns></returns> [Obsolete("Use " + nameof(MapLivenessHealthCheck))] public static IApplicationBuilder UseLivenessHealthCheck( this IApplicationBuilder builder, string healthCheckPath = "/liveness", HealthCheckOptions? healthCheckOptions = default) { if (healthCheckOptions == default) { // Exclude all checks and return a 200-Ok. Default registered health check is self. healthCheckOptions = new HealthCheckOptions { Predicate = (p) => false }; } builder.UseHealthChecks(healthCheckPath, healthCheckOptions); return builder; } /// <summary> /// Map Healtheck Liveleness route. /// Enable usage of the basic liveness check that returns 200 http status code. /// Default registered health check is self. /// </summary> /// <param name="builder"></param> /// <param name="healthCheckPath"></param> /// <param name="healthCheckOptions"></param> /// <returns></returns> public static IEndpointRouteBuilder MapLivenessHealthCheck( this IEndpointRouteBuilder builder, string healthCheckPath = "/liveness", HealthCheckOptions? healthCheckOptions = null) { var options = healthCheckOptions ?? new HealthCheckOptions { Predicate = (p) => false }; builder.MapHealthChecks(healthCheckPath, options); return builder; } /// <summary> /// Use Healthcheck which returns a report of all registered healthchecks. /// </summary> /// <param name="builder"></param> /// <param name="healthCheckPath"></param> /// <param name="healthCheckOptions"></param> /// <returns></returns> [Obsolete("Use " + nameof(MapHealthyHealthCheck))] public static IApplicationBuilder UseHealthyHealthCheck( this IApplicationBuilder builder, string healthCheckPath = "/healthy", HealthCheckOptions? healthCheckOptions = default) { if (healthCheckOptions == default) { healthCheckOptions = new HealthCheckOptions { ResponseWriter = WriteResponse }; } builder.UseHealthChecks(healthCheckPath, healthCheckOptions); return builder; } /// <summary> /// Use Healthcheck which returns a report of all registered healthchecks. /// </summary> /// <param name="builder"></param> /// <param name="healthCheckPath"></param> /// <param name="healthCheckOptions"></param> /// <returns></returns> public static IEndpointRouteBuilder MapHealthyHealthCheck( this IEndpointRouteBuilder builder, string healthCheckPath = "/healthy", HealthCheckOptions? healthCheckOptions = default) { var options = healthCheckOptions ?? new HealthCheckOptions { ResponseWriter = WriteResponse }; builder.MapHealthChecks(healthCheckPath, options); return builder; } /// <summary> /// Custom HealthCheck <see cref="HealthReport"/> renderer. /// </summary> /// <param name="httpContext"></param> /// <param name="result"></param> /// <returns></returns> public static Task WriteResponse( HttpContext httpContext, HealthReport result) { httpContext.Response.ContentType = "application/json"; var json = new JObject( new JProperty("status", result.Status.ToString()), new JProperty("results", new JObject(result.Entries.Select(pair => new JProperty(pair.Key, new JObject( new JProperty("status", pair.Value.Status.ToString()), new JProperty("description", pair.Value.Description), new JProperty("data", new JObject(pair.Value.Data.Select( p => new JProperty(p.Key, p.Value)))))))))); return httpContext.Response.WriteAsync( json.ToString(Formatting.Indented)); } } }
namespace Unosquare.Net { using System; /// <summary> /// Represents an HTTP Listener's exception. /// </summary> public class HttpListenerException : Exception { internal HttpListenerException(int errorCode, string message) : base(message) { ErrorCode = errorCode; } /// <summary> /// Gets the error code. /// </summary> public int ErrorCode { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IconifyXamarin.Typicons { public class TypiconsIcons : IIcon { public const char typcn_adjust_brightness = '\ue000'; public const char typcn_adjust_contrast = '\ue001'; public const char typcn_anchor_outline = '\ue002'; public const char typcn_anchor = '\ue003'; public const char typcn_archive = '\ue004'; public const char typcn_arrow_back_outline = '\ue005'; public const char typcn_arrow_back = '\ue006'; public const char typcn_arrow_down_outline = '\ue007'; public const char typcn_arrow_down_thick = '\ue008'; public const char typcn_arrow_down = '\ue009'; public const char typcn_arrow_forward_outline = '\ue00a'; public const char typcn_arrow_forward = '\ue00b'; public const char typcn_arrow_left_outline = '\ue00c'; public const char typcn_arrow_left_thick = '\ue00d'; public const char typcn_arrow_left = '\ue00e'; public const char typcn_arrow_loop_outline = '\ue00f'; public const char typcn_arrow_loop = '\ue010'; public const char typcn_arrow_maximise_outline = '\ue011'; public const char typcn_arrow_maximise = '\ue012'; public const char typcn_arrow_minimise_outline = '\ue013'; public const char typcn_arrow_minimise = '\ue014'; public const char typcn_arrow_move_outline = '\ue015'; public const char typcn_arrow_move = '\ue016'; public const char typcn_arrow_repeat_outline = '\ue017'; public const char typcn_arrow_repeat = '\ue018'; public const char typcn_arrow_right_outline = '\ue019'; public const char typcn_arrow_right_thick = '\ue01a'; public const char typcn_arrow_right = '\ue01b'; public const char typcn_arrow_shuffle = '\ue01c'; public const char typcn_arrow_sorted_down = '\ue01d'; public const char typcn_arrow_sorted_up = '\ue01e'; public const char typcn_arrow_sync_outline = '\ue01f'; public const char typcn_arrow_sync = '\ue020'; public const char typcn_arrow_unsorted = '\ue021'; public const char typcn_arrow_up_outline = '\ue022'; public const char typcn_arrow_up_thick = '\ue023'; public const char typcn_arrow_up = '\ue024'; public const char typcn_at = '\ue025'; public const char typcn_attachment_outline = '\ue026'; public const char typcn_attachment = '\ue027'; public const char typcn_backspace_outline = '\ue028'; public const char typcn_backspace = '\ue029'; public const char typcn_battery_charge = '\ue02a'; public const char typcn_battery_full = '\ue02b'; public const char typcn_battery_high = '\ue02c'; public const char typcn_battery_low = '\ue02d'; public const char typcn_battery_mid = '\ue02e'; public const char typcn_beaker = '\ue02f'; public const char typcn_beer = '\ue030'; public const char typcn_bell = '\ue031'; public const char typcn_book = '\ue032'; public const char typcn_bookmark = '\ue033'; public const char typcn_briefcase = '\ue034'; public const char typcn_brush = '\ue035'; public const char typcn_business_card = '\ue036'; public const char typcn_calculator = '\ue037'; public const char typcn_calendar_outline = '\ue038'; public const char typcn_calendar = '\ue039'; public const char typcn_camera_outline = '\ue03a'; public const char typcn_camera = '\ue03b'; public const char typcn_cancel_outline = '\ue03c'; public const char typcn_cancel = '\ue03d'; public const char typcn_chart_area_outline = '\ue03e'; public const char typcn_chart_area = '\ue03f'; public const char typcn_chart_bar_outline = '\ue040'; public const char typcn_chart_bar = '\ue041'; public const char typcn_chart_line_outline = '\ue042'; public const char typcn_chart_line = '\ue043'; public const char typcn_chart_pie_outline = '\ue044'; public const char typcn_chart_pie = '\ue045'; public const char typcn_chevron_left_outline = '\ue046'; public const char typcn_chevron_left = '\ue047'; public const char typcn_chevron_right_outline = '\ue048'; public const char typcn_chevron_right = '\ue049'; public const char typcn_clipboard = '\ue04a'; public const char typcn_cloud_storage = '\ue04b'; public const char typcn_cloud_storage_outline = '\ue054'; public const char typcn_code_outline = '\ue04c'; public const char typcn_code = '\ue04d'; public const char typcn_coffee = '\ue04e'; public const char typcn_cog_outline = '\ue04f'; public const char typcn_cog = '\ue050'; public const char typcn_compass = '\ue051'; public const char typcn_contacts = '\ue052'; public const char typcn_credit_card = '\ue053'; public const char typcn_css3 = '\ue055'; public const char typcn_database = '\ue056'; public const char typcn_delete_outline = '\ue057'; public const char typcn_delete = '\ue058'; public const char typcn_device_desktop = '\ue059'; public const char typcn_device_laptop = '\ue05a'; public const char typcn_device_phone = '\ue05b'; public const char typcn_device_tablet = '\ue05c'; public const char typcn_directions = '\ue05d'; public const char typcn_divide_outline = '\ue05e'; public const char typcn_divide = '\ue05f'; public const char typcn_document_add = '\ue060'; public const char typcn_document_delete = '\ue061'; public const char typcn_document_text = '\ue062'; public const char typcn_document = '\ue063'; public const char typcn_download_outline = '\ue064'; public const char typcn_download = '\ue065'; public const char typcn_dropbox = '\ue066'; public const char typcn_edit = '\ue067'; public const char typcn_eject_outline = '\ue068'; public const char typcn_eject = '\ue069'; public const char typcn_equals_outline = '\ue06a'; public const char typcn_equals = '\ue06b'; public const char typcn_export_outline = '\ue06c'; public const char typcn_export = '\ue06d'; public const char typcn_eye_outline = '\ue06e'; public const char typcn_eye = '\ue06f'; public const char typcn_feather = '\ue070'; public const char typcn_film = '\ue071'; public const char typcn_filter = '\ue072'; public const char typcn_flag_outline = '\ue073'; public const char typcn_flag = '\ue074'; public const char typcn_flash_outline = '\ue075'; public const char typcn_flash = '\ue076'; public const char typcn_flow_children = '\ue077'; public const char typcn_flow_merge = '\ue078'; public const char typcn_flow_parallel = '\ue079'; public const char typcn_flow_switch = '\ue07a'; public const char typcn_folder_add = '\ue07b'; public const char typcn_folder_delete = '\ue07c'; public const char typcn_folder_open = '\ue07d'; public const char typcn_folder = '\ue07e'; public const char typcn_gift = '\ue07f'; public const char typcn_globe_outline = '\ue080'; public const char typcn_globe = '\ue081'; public const char typcn_group_outline = '\ue082'; public const char typcn_group = '\ue083'; public const char typcn_headphones = '\ue084'; public const char typcn_heart_full_outline = '\ue085'; public const char typcn_heart_half_outline = '\ue086'; public const char typcn_heart_outline = '\ue087'; public const char typcn_heart = '\ue088'; public const char typcn_home_outline = '\ue089'; public const char typcn_home = '\ue08a'; public const char typcn_html5 = '\ue08b'; public const char typcn_image_outline = '\ue08c'; public const char typcn_image = '\ue08d'; public const char typcn_infinity_outline = '\ue08e'; public const char typcn_infinity = '\ue08f'; public const char typcn_info_large_outline = '\ue090'; public const char typcn_info_large = '\ue091'; public const char typcn_info_outline = '\ue092'; public const char typcn_info = '\ue093'; public const char typcn_input_checked_outline = '\ue094'; public const char typcn_input_checked = '\ue095'; public const char typcn_key_outline = '\ue096'; public const char typcn_key = '\ue097'; public const char typcn_keyboard = '\ue098'; public const char typcn_leaf = '\ue099'; public const char typcn_lightbulb = '\ue09a'; public const char typcn_link_outline = '\ue09b'; public const char typcn_link = '\ue09c'; public const char typcn_location_arrow_outline = '\ue09d'; public const char typcn_location_arrow = '\ue09e'; public const char typcn_location_outline = '\ue09f'; public const char typcn_location = '\ue0a0'; public const char typcn_lock_closed_outline = '\ue0a1'; public const char typcn_lock_closed = '\ue0a2'; public const char typcn_lock_open_outline = '\ue0a3'; public const char typcn_lock_open = '\ue0a4'; public const char typcn_mail = '\ue0a5'; public const char typcn_map = '\ue0a6'; public const char typcn_media_eject_outline = '\ue0a7'; public const char typcn_media_eject = '\ue0a8'; public const char typcn_media_fast_forward_outline = '\ue0a9'; public const char typcn_media_fast_forward = '\ue0aa'; public const char typcn_media_pause_outline = '\ue0ab'; public const char typcn_media_pause = '\ue0ac'; public const char typcn_media_play_outline = '\ue0ad'; public const char typcn_media_play_reverse_outline = '\ue0ae'; public const char typcn_media_play_reverse = '\ue0af'; public const char typcn_media_play = '\ue0b0'; public const char typcn_media_record_outline = '\ue0b1'; public const char typcn_media_record = '\ue0b2'; public const char typcn_media_rewind_outline = '\ue0b3'; public const char typcn_media_rewind = '\ue0b4'; public const char typcn_media_stop_outline = '\ue0b5'; public const char typcn_media_stop = '\ue0b6'; public const char typcn_message_typing = '\ue0b7'; public const char typcn_message = '\ue0b8'; public const char typcn_messages = '\ue0b9'; public const char typcn_microphone_outline = '\ue0ba'; public const char typcn_microphone = '\ue0bb'; public const char typcn_minus_outline = '\ue0bc'; public const char typcn_minus = '\ue0bd'; public const char typcn_mortar_board = '\ue0be'; public const char typcn_news = '\ue0bf'; public const char typcn_notes_outline = '\ue0c0'; public const char typcn_notes = '\ue0c1'; public const char typcn_pen = '\ue0c2'; public const char typcn_pencil = '\ue0c3'; public const char typcn_phone_outline = '\ue0c4'; public const char typcn_phone = '\ue0c5'; public const char typcn_pi_outline = '\ue0c6'; public const char typcn_pi = '\ue0c7'; public const char typcn_pin_outline = '\ue0c8'; public const char typcn_pin = '\ue0c9'; public const char typcn_pipette = '\ue0ca'; public const char typcn_plane_outline = '\ue0cb'; public const char typcn_plane = '\ue0cc'; public const char typcn_plug = '\ue0cd'; public const char typcn_plus_outline = '\ue0ce'; public const char typcn_plus = '\ue0cf'; public const char typcn_point_of_interest_outline = '\ue0d0'; public const char typcn_point_of_interest = '\ue0d1'; public const char typcn_power_outline = '\ue0d2'; public const char typcn_power = '\ue0d3'; public const char typcn_printer = '\ue0d4'; public const char typcn_puzzle_outline = '\ue0d5'; public const char typcn_puzzle = '\ue0d6'; public const char typcn_radar_outline = '\ue0d7'; public const char typcn_radar = '\ue0d8'; public const char typcn_refresh_outline = '\ue0d9'; public const char typcn_refresh = '\ue0da'; public const char typcn_rss_outline = '\ue0db'; public const char typcn_rss = '\ue0dc'; public const char typcn_scissors_outline = '\ue0dd'; public const char typcn_scissors = '\ue0de'; public const char typcn_shopping_bag = '\ue0df'; public const char typcn_shopping_cart = '\ue0e0'; public const char typcn_social_at_circular = '\ue0e1'; public const char typcn_social_dribbble_circular = '\ue0e2'; public const char typcn_social_dribbble = '\ue0e3'; public const char typcn_social_facebook_circular = '\ue0e4'; public const char typcn_social_facebook = '\ue0e5'; public const char typcn_social_flickr_circular = '\ue0e6'; public const char typcn_social_flickr = '\ue0e7'; public const char typcn_social_github_circular = '\ue0e8'; public const char typcn_social_github = '\ue0e9'; public const char typcn_social_google_plus_circular = '\ue0ea'; public const char typcn_social_google_plus = '\ue0eb'; public const char typcn_social_instagram_circular = '\ue0ec'; public const char typcn_social_instagram = '\ue0ed'; public const char typcn_social_last_fm_circular = '\ue0ee'; public const char typcn_social_last_fm = '\ue0ef'; public const char typcn_social_linkedin_circular = '\ue0f0'; public const char typcn_social_linkedin = '\ue0f1'; public const char typcn_social_pinterest_circular = '\ue0f2'; public const char typcn_social_pinterest = '\ue0f3'; public const char typcn_social_skype_outline = '\ue0f4'; public const char typcn_social_skype = '\ue0f5'; public const char typcn_social_tumbler_circular = '\ue0f6'; public const char typcn_social_tumbler = '\ue0f7'; public const char typcn_social_twitter_circular = '\ue0f8'; public const char typcn_social_twitter = '\ue0f9'; public const char typcn_social_vimeo_circular = '\ue0fa'; public const char typcn_social_vimeo = '\ue0fb'; public const char typcn_social_youtube_circular = '\ue0fc'; public const char typcn_social_youtube = '\ue0fd'; public const char typcn_sort_alphabetically_outline = '\ue0fe'; public const char typcn_sort_alphabetically = '\ue0ff'; public const char typcn_sort_numerically_outline = '\ue100'; public const char typcn_sort_numerically = '\ue101'; public const char typcn_spanner_outline = '\ue102'; public const char typcn_spanner = '\ue103'; public const char typcn_spiral = '\ue104'; public const char typcn_star_full_outline = '\ue105'; public const char typcn_star_half_outline = '\ue106'; public const char typcn_star_half = '\ue107'; public const char typcn_star_outline = '\ue108'; public const char typcn_star = '\ue109'; public const char typcn_starburst_outline = '\ue10a'; public const char typcn_starburst = '\ue10b'; public const char typcn_stopwatch = '\ue10c'; public const char typcn_support = '\ue10d'; public const char typcn_tabs_outline = '\ue10e'; public const char typcn_tag = '\ue10f'; public const char typcn_tags = '\ue110'; public const char typcn_th_large_outline = '\ue111'; public const char typcn_th_large = '\ue112'; public const char typcn_th_list_outline = '\ue113'; public const char typcn_th_list = '\ue114'; public const char typcn_th_menu_outline = '\ue115'; public const char typcn_th_menu = '\ue116'; public const char typcn_th_small_outline = '\ue117'; public const char typcn_th_small = '\ue118'; public const char typcn_thermometer = '\ue119'; public const char typcn_thumbs_down = '\ue11a'; public const char typcn_thumbs_ok = '\ue11b'; public const char typcn_thumbs_up = '\ue11c'; public const char typcn_tick_outline = '\ue11d'; public const char typcn_tick = '\ue11e'; public const char typcn_ticket = '\ue11f'; public const char typcn_time = '\ue120'; public const char typcn_times_outline = '\ue121'; public const char typcn_times = '\ue122'; public const char typcn_trash = '\ue123'; public const char typcn_tree = '\ue124'; public const char typcn_upload_outline = '\ue125'; public const char typcn_upload = '\ue126'; public const char typcn_user_add_outline = '\ue127'; public const char typcn_user_add = '\ue128'; public const char typcn_user_delete_outline = '\ue129'; public const char typcn_user_delete = '\ue12a'; public const char typcn_user_outline = '\ue12b'; public const char typcn_user = '\ue12c'; public const char typcn_vendor_android = '\ue12d'; public const char typcn_vendor_apple = '\ue12e'; public const char typcn_vendor_microsoft = '\ue12f'; public const char typcn_video_outline = '\ue130'; public const char typcn_video = '\ue131'; public const char typcn_volume_down = '\ue132'; public const char typcn_volume_mute = '\ue133'; public const char typcn_volume_up = '\ue134'; public const char typcn_volume = '\ue135'; public const char typcn_warning_outline = '\ue136'; public const char typcn_warning = '\ue137'; public const char typcn_watch = '\ue138'; public const char typcn_waves_outline = '\ue139'; public const char typcn_waves = '\ue13a'; public const char typcn_weather_cloudy = '\ue13b'; public const char typcn_weather_downpour = '\ue13c'; public const char typcn_weather_night = '\ue13d'; public const char typcn_weather_partly_sunny = '\ue13e'; public const char typcn_weather_shower = '\ue13f'; public const char typcn_weather_snow = '\ue140'; public const char typcn_weather_stormy = '\ue141'; public const char typcn_weather_sunny = '\ue142'; public const char typcn_weather_windy_cloudy = '\ue143'; public const char typcn_weather_windy = '\ue144'; public const char typcn_wi_fi_outline = '\ue145'; public const char typcn_wi_fi = '\ue146'; public const char typcn_wine = '\ue147'; public const char typcn_world_outline = '\ue148'; public const char typcn_world = '\ue149'; public const char typcn_zoom_in_outline = '\ue14a'; public const char typcn_zoom_in = '\ue14b'; public const char typcn_zoom_out_outline = '\ue14c'; public const char typcn_zoom_out = '\ue14d'; public const char typcn_zoom_outline = '\ue14e'; public const char typcn_zoom = '\ue14f'; public static readonly List<KeyValuePair<char, string>> Characters; public static IIcon[] Icons { get; } static TypiconsIcons() { Characters = IconReflectionUtils.GetIcons<TypiconsIcons>(); Icons = Characters.Select(p => new TypiconsIcons(p.Value, p.Key)).Cast<IIcon>().ToArray(); } private readonly string _key; public TypiconsIcons(string key, char @char) { _key = key; Character = @char; } public string Key => Characters.Single(p => p.Value == _key).Value.Replace("_", "-"); public char Character { get; } } }
using System; using UnityEngine; using DarkRoom.Core; namespace DarkRoom.Game { /// <summary> /// mvc中的view, 作为视图方面的总代理, 在具体继承中会持有各个comp的引用 /// 自身带有移动功能, 默认我们提供基于手柄的输入移动--类似于unreal的default pawn提供的基于FPS的移动 /// /// Pawn本身表示的是一个“能动”的概念,重点在于“能”。而Controller代表的是动到“哪里”的概念,重点在于“方向”。所以如果是一些 /// Pawn本身固有的能力逻辑,如前进后退、播放动画、碰撞检测之类的就完全可以在Pawn内实现 /// /// 如果一个逻辑只属于某一类Pawn,那么其实你放进Pawn内也挺好。而如果一个逻辑可以应用于多个Pawn, /// 那么放进Controller就可以组合应用了 /// </summary> [RequireComponent(typeof(CPawnPathFollowingComp))] [RequireComponent(typeof(CPawnMovementComp))] public class CPawnEntity : CUnitEntity { /// <summary> /// 谁在这时伤害了我 /// </summary> [HideInInspector, NonSerialized] public CController Instigator; //控制pawn移动的基础组件 protected CPawnMovementComp m_movement; //跟随路径行走的组件 protected CPawnPathFollowingComp m_follower; /// <summary> /// 我的视力扇形区域 /// 当然, 我们也会用来做其他的事情 /// 比如临时设置一个半径(这个半径可能是一个特殊值, 比如攻击范围) /// 来帮助确认某个人是否在扇形内. /// </summary> protected CCircularSector m_viewSight; /// <summary> /// 控制pawn行走的组件 /// </summary> /// <value>The mover.</value> public CPawnMovementComp Mover => m_movement; public CPawnPathFollowingComp Follower => m_follower; /// <summary> /// 我的视野范围是一个扇形 /// field of view /// </summary> public CCircularSector FOV => m_viewSight; /// <summary> /// 是否正在跟随路径行走, 实现 nav agent的接口 /// </summary> public bool IsFollowingPath => m_follower.Status == PathFollowingStatus.Moving; /// <summary> /// 是否完成路径行走 /// </summary> public bool FinishedFollowingPath => m_follower.FinishResult == FinishPathResultType.Success; protected override void RegisterAllComponents() { base.RegisterAllComponents(); //初始化CPawnMovementComp m_movement = GetComponent<CPawnMovementComp>(); m_follower = GetComponent<CPawnPathFollowingComp>(); } /// <summary> /// 我看向point, 会设置空间组件的方向 /// </summary> /// <param name="point"></param> public virtual void LookAt(Vector3 point) { m_spacial.LookAt(point); m_viewSight.LookAt(point); } /// <summary> /// 冻住pawn--停止声音,动画,物理,武器开火 /// </summary> public virtual void TurnOff() { //暂停移动. 其他的需求在子类覆盖编写 m_movement.TurnOff(); m_follower.PauseMove(); } /// <summary> /// 解冻单位 /// </summary> public virtual void TurnOn() { //暂停移动. 其他的需求在子类覆盖编写 m_movement.TurnOn(); m_follower.ResumeMove(); } /// <summary> /// 停止移动, 停止移动器和路径跟随器 /// </summary> public virtual void StopMovement() { m_movement.Stop(); m_follower.AbortMove(); } /// <summary> /// 让单位频死, 子类重写该方法保证多出来的组件的关闭 /// </summary> public virtual void MakeDying() { //死亡关闭移动 m_movement.TurnOff(); m_follower.AbortMove(); m_dying = true; } /// <summary> /// 使复活 /// </summary> public virtual void MakeRevival() { m_dying = false; m_dead = false; } /// <summary> /// 让单位死亡, 会在下一帧销毁, 子类重写该方法保证多出来的组件的关闭 /// </summary> public virtual void MakeDead() { MakeDying(); m_dead = true; } /// <summary> /// 让单位失效 /// </summary> public virtual void MakeInvalid() { m_invalid = true; } /// <summary> /// 让单位有效化 /// </summary> public virtual void MakeValid() { m_invalid = false; } /// <summary> /// 重启. 一般会被controller调用 /// </summary> public virtual void Restart() { } protected override void Update() { base.Update(); if (m_viewSight != null) { m_viewSight.SetCenter(LocalPosition); } } protected override void OnDestroy() { base.OnDestroy(); m_movement = null; } } }
using System; using System.Collections.Generic; using System.Linq; using Semver; namespace DotnetProjectDependenciesAnalyser.Domain { public class ProjectsDependencies { private readonly List<ProjectDependencies> _projectsDependencies; internal ProjectsDependencies() { _projectsDependencies = new List<ProjectDependencies>(); } public IReadOnlyCollection<ProjectDependencies> ProjectDependencies => _projectsDependencies; internal void AddProject( DotnetProject project) { if (_projectsDependencies.Any(x => x.Project == project)) throw new Exception("TODO"); _projectsDependencies.Add( new ProjectDependencies( project)); } internal void AddDependencyToProject( Dependency dependency, SemVersion version, DotnetProject project) { var projectDependencies = _projectsDependencies.SingleOrDefault( x => x.Project == project); if (projectDependencies == null) throw new Exception("TODO"); projectDependencies.AddDependency( dependency, version ); } } }
using System; using System.Data.Entity.Design.PluralizationServices; using System.Globalization; using System.Threading; namespace DynamicLinqPadPostgreSqlDriver.Extensions { internal static class StringExtensions { private static readonly PluralizationService _pluralizationService = PluralizationService.CreateService(CultureInfo.GetCultureInfo("en")); public static string Capitalize(this string s) { if (s == null) throw new ArgumentNullException(nameof(s)); var cultureInfo = Thread.CurrentThread.CurrentCulture; var textInfo = cultureInfo.TextInfo; return textInfo.ToTitleCase(s); } public static string Pluralize(this string s) { if (s == null) throw new ArgumentNullException(nameof(s)); return !_pluralizationService.IsPlural(s) ? _pluralizationService.Pluralize(s) : s; } public static string Singularize(this string s) { if (s == null) throw new ArgumentNullException(nameof(s)); return !_pluralizationService.IsSingular(s) ? _pluralizationService.Singularize(s) : s; } } }
/* * Your rights to use code governed by this license https://github.com/AlexWan/OsEngine/blob/master/LICENSE * Ваши права на использование кода регулируются данной лицензией http://o-s-a.net/doc/license_simple_engine.pdf */ using System.Windows; using System.ComponentModel; using OsEngine.Entity; using OsEngine.Language; using OsEngine.Market; namespace OsEngine.OsTrader.Gui { /// <summary> /// Логика взаимодействия для RobotUiLight.xaml /// </summary> public partial class RobotUiLight : Window { public RobotUiLight() { InitializeComponent(); ServerMaster.SetHostTable(HostPositionOnBoard, HostOrdersOnBoard); ServerMaster.GetServers(); _strategyKeeper = new OsTraderMaster(null, null, null, null, null, HostAllPosition, null, HostBotLogPrime, null, null, null, null, null, null, StartProgram.IsOsTrader); LabelOsa.Content = "V_" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; Closing += TesterUi_Closing; Local(); BotTabsPainter painter = new BotTabsPainter(_strategyKeeper, BotsHost); ServerMasterPainter painterServer = new ServerMasterPainter(HostServers, HostServerLog, CheckBoxServerAutoOpen); Closing += delegate (object sender, CancelEventArgs args) { painterServer.Dispose(); painter = null; }; } private void Local() { TabItemAllPos.Header = OsLocalization.Trader.Label20; TextBoxPositionBord.Header = OsLocalization.Trader.Label21; TextBoxPositionAllOrders.Header = OsLocalization.Trader.Label22; TabItemLogPrime.Header = OsLocalization.Trader.Label24; TabItemControl.Header = OsLocalization.Trader.Label37; CheckBoxServerAutoOpen.Content = OsLocalization.Market.Label20; } void TesterUi_Closing(object sender, System.ComponentModel.CancelEventArgs e) { AcceptDialogUi ui = new AcceptDialogUi(OsLocalization.Trader.Label48); ui.ShowDialog(); if (ui.UserAcceptActioin == false) { e.Cancel = true; } } private OsTraderMaster _strategyKeeper; } }
using System; using System.Security.Cryptography; namespace WORLD.Sharp { class XorShift { // XorShift128+ // see: http://xorshift.di.unimi.it/xorshift128plus.c ulong stage0 = 0x8a5cd789635d2dffUL; ulong stage1 = 0x121fd2155c472f96UL; public XorShift() { using (var seedRand = new RNGCryptoServiceProvider()) { var seed = new byte[8]; seedRand.GetNonZeroBytes(seed); stage0 = BitConverter.ToUInt64(seed, 0); seedRand.GetNonZeroBytes(seed); stage1 = BitConverter.ToUInt64(seed, 0); } } public double Next() { var s1 = stage0; var s0 = stage1; var result = s1 + s0; stage0 = s0; s1 ^= s1 << 23; stage1 = s1 ^ s0 ^ (s1 >> 18) ^ (s0 >> 5); return result / (double)ulong.MaxValue; } } }
using System; using System.Globalization; using BizHawk.Emulation.Common; namespace BizHawk.Client.Common { /// <summary> /// This class holds a converter for BizHawk SystemId (which is a simple <see cref="string"/> /// It allows you to convert it to a <see cref="CoreSystem"/> value and vice versa /// </summary> /// <remarks>I made it this way just in case one day we need it for WPF (DependencyProperty binding). Just uncomment :IValueConverter implementation /// I didn't implemented it because of mono compatibility /// </remarks> public sealed class BizHawkSystemIdToEnumConverter //:IValueConverter { /// <summary> /// Convert BizHawk SystemId <see cref="string"/> to <see cref="CoreSystem"/> value /// </summary> /// <param name="value"><see cref="string"/> you want to convert</param> /// <param name="targetType">The type of the binding target property</param> /// <param name="parameter">The converter parameter to use; null in our case</param> /// <param name="cultureInfo">The culture to use in the converter</param> /// <returns>A <see cref="CoreSystem"/> that is equivalent to BizHawk SystemId <see cref="string"/></returns> /// <exception cref="IndexOutOfRangeException">Thrown when SystemId hasn't been found</exception> public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo) { return (string) value switch { VSystemID.Raw.AppleII => CoreSystem.AppleII, VSystemID.Raw.A26 => CoreSystem.Atari2600, VSystemID.Raw.A78 => CoreSystem.Atari7800, VSystemID.Raw.Coleco => CoreSystem.ColecoVision, VSystemID.Raw.C64 => CoreSystem.Commodore64, VSystemID.Raw.GBL => CoreSystem.GameBoyLink, VSystemID.Raw.GB => CoreSystem.GameBoy, VSystemID.Raw.GBA => CoreSystem.GameBoyAdvance, VSystemID.Raw.GEN => CoreSystem.Genesis, VSystemID.Raw.INTV => CoreSystem.Intellivision, VSystemID.Raw.Libretro => CoreSystem.Libretro, VSystemID.Raw.Lynx => CoreSystem.Lynx, VSystemID.Raw.SMS => CoreSystem.MasterSystem, VSystemID.Raw.NDS => CoreSystem.NintendoDS, VSystemID.Raw.NES => CoreSystem.NES, VSystemID.Raw.N64 => CoreSystem.Nintendo64, VSystemID.Raw.NULL => CoreSystem.Null, VSystemID.Raw.PCE => CoreSystem.PCEngine, VSystemID.Raw.PCECD => CoreSystem.PCEngine, VSystemID.Raw.SGX => CoreSystem.PCEngine, VSystemID.Raw.PSX => CoreSystem.Playstation, VSystemID.Raw.SAT => CoreSystem.Saturn, VSystemID.Raw.SNES => CoreSystem.SNES, VSystemID.Raw.TI83 => CoreSystem.TI83, VSystemID.Raw.VEC => CoreSystem.Vectrex, VSystemID.Raw.WSWAN => CoreSystem.WonderSwan, VSystemID.Raw.ZXSpectrum => CoreSystem.ZXSpectrum, VSystemID.Raw.AmstradCPC => CoreSystem.AmstradCPC, VSystemID.Raw.GGL => CoreSystem.GGL, VSystemID.Raw.ChannelF => CoreSystem.ChannelF, VSystemID.Raw.MAME => CoreSystem.MAME, VSystemID.Raw.O2 => CoreSystem.Odyssey2, VSystemID.Raw.MSX => CoreSystem.MSX, VSystemID.Raw.VB => CoreSystem.VirtualBoy, VSystemID.Raw.NGP => CoreSystem.NeoGeoPocket, VSystemID.Raw.SGB => CoreSystem.SuperGameBoy, VSystemID.Raw.UZE => CoreSystem.UzeBox, VSystemID.Raw.PCFX => CoreSystem.PcFx, _ => throw new IndexOutOfRangeException($"{value} is missing in convert list") }; } /// <summary> /// Convert BizHawk SystemId <see cref="string"/> to <see cref="CoreSystem"/> value /// </summary> /// <param name="value"><see cref="string"/> you want to convert</param> /// <returns>A <see cref="CoreSystem"/> that is equivalent to BizHawk SystemId <see cref="string"/></returns> /// <exception cref="IndexOutOfRangeException">Thrown when SystemId hasn't been found</exception> public CoreSystem Convert(string value) { return (CoreSystem)Convert(value, null, null, CultureInfo.CurrentCulture); } /// <summary> /// Convert a <see cref="CoreSystem"/> value to BizHawk SystemId <see cref="string"/> /// </summary> /// <param name="value"><see cref="CoreSystem"/> you want to convert</param> /// <param name="targetType">The type of the binding target property</param> /// <param name="parameter">The converter parameter to use; null in our case</param> /// <param name="cultureInfo">The culture to use in the converter</param> /// <returns>A <see cref="string"/> that is used by BizHawk SystemId</returns> /// <exception cref="IndexOutOfRangeException">Thrown when <see cref="CoreSystem"/> hasn't been found</exception> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo cultureInfo) { return (CoreSystem) value switch { CoreSystem.AppleII => VSystemID.Raw.AppleII, CoreSystem.Atari2600 => VSystemID.Raw.A26, CoreSystem.Atari7800 => VSystemID.Raw.A78, CoreSystem.ChannelF => VSystemID.Raw.ChannelF, CoreSystem.ColecoVision => VSystemID.Raw.Coleco, CoreSystem.Commodore64 => VSystemID.Raw.C64, CoreSystem.GameBoyLink => VSystemID.Raw.GBL, CoreSystem.GameBoy => VSystemID.Raw.GB, CoreSystem.GameBoyAdvance => VSystemID.Raw.GBA, CoreSystem.Genesis => VSystemID.Raw.GEN, CoreSystem.GGL => VSystemID.Raw.GGL, CoreSystem.Intellivision => VSystemID.Raw.INTV, CoreSystem.Libretro => VSystemID.Raw.Libretro, CoreSystem.Lynx => VSystemID.Raw.Lynx, CoreSystem.MAME => VSystemID.Raw.MAME, CoreSystem.MasterSystem => VSystemID.Raw.SMS, CoreSystem.MSX => VSystemID.Raw.MSX, CoreSystem.NeoGeoPocket => VSystemID.Raw.NGP, CoreSystem.NES => VSystemID.Raw.NES, CoreSystem.Nintendo64 => VSystemID.Raw.N64, CoreSystem.NintendoDS => VSystemID.Raw.NDS, CoreSystem.Null => VSystemID.Raw.NULL, CoreSystem.PCEngine => VSystemID.Raw.PCE, CoreSystem.PcFx => VSystemID.Raw.PCFX, CoreSystem.Playstation => VSystemID.Raw.PSX, CoreSystem.Saturn => VSystemID.Raw.SAT, CoreSystem.SNES => VSystemID.Raw.SNES, CoreSystem.SuperGameBoy => VSystemID.Raw.SGB, CoreSystem.TI83 => VSystemID.Raw.TI83, CoreSystem.UzeBox => VSystemID.Raw.UZE, CoreSystem.Vectrex => VSystemID.Raw.VEC, CoreSystem.VirtualBoy => VSystemID.Raw.VB, CoreSystem.WonderSwan => VSystemID.Raw.WSWAN, CoreSystem.ZXSpectrum => VSystemID.Raw.ZXSpectrum, CoreSystem.AmstradCPC => VSystemID.Raw.AmstradCPC, CoreSystem.Odyssey2 => VSystemID.Raw.O2, _ => throw new IndexOutOfRangeException($"{value} is missing in convert list") }; } /// <summary> /// Convert a <see cref="CoreSystem"/> value to BizHawk SystemId <see cref="string"/> /// </summary> /// <param name="value"><see cref="CoreSystem"/> you want to convert</param> /// <returns>A <see cref="string"/> that is used by BizHawk SystemId</returns> /// <exception cref="IndexOutOfRangeException">Thrown when <see cref="CoreSystem"/> hasn't been found</exception> public string ConvertBack(CoreSystem value) { return (string)ConvertBack(value, null, null, CultureInfo.CurrentCulture); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; namespace CSharpGL { /// <summary> /// This class wraps the functionality of the wglUseFontBitmaps function to /// allow straightforward rendering of text. /// </summary> internal class FontBitmaps { /// <summary> /// Cache of font bitmap enties. /// </summary> private static readonly List<FontBitmapEntry> fontBitmapEntries = new List<FontBitmapEntry>(); /// <summary> /// Draws the text. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="color"></param> /// <param name="faceName"></param> /// <param name="fontSize"></param> /// <param name="text"></param> public static void DrawText(int x, int y, Color color, string faceName, float fontSize, string text) { IntPtr renderContext = Win32.wglGetCurrentContext(); IntPtr deviceContext = Win32.wglGetCurrentDC(); // Get the font size in pixels. var fontHeight = (int)(fontSize * (16.0f / 12.0f)); // Do we have a font bitmap entry for this OpenGL instance and face name? var result = (from fbe in fontBitmapEntries where fbe.HDC == deviceContext && fbe.HRC == renderContext && String.Compare(fbe.FaceName, faceName, StringComparison.OrdinalIgnoreCase) == 0 && fbe.Height == fontHeight select fbe).ToList(); // Get the FBE or null. var fontBitmapEntry = result.FirstOrDefault(); // If we don't have the FBE, we must create it. if (fontBitmapEntry == null) fontBitmapEntry = CreateFontBitmapEntry(faceName, fontHeight); var viewport = new int[4]; GL.Instance.GetIntegerv(GL.GL_VIEWPORT, viewport); double width = viewport[2]; double height = viewport[3]; // Create the appropriate projection matrix. GL.Instance.MatrixMode(GL.GL_PROJECTION); GL.Instance.PushMatrix(); GL.Instance.LoadIdentity(); GL.Instance.Ortho(0, width, 0, height, -1, 1); // Create the appropriate modelview matrix. GL.Instance.MatrixMode(GL.GL_MODELVIEW); GL.Instance.PushMatrix(); GL.Instance.LoadIdentity(); //GL.Instance.Color(color.R, color.G, color.B); //GL.Instance.RasterPos2i(x, y); //GL.Instance.PushAttrib(GL.GL_LIST_BIT | GL.GL_CURRENT_BIT | // GL.GL_ENABLE_BIT | GL.GL_TRANSFORM_BIT); GL.Instance.Color3ub(color.R, color.G, color.B); //GL.Instance.Disable(GL.GL_LIGHTING); //GL.Instance.Disable(GL.GL_TEXTURE_2D); //GL.Instance.Disable(GL.GL_DEPTH_TEST); GL.Instance.RasterPos2i(x, y); // Set the list base. GL.Instance.ListBase(fontBitmapEntry.ListBase); // Create an array of lists for the glyphs. var lists = text.Select(c => (byte)c).ToArray(); // Call the lists for the string. GL.Instance.CallLists(lists.Length, GL.GL_UNSIGNED_BYTE, lists); GL.Instance.Flush(); //// Reset the list bit. //GL.Instance.PopAttrib(); // Pop the modelview. GL.Instance.PopMatrix(); // back to the projection and pop it, then back to the model view. GL.Instance.MatrixMode(GL.GL_PROJECTION); GL.Instance.PopMatrix(); GL.Instance.MatrixMode(GL.GL_MODELVIEW); } private static FontBitmapEntry CreateFontBitmapEntry(string faceName, int height) { // Make the OpenGL instance current. //GL.MakeCurrent(); IntPtr renderContext = Win32.wglGetCurrentContext(); IntPtr deviceContext = Win32.wglGetCurrentDC(); Win32.wglMakeCurrent(deviceContext, renderContext); // Create the font based on the face name. var hFont = Win32.CreateFont(height, 0, 0, 0, Win32.FW_DONTCARE, 0, 0, 0, Win32.DEFAULT_CHARSET, Win32.OUT_OUTLINE_PRECIS, Win32.CLIP_DEFAULT_PRECIS, Win32.CLEARTYPE_QUALITY, Win32.VARIABLE_PITCH, faceName); // Select the font handle. var hOldObject = Win32.SelectObject(deviceContext, hFont); // Create the list base. var listBase = GL.Instance.GenLists(1); // Create the font bitmaps. bool result = Win32.wglUseFontBitmaps(deviceContext, 0, 255, listBase); // Reselect the old font. Win32.SelectObject(deviceContext, hOldObject); // Free the font. Win32.DeleteObject(hFont); // Create the font bitmap entry. var fbe = new FontBitmapEntry() { HDC = deviceContext, HRC = renderContext, FaceName = faceName, Height = height, ListBase = listBase, ListCount = 255 }; // Add the font bitmap entry to the internal list. fontBitmapEntries.Add(fbe); return fbe; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using Ultraviolet.Core; using Ultraviolet.Core.Data; using Ultraviolet.Presentation.Animations; using Ultraviolet.Presentation.Uvss; using Ultraviolet.Presentation.Uvss.Syntax; namespace Ultraviolet.Presentation.Styles { /// <summary> /// Represents an Ultraviolet Style Sheet (UVSS) document. /// </summary> public sealed partial class UvssDocument : UltravioletResource { /// <summary> /// Initializes the <see cref="UvssDocument"/> type. /// </summary> static UvssDocument() { standardEasingFunctions[KnownEasingFunctions.EaseInLinear] = Easings.EaseInLinear; standardEasingFunctions[KnownEasingFunctions.EaseOutLinear] = Easings.EaseOutLinear; standardEasingFunctions[KnownEasingFunctions.EaseInCubic] = Easings.EaseInCubic; standardEasingFunctions[KnownEasingFunctions.EaseOutCubic] = Easings.EaseOutCubic; standardEasingFunctions[KnownEasingFunctions.EaseInQuadratic] = Easings.EaseInQuadratic; standardEasingFunctions[KnownEasingFunctions.EaseOutQuadratic] = Easings.EaseOutQuadratic; standardEasingFunctions[KnownEasingFunctions.EaseInOutQuadratic] = Easings.EaseInOutQuadratic; standardEasingFunctions[KnownEasingFunctions.EaseInQuartic] = Easings.EaseInQuartic; standardEasingFunctions[KnownEasingFunctions.EaseOutQuartic] = Easings.EaseOutQuartic; standardEasingFunctions[KnownEasingFunctions.EaseInOutQuartic] = Easings.EaseInOutQuartic; standardEasingFunctions[KnownEasingFunctions.EaseInQuintic] = Easings.EaseInQuintic; standardEasingFunctions[KnownEasingFunctions.EaseOutQuintic] = Easings.EaseInQuintic; standardEasingFunctions[KnownEasingFunctions.EaseInOutQuintic] = Easings.EaseInOutQuintic; standardEasingFunctions[KnownEasingFunctions.EaseInSin] = Easings.EaseInSin; standardEasingFunctions[KnownEasingFunctions.EaseOutSin] = Easings.EaseOutSin; standardEasingFunctions[KnownEasingFunctions.EaseInOutSin] = Easings.EaseInOutSin; standardEasingFunctions[KnownEasingFunctions.EaseInExponential] = Easings.EaseInExponential; standardEasingFunctions[KnownEasingFunctions.EaseOutExponential] = Easings.EaseOutExponential; standardEasingFunctions[KnownEasingFunctions.EaseInOutExponential] = Easings.EaseInOutExponential; standardEasingFunctions[KnownEasingFunctions.EaseInCircular] = Easings.EaseInCircular; standardEasingFunctions[KnownEasingFunctions.EaseOutCircular] = Easings.EaseOutCircular; standardEasingFunctions[KnownEasingFunctions.EaseInOutCircular] = Easings.EaseInOutCircular; standardEasingFunctions[KnownEasingFunctions.EaseInBack] = Easings.EaseInBack; standardEasingFunctions[KnownEasingFunctions.EaseOutBack] = Easings.EaseOutBack; standardEasingFunctions[KnownEasingFunctions.EaseInOutBack] = Easings.EaseInOutBack; standardEasingFunctions[KnownEasingFunctions.EaseInElastic] = Easings.EaseInElastic; standardEasingFunctions[KnownEasingFunctions.EaseOutElastic] = Easings.EaseOutElastic; standardEasingFunctions[KnownEasingFunctions.EaseInOutElastic] = Easings.EaseInOutElastic; standardEasingFunctions[KnownEasingFunctions.EaseInBounce] = Easings.EaseInBounce; standardEasingFunctions[KnownEasingFunctions.EaseOutBounce] = Easings.EaseOutBounce; standardEasingFunctions[KnownEasingFunctions.EaseInOutBounce] = Easings.EaseInOutBounce; } /// <summary> /// Initializes a new instance of the <see cref="UvssDocument"/> class with no rules or storyboards. /// </summary> /// <param name="uv">The Ultraviolet context.</param> public UvssDocument(UltravioletContext uv) : this(uv, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="UvssDocument"/> class. /// </summary> /// <param name="uv">The Ultraviolet context.</param> /// <param name="rules">A collection containing the document's rules.</param> /// <param name="storyboards">A collection containing the document's storyboards.</param> public UvssDocument(UltravioletContext uv, IEnumerable<UvssRuleSet> rules, IEnumerable<UvssStoryboard> storyboards) : base(uv) { this.ruleSets = (rules ?? Enumerable.Empty<UvssRuleSet>()) .ToList(); this.storyboardDefinitions = (storyboards ?? Enumerable.Empty<UvssStoryboard>()) .ToList(); this.storyboardDefinitionsByName = new Dictionary<String, UvssStoryboard>(StringComparer.OrdinalIgnoreCase); this.storyboardInstancesByName = new Dictionary<String, Storyboard>(StringComparer.OrdinalIgnoreCase); foreach (var storyboardDefinition in storyboardDefinitions) storyboardDefinitionsByName[storyboardDefinition.Name] = storyboardDefinition; InstantiateStoryboards(); CategorizeRuleSets(); } /// <summary> /// Compiles an Ultraviolet Style Sheet (UVSS) document from the specified source text. /// </summary> /// <param name="uv">The Ultraviolet context.</param> /// <param name="source">The source text from which to compile the document.</param> /// <returns>A new instance of <see cref="UvssDocument"/> that represents the compiled data.</returns> public static UvssDocument Compile(UltravioletContext uv, String source) { Contract.Require(uv, nameof(uv)); Contract.Require(source, nameof(source)); var document = UvssParser.Parse(source); return Compile(uv, document); } /// <summary> /// Compiles an Ultraviolet Style Sheet (UVSS) document from the specified stream. /// </summary> /// <param name="uv">The Ultraviolet context.</param> /// <param name="stream">The <see cref="Stream"/> that contains the document to compile.</param> /// <returns>A new instance of <see cref="UvssDocument"/> that represents the compiled data.</returns> public static UvssDocument Compile(UltravioletContext uv, Stream stream) { Contract.Require(uv, nameof(uv)); Contract.Require(stream, nameof(stream)); using (var reader = new StreamReader(stream)) { var source = reader.ReadToEnd(); var document = UvssParser.Parse(source); return Compile(uv, document); } } /// <summary> /// Compiles an Ultraviolet Style Sheet (UVSS) document from the specified abstract syntax tree. /// </summary> /// <param name="uv">The Ultraviolet context.</param> /// <param name="tree">A <see cref="UvssDocumentSyntax"/> that represents the /// abstract syntax tree to compile.</param> /// <returns>A new instance of <see cref="UvssDocument"/> that represents the compiled data.</returns> public static UvssDocument Compile(UltravioletContext uv, UvssDocumentSyntax tree) { Contract.Require(uv, nameof(uv)); Contract.Require(tree, nameof(tree)); return UvssCompiler.Compile(uv, tree); } /// <summary> /// Clears the document's lists of rules and storyboards. /// </summary> public void Clear() { ruleSets.Clear(); storyboardDefinitions.Clear(); storyboardDefinitionsByName.Clear(); storyboardInstancesByName.Clear(); } /// <summary> /// Appends another styling document to the end of this document. /// </summary> /// <param name="document">The document to append to the end of this document.</param> public void Append(UvssDocument document) { Contract.Require(document, nameof(document)); Ultraviolet.ValidateResource(document); this.ruleSets.AddRange(document.RuleSets); this.storyboardDefinitions.AddRange(document.StoryboardDefinitions); foreach (var storyboardDefinition in document.storyboardDefinitions) this.storyboardDefinitionsByName[storyboardDefinition.Name] = storyboardDefinition; foreach (var storyboardInstance in document.storyboardInstancesByName) this.storyboardInstancesByName[storyboardInstance.Key] = storyboardInstance.Value; CategorizeRuleSets(); } /// <summary> /// Gets a <see cref="Storyboard"/> instance for the storyboard with the specified name, if /// such a storyboard exists within the styling document. /// </summary> /// <param name="name">The name of the storyboard to retrieve.</param> /// <returns>The <see cref="Storyboard"/> instance that was retrieved, or /// <see langword="null"/> if no such storyboard exists.</returns> public Storyboard GetStoryboardInstance(String name) { Contract.RequireNotEmpty(name, nameof(name)); Storyboard storyboard; storyboardInstancesByName.TryGetValue(name, out storyboard); return storyboard; } /// <summary> /// Gets the document's rule sets. /// </summary> public IEnumerable<UvssRuleSet> RuleSets { get { return ruleSets; } } /// <summary> /// Gets the document's storyboard definitions. /// </summary> public IEnumerable<UvssStoryboard> StoryboardDefinitions { get { return storyboardDefinitions; } } /// <summary> /// Gets the document's storyboard instances. /// </summary> public IEnumerable<Storyboard> StoryboardInstances { get { return storyboardInstancesByName.Values; } } /// <summary> /// Gets the culture which is used for UVSS documents which do not specify a culture. /// </summary> internal static CultureInfo DefaultCulture { get { return CultureInfo.GetCultureInfo(String.Empty); } } /// <summary> /// Applies styles to the specified element. /// </summary> /// <param name="element">The element to which to apply styles.</param> internal void ApplyStyles(UIElement element) { Contract.Require(element, nameof(element)); ApplyStylesInternal(element); } /// <summary> /// Retrieves the registered element type with the specified name. /// </summary> /// <param name="uv">The Ultraviolet context.</param> /// <param name="name">The name of the type to retrieve.</param> /// <returns>The registered element type with the specified name.</returns> private static Type ResolveKnownType(UltravioletContext uv, String name) { Type type; if (!uv.GetUI().GetPresentationFoundation().GetKnownType(name, false, out type)) throw new InvalidOperationException(PresentationStrings.UnrecognizedType.Format(name)); return type; } /// <summary> /// Retrieves the type of the dependency property with the specified name that /// matches the specified type filter. /// </summary> /// <param name="uv">The Ultraviolet context.</param> /// <param name="filter">The type filter for which to resolve a property type.</param> /// <param name="property">The property name for which to resolve a property type.</param> /// <returns>The type of the dependency property that was resolved.</returns> private static Type ResolvePropertyTypeFromFilter(UltravioletContext uv, IEnumerable<String> filter, ref String property) { var propertyName = property; var possiblePropertyMatches = from f in filter let elementType = ResolveKnownType(uv, f) let propertyID = DependencyProperty.FindByStylingName(propertyName, elementType) let propertyType = (propertyID == null) ? null : propertyID.PropertyType where propertyType != null select new { PropertyID = propertyID, PropertyType = propertyType }; var distinctNames = possiblePropertyMatches.Select(x => x.PropertyID.Name).Distinct(); if (distinctNames.Count() > 1) throw new InvalidOperationException(PresentationStrings.AmbiguousDependencyProperty.Format(property)); if (distinctNames.Any()) property = distinctNames.Single(); var distinctTypes = possiblePropertyMatches.Select(x => x.PropertyType).Distinct(); if (distinctTypes.Count() > 1) throw new InvalidOperationException(PresentationStrings.AmbiguousDependencyProperty.Format(property)); return distinctTypes.FirstOrDefault(); } /// <summary> /// Gets the type of <see cref="Animation{T}"/> which is used to animate /// the specified type. /// </summary> /// <param name="type">The type which is being animated.</param> /// <returns>The type of <see cref="Animation{T}"/> which is used to animate /// the specified type.</returns> private static Type GetAnimationType(Type type) { var nullable = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); return typeof(Animation<>).MakeGenericType(nullable ? type.GetGenericArguments()[0] : type); } /// <summary> /// Creates new <see cref="Storyboard"/> instances based on the current set of <see cref="UvssStoryboard"/> definitions. /// </summary> private void InstantiateStoryboards() { storyboardInstancesByName.Clear(); foreach (var storyboardDefinition in storyboardDefinitions) { var storyboardInstance = InstantiateStoryboard(storyboardDefinition); storyboardInstancesByName[storyboardDefinition.Name] = storyboardInstance; } } /// <summary> /// Creates a new <see cref="Storyboard"/> instance from the specified storyboard definition. /// </summary> /// <param name="storyboardDefinition">The storyboard definition to instantiate.</param> /// <returns>The <see cref="Storyboard"/> instance that was created.</returns> private Storyboard InstantiateStoryboard(UvssStoryboard storyboardDefinition) { var storyboardInstance = new Storyboard( Ultraviolet, storyboardDefinition.LoopBehavior); foreach (var targetDefinition in storyboardDefinition.Targets) { var targetInstance = InstantiateStoryboardTarget(targetDefinition); storyboardInstance.Targets.Add(targetInstance); } return storyboardInstance; } /// <summary> /// Creates a new <see cref="StoryboardTarget"/> instance from the specified target definition. /// </summary> /// <param name="targetDefinition">The storyboard target definition to instantiate.</param> /// <returns>The <see cref="StoryboardTarget"/> instance that was created.</returns> private StoryboardTarget InstantiateStoryboardTarget(UvssStoryboardTarget targetDefinition) { var target = new StoryboardTarget(targetDefinition.Selector); foreach (var animationDefinition in targetDefinition.Animations) { var ownerType = default(Type); if (animationDefinition.AnimatedProperty.IsAttached) PresentationFoundation.Instance.GetKnownType(animationDefinition.AnimatedProperty.Owner, out ownerType); var animatedPropertyName = animationDefinition.AnimatedProperty.Name; var animatedPropertyType = default(Type); if (animationDefinition.AnimatedProperty.IsAttached) { var dp = DependencyPropertySystem.FindByStylingName(animatedPropertyName, ownerType); if (dp != null) { animatedPropertyType = dp.PropertyType; animatedPropertyName = dp.Name; } } else { animatedPropertyType = ResolvePropertyTypeFromFilter(Ultraviolet, targetDefinition.Filter, ref animatedPropertyName); } var navigationExpression = default(NavigationExpression?); var navigationExpressionDef = animationDefinition.NavigationExpression; if (navigationExpressionDef != null) { animatedPropertyType = ResolvePropertyTypeFromFilter(Ultraviolet, new[] { navigationExpressionDef.NavigationPropertyType }, ref animatedPropertyName); navigationExpression = NavigationExpression.FromUvssNavigationExpression(Ultraviolet, navigationExpressionDef); } var animationDependencyName = new DependencyName(animationDefinition.AnimatedProperty.IsAttached ? $"{animationDefinition.AnimatedProperty.Owner}.{animatedPropertyName}" : animatedPropertyName); var animationKey = new StoryboardTargetAnimationKey(animationDependencyName, navigationExpression); var animation = InstantiateStoryboardAnimation(animationDefinition, animatedPropertyType); if (animation != null) { target.Animations.Add(animationKey, animation); } } return target; } /// <summary> /// Creates a new <see cref="AnimationBase"/> instance from the specified animation definition. /// </summary> /// <param name="animationDefinition">The animation definition to instantiate.</param> /// <param name="animatedPropertyType">The type of property which is being animated.</param> /// <returns>The <see cref="AnimationBase"/> instance that was created.</returns> private AnimationBase InstantiateStoryboardAnimation(UvssStoryboardAnimation animationDefinition, Type animatedPropertyType) { if (animatedPropertyType == null) return null; var animationType = GetAnimationType(animatedPropertyType); if (animationType == null) return null; var animation = (AnimationBase)Activator.CreateInstance(animationType); foreach (var keyframeDefinition in animationDefinition.Keyframes) { var keyframe = InstantiateStoryboardAnimationKeyframe(keyframeDefinition, animatedPropertyType); animation.AddKeyframe(keyframe); } return animation; } /// <summary> /// Creates a new <see cref="AnimationKeyframeBase"/> instance from the specified keyframe definition. /// </summary> /// <param name="keyframeDefinition">The keyframe definition to instantiate.</param> /// <param name="keyframeValueType">The type of value being animated by the keyframe.</param> /// <returns>The <see cref="AnimationKeyframeBase"/> instance that was created.</returns> private AnimationKeyframeBase InstantiateStoryboardAnimationKeyframe(UvssStoryboardKeyframe keyframeDefinition, Type keyframeValueType) { var time = TimeSpan.FromMilliseconds(keyframeDefinition.Time); var easing = default(EasingFunction); if (!String.IsNullOrEmpty(keyframeDefinition.Easing)) standardEasingFunctions.TryGetValue(keyframeDefinition.Easing, out easing); var valueDef = keyframeDefinition.Value; var value = valueDef.IsEmpty ? null : ObjectResolver.FromString(valueDef.Value, keyframeValueType, valueDef.Culture, true); var keyframeType = typeof(AnimationKeyframe<>).MakeGenericType(keyframeValueType); var keyframeInstance = (value == null) ? (AnimationKeyframeBase)Activator.CreateInstance(keyframeType, time, easing) : (AnimationKeyframeBase)Activator.CreateInstance(keyframeType, time, value, easing); return keyframeInstance; } /// <summary> /// Adds the specified rule set to the style prioritizer. /// </summary> private void AddRuleSetToPrioritizer(UIElement element, UvssSelector selector, UvssRuleSet ruleSet, Int32 index) { if (!selector.MatchesElement(element)) return; var navexp = NavigationExpression.FromUvssNavigationExpression(Ultraviolet, selector.NavigationExpression); foreach (var rule in ruleSet.Rules) prioritizer.Add(Ultraviolet, selector, navexp, rule, index); foreach (var trigger in ruleSet.Triggers) prioritizer.Add(Ultraviolet, selector, navexp, trigger, index); } /// <summary> /// Applies styles to the specified element. /// </summary> /// <param name="element">The element to which to apply styles.</param> private void ApplyStylesInternal(UIElement element) { try { element.ClearStyledValues(false); // Prioritize styles from name. var frameworkElement = element as FrameworkElement; if (frameworkElement != null && !String.IsNullOrEmpty(frameworkElement.Name)) { var ruleSetsByName = GetRuleSetsByName(frameworkElement.Name, onlyIfExists: true); if (ruleSetsByName != null) { foreach (var categorized in ruleSetsByName) AddRuleSetToPrioritizer(element, categorized.Selector, categorized.RuleSet, categorized.Index); } } // Prioritize styles from class. foreach (var @class in element.Classes) { var ruleSetsByCategory = GetRuleSetsByClass(@class, onlyIfExists: true); if (ruleSetsByCategory != null) { foreach (var categorized in ruleSetsByCategory) AddRuleSetToPrioritizer(element, categorized.Selector, categorized.RuleSet, categorized.Index); } } // Prioritize rules from type. var ruleSetsByType = GetRuleSetsByType(element.UvmlName, onlyIfExists: true); if (ruleSetsByType != null) { foreach (var categorized in ruleSetsByType) AddRuleSetToPrioritizer(element, categorized.Selector, categorized.RuleSet, categorized.Index); } // Prioritize uncategorized styles. foreach (var categorized in ruleSetsWithoutCategory) AddRuleSetToPrioritizer(element, categorized.Selector, categorized.RuleSet, categorized.Index); // Apply styles to element prioritizer.Apply(element); } finally { // Reset the prioritizer even if something blows up. prioritizer.Reset(); } } /// <summary> /// Sorts the document's rule sets into categories for faster querying. /// </summary> private void CategorizeRuleSets() { ruleSetsWithoutCategory.Clear(); ruleSetsByName.Clear(); ruleSetsByType.Clear(); ruleSetsByClass.Clear(); for (int i = 0; i < ruleSets.Count; i++) { var ruleSet = ruleSets[i]; foreach (var selector in ruleSet.Selectors) { var lastSelectorPart = selector[selector.PartCount - 1]; var categorized = false; if (!categorized && lastSelectorPart.HasName) { var category = GetRuleSetsByName(lastSelectorPart.Name); category.Add(new CategorizedRuleSet(selector, ruleSet, i)); categorized = true; } if (!categorized && lastSelectorPart.HasClasses) { foreach (var @class in lastSelectorPart.Classes) { var category = GetRuleSetsByClass(@class); category.Add(new CategorizedRuleSet(selector, ruleSet, i)); categorized = true; } } if (!categorized && lastSelectorPart.HasExactType) { var category = GetRuleSetsByType(lastSelectorPart.Type); category.Add(new CategorizedRuleSet(selector, ruleSet, i)); categorized = true; } if (!categorized) GetRuleSetsWithoutCategory().Add(new CategorizedRuleSet(selector, ruleSet, i)); } } } /// <summary> /// Gets the list of rule sets which have no particular category. /// </summary> private List<CategorizedRuleSet> GetRuleSetsWithoutCategory() { return ruleSetsWithoutCategory; } /// <summary> /// Gets the list of rule sets which apply to the specified name. /// </summary> private List<CategorizedRuleSet> GetRuleSetsByName(String name, Boolean onlyIfExists = false) { return GetRuleSetCategory(ruleSetsByName, name, onlyIfExists); } /// <summary> /// Gets the list of rule sets which apply to the specified type. /// </summary> private List<CategorizedRuleSet> GetRuleSetsByType(String element, Boolean onlyIfExists = false) { return GetRuleSetCategory(ruleSetsByType, element, onlyIfExists); } /// <summary> /// Gets the list of rule sets which apply to the specified class. /// </summary> private List<CategorizedRuleSet> GetRuleSetsByClass(String @class, Boolean onlyIfExists = false) { return GetRuleSetCategory(ruleSetsByClass, @class, onlyIfExists); } /// <summary> /// Gets the list of rule sets which apply to the specified category. /// </summary> private List<CategorizedRuleSet> GetRuleSetCategory(Dictionary<String, List<CategorizedRuleSet>> ruleSets, String key, Boolean onlyIfExists = false) { List<CategorizedRuleSet> category; if (!ruleSets.TryGetValue(key, out category)) { if (onlyIfExists) return null; category = new List<CategorizedRuleSet>(); ruleSets[key] = category; } return category; } // The standard easing functions which can be specified in an animation. private static readonly Dictionary<String, EasingFunction> standardEasingFunctions = new Dictionary<String, EasingFunction>(); // State values. private readonly UvssStylePrioritizer prioritizer = new UvssStylePrioritizer(); // Property values. private readonly List<UvssRuleSet> ruleSets; private readonly List<UvssStoryboard> storyboardDefinitions; private readonly Dictionary<String, UvssStoryboard> storyboardDefinitionsByName; private readonly Dictionary<String, Storyboard> storyboardInstancesByName; // Categorize rule sets based on their selectors. private readonly Dictionary<String, List<CategorizedRuleSet>> ruleSetsByName = new Dictionary<String, List<CategorizedRuleSet>>(); private readonly Dictionary<String, List<CategorizedRuleSet>> ruleSetsByType = new Dictionary<String, List<CategorizedRuleSet>>(); private readonly Dictionary<String, List<CategorizedRuleSet>> ruleSetsByClass = new Dictionary<String, List<CategorizedRuleSet>>(); private readonly List<CategorizedRuleSet> ruleSetsWithoutCategory = new List<CategorizedRuleSet>(); } }
// Copyright (c) 2020 Sergio Aquilini // This code is licensed under MIT license (see LICENSE file for details) using System; using Confluent.Kafka; using FluentAssertions; using Silverback.Messaging; using Silverback.Messaging.Configuration.Kafka; using Silverback.Messaging.Serialization; using Xunit; namespace Silverback.Tests.Integration.Kafka.Messaging { public class KafkaProducerEndpointTests { [Theory] [InlineData(0, true)] [InlineData(42, true)] [InlineData(-1, true)] [InlineData(-2, false)] public void Constructor_Partition_CorrectlyValidated(int value, bool isValid) { KafkaProducerEndpoint? endpoint = null; Action act = () => { endpoint = new KafkaProducerEndpoint("test", value) { Configuration = new KafkaProducerConfig { BootstrapServers = "test-server" } }; }; if (isValid) { act.Should().NotThrow(); endpoint.Should().NotBeNull(); } else { act.Should().ThrowExactly<ArgumentOutOfRangeException>(); } } [Fact] public void Equals_SameEndpointInstance_TrueIsReturned() { var endpoint = new KafkaProducerEndpoint("topic") { Configuration = { Acks = Acks.Leader } }; endpoint.Equals(endpoint).Should().BeTrue(); } [Fact] public void Equals_SameConfiguration_TrueIsReturned() { var endpoint1 = new KafkaProducerEndpoint("topic") { Configuration = { Acks = Acks.Leader } }; var endpoint2 = new KafkaProducerEndpoint("topic") { Configuration = { Acks = Acks.Leader } }; endpoint1.Equals(endpoint2).Should().BeTrue(); } [Fact] public void Equals_DifferentTopic_FalseIsReturned() { var endpoint1 = new KafkaProducerEndpoint("topic") { Configuration = { Acks = Acks.Leader } }; var endpoint2 = new KafkaProducerEndpoint("topic2") { Configuration = { Acks = Acks.Leader } }; endpoint1.Equals(endpoint2).Should().BeFalse(); } [Fact] public void Equals_SameTopicAndPartition_TrueIsReturned() { var endpoint1 = new KafkaProducerEndpoint("topic", 1); var endpoint2 = new KafkaProducerEndpoint("topic", 1); endpoint1.Equals(endpoint2).Should().BeTrue(); } [Fact] public void Equals_DifferentConfiguration_FalseIsReturned() { var endpoint1 = new KafkaProducerEndpoint("topic") { Configuration = { Acks = Acks.Leader } }; var endpoint2 = new KafkaProducerEndpoint("topic") { Configuration = { Acks = Acks.All } }; endpoint1.Equals(endpoint2).Should().BeFalse(); } [Fact] public void Equals_SameSerializerSettings_TrueIsReturned() { var endpoint1 = new KafkaProducerEndpoint("topic") { Serializer = new JsonMessageSerializer { Options = { MaxDepth = 100 } } }; var endpoint2 = new KafkaProducerEndpoint("topic") { Serializer = new JsonMessageSerializer { Options = { MaxDepth = 100 } } }; endpoint1.Equals(endpoint2).Should().BeTrue(); } [Fact] public void Equals_DifferentSerializerSettings_FalseIsReturned() { var endpoint1 = new KafkaProducerEndpoint("topic") { Serializer = new JsonMessageSerializer { Options = { MaxDepth = 100 } } }; var endpoint2 = new KafkaProducerEndpoint("topic") { Serializer = new JsonMessageSerializer { Options = { MaxDepth = 8 } } }; endpoint1.Equals(endpoint2).Should().BeFalse(); } [Fact] public void Validate_ValidTopicAndConfiguration_NoExceptionThrown() { var endpoint = GetValidEndpoint(); Action act = () => endpoint.Validate(); act.Should().NotThrow<EndpointConfigurationException>(); } [Fact] public void Validate_InvalidConfiguration_ExceptionThrown() { var endpoint = new KafkaProducerEndpoint("topic"); Action act = () => endpoint.Validate(); act.Should().ThrowExactly<EndpointConfigurationException>(); } [Fact] public void Validate_MissingTopic_ExceptionThrown() { var endpoint = new KafkaProducerEndpoint(string.Empty) { Configuration = new KafkaProducerConfig { BootstrapServers = "test-server" } }; Action act = () => endpoint.Validate(); act.Should().ThrowExactly<EndpointConfigurationException>(); } private static KafkaProducerEndpoint GetValidEndpoint() => new("test") { Configuration = new KafkaProducerConfig { BootstrapServers = "test-server" } }; } }
using System.Threading.Tasks; using Chameleon.Core.ViewModels; using MvvmCross.Navigation; using MvvmCross.ViewModels; namespace Chameleon.Core { public class AppStart : MvxAppStart { public AppStart(IMvxApplication application, IMvxNavigationService navigationService) : base(application, navigationService) { } protected override async Task NavigateToFirstViewModel(object hint = null) { await NavigationService.Navigate<RootViewModel>(); } } }
using System; using XLua.LuaDLL; using XLuaTest; namespace XLua.CSObjectWrap { public class XLuaTestFooExtensionWrap { public static void __Register(IntPtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Type typeFromHandle = typeof(FooExtension); Utils.BeginObjectRegister(typeFromHandle, L, translator, 0, 0, 0, 0, -1); Utils.EndObjectRegister(typeFromHandle, L, translator, null, null, null, null, null); Utils.BeginClassRegister(typeFromHandle, L, new lua_CSFunction(XLuaTestFooExtensionWrap.__CreateInstance), 1, 0, 0); Utils.EndClassRegister(typeFromHandle, L, translator); } [MonoPInvokeCallback(typeof(lua_CSFunction))] private static int __CreateInstance(IntPtr L) { return Lua.luaL_error(L, "XLuaTest.FooExtension does not have a constructor!"); } } }