content
stringlengths
23
1.05M
using System; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Options; using MongoDB.Driver; namespace MongoDistributedCache { public interface IMongoAccessor { MongoCacheItem Get(string key); Task<MongoCacheItem> GetAsync(string key, CancellationToken token); void Upsert(string key, MongoCacheItem cacheItem); Task UpsertAsync(string key, MongoCacheItem cacheItem, CancellationToken token); void Delete(string key); Task DeleteAsync(string key, CancellationToken token); void DeleteMany(Expression<Func<MongoCacheItem, bool>> filter); } }
namespace TheSaga.Handlers.Builders { public interface IHandlersBuilderWhen : IHandlersBuilder { } }
using System; using Unity.Entities; namespace Ecosystem.ECS.Player { /// <summary> /// Marks an entity as player-controlled. /// </summary> [Serializable] [GenerateAuthoringComponent] public struct PlayerTag : IComponentData { } }
// ReSharper disable once CheckNamespace namespace Fluxera.Utilities.Extensions { using System; using System.Globalization; using Guards; public static partial class DateTimeExtensions { /// <summary> /// Gets the next occurrence of the specified weekday within the current week using the current culture. /// </summary> /// <param name="date">The base date.</param> /// <param name="weekday">The desired weekday.</param> /// <returns>The calculated date.</returns> public static DateTime GetWeeksWeekday(this DateTime date, DayOfWeek weekday) { return date.GetWeeksWeekday(weekday, CultureInfo.CurrentCulture); } /// <summary> /// Gets the next occurrence of the specified weekday within the current week using the specified culture. /// </summary> /// <param name="date">The base date.</param> /// <param name="weekday">The desired weekday.</param> /// <param name="cultureInfo">The culture to determine the first weekday of a week.</param> /// <returns>The calculated date.</returns> public static DateTime GetWeeksWeekday(this DateTime date, DayOfWeek weekday, CultureInfo cultureInfo) { Guard.Against.Null(cultureInfo, nameof(cultureInfo)); DateTime firstDayOfWeek = date.GetFirstDayOfWeek(cultureInfo); return firstDayOfWeek.GetNextWeekday(weekday); } } }
using System; using EcsRx.Entities; using EcsRx.Events; using EcsRx.Pools; using UnityEngine; using Zenject; namespace EcsRx.Unity.Systems { public interface IViewHandler { IPoolManager PoolManager { get; } IEventSystem EventSystem { get; } IInstantiator Instantiator { get; } GameObject InstantiateAndInject(GameObject prefab, Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion)); void DestroyView(GameObject view); void SetupView(IEntity entity, Func<IEntity, GameObject> viewResolver); } }
using System; using System.Globalization; using Newtonsoft.Json; namespace Kudu.Contracts.Diagnostics { public class ApplicationLogEntry { [JsonProperty(PropertyName = "timestamp")] public DateTimeOffset TimeStamp { get; set; } [JsonProperty(PropertyName = "level")] public string Level { get; set; } [JsonProperty(PropertyName = "pid")] public int PID { get; set; } [JsonProperty(PropertyName = "message")] public string Message { get; set; } public ApplicationLogEntry() { } public ApplicationLogEntry(DateTime eventDate, string level, int pid, string message) { TimeStamp = eventDate; Level = level; PID = pid; Message = message; } public void AddMessageLine(string messagePart) { this.Message = string.IsNullOrEmpty(this.Message) ? messagePart : messagePart + System.Environment.NewLine + this.Message; } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "Application Log Entry, TimeStamp: {0}, Level: {1}, PID: {2}, Message: {3}", TimeStamp, Level, PID, Message); } } }
// (c) 2020 Francesco Del Re <francesco.delre.87@gmail.com> // This code is licensed under MIT license (see LICENSE.txt for details) namespace SharpRedisMonitor.Models { public class ClientsModel { public string ConnectedClients { get; set; } } }
using ShapeCrawler; internal class PictureSample { internal static void ReadPicture() { using var presentation = SCPresentation.Open(@"test.pptx", true); var slide = presentation.Slides[0]; // Get picture shape by name var pictureShape = slide.Shapes.GetByName<IPicture>("Picture 1"); // Get MIME type of image, eg. "image/png" var mimeType = pictureShape.Image.MIME; } }
using System; using BookLovers.Shared; using BookLovers.Shared.SharedSexes; namespace BookLovers.Readers.Domain.Profiles.Services.Factories { public class ProfileContentData { public FullName FullName { get; } public DateTime BirthDate { get; } public Sex Sex { get; } public ProfileContentData(FullName fullName, DateTime birthDate, Sex sex) { FullName = fullName; BirthDate = birthDate; Sex = sex; } } }
public enum ButtonInteractID // TypeDefIndex: 10738 { // Fields public int value__; // 0x0 public const ButtonInteractID A = 0; public const ButtonInteractID B = 1; public const ButtonInteractID X = 2; public const ButtonInteractID Y = 3; }
using System.Xml.Linq; namespace Weixin.Next.MP.Messaging.Requests { /// <summary> /// 未知类别的请求消息, 可以通过 Xml 属性直接获取消息内容 /// </summary> public class UnknownRequestMessage : RequestMessage { public UnknownRequestMessage(XElement xml) : base(xml) { } /// <summary> /// 代表请求消息中 xml 元素 /// </summary> public XElement Xml { get { return _xml; } } /// <summary> /// 消息中的 MsgType 值 /// </summary> public string RawMsgType { get { return _xml.Element("MsgType").Value; } } public override string GetDuplicationKey() { return _xml.Element("MsgId")?.Value ?? base.GetDuplicationKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using GCore.Extensions.StreamEx; namespace GCore.Networking { public class NetworkingHelper { public static string FTPUpload(string ftpServer, string filename) { return FTPUpload(ftpServer, filename, "anonymous", ""); } public static string FTPUpload(string ftpServer, string filename, string userName, string password) { using (System.Net.WebClient client = new System.Net.WebClient()) { client.Credentials = new System.Net.NetworkCredential(userName, password); client.UploadFile(ftpServer + "/" + new FileInfo(filename).Name, "STOR", filename); } return "OK"; } public static string FTPUploadS(string ftpServerFile, string data) { return FTPUploadS(ftpServerFile, data, "anonymous", ""); } public static string FTPUploadS(string ftpServerFile, string data, string userName, string password) { using (System.Net.WebClient client = new System.Net.WebClient()) { client.Credentials = new System.Net.NetworkCredential(userName, password); //client.UploadFile(ftpServerFile, "STOR", filename); client.UploadString(ftpServerFile, data); } return "OK"; } public static string FTPDownload(string ftpServerFile, string filename) { return FTPDownload(ftpServerFile, filename, "anonymous", ""); } public static string FTPDownload(string ftpServerFile, string filename, string userName, string password) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServerFile); request.Method = WebRequestMethods.Ftp.DownloadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential(userName, password); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); responseStream.StreamToFile(filename, FileMode.OpenOrCreate); return "OK"; } public static string FTPDownloadS(string ftpServerFile, string filename) { return FTPDownloadS(ftpServerFile, filename, "anonymous", ""); } public static string FTPDownloadS(string ftpServerFile, string filename, string userName, string password) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServerFile); request.Method = WebRequestMethods.Ftp.DownloadFile; // This example assumes the FTP site uses anonymous logon. request.Credentials = new NetworkCredential(userName, password); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); string tmp = reader.ReadToEnd(); reader.Close(); return tmp; } public static string wget(string url, string dst) { WebClient webClient = new WebClient(); webClient.DownloadFile(url, dst); return "OK"; } public static string wget(string url) { WebClient client = new WebClient(); return client.DownloadString(url); } public static bool IsLocalIpAddress(string host) { try { // get host IP addresses IPAddress[] hostIPs = Dns.GetHostAddresses(host); // get local IP addresses IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName()); // test if any host IP equals to any local IP or to localhost foreach (IPAddress hostIP in hostIPs) { // is localhost if (IPAddress.IsLoopback(hostIP)) return true; // is local address foreach (IPAddress localIP in localIPs) { if (hostIP.Equals(localIP)) return true; } } } catch { } return false; } public static IEnumerable<string> GetLocalAddresses() => Dns.GetHostAddresses(Dns.GetHostName()).Select(h => h.ToString()); public static string GetLocalAddress() { var shortest = "####################################################################"; foreach (var localAddress in GetLocalAddresses()) { if (localAddress.Length < shortest.Length) shortest = localAddress; } return shortest; } public static bool TryParseIpAddress(string ipString, out IPAddress ipAddress) { if (ipString == "*") { ipAddress = IPAddress.Any; return true; } else if (ipString.ToLower() == "any") { ipAddress = IPAddress.Any; return true; } else if (ipString.ToLower() == "broadcast") { ipAddress = IPAddress.Broadcast; return true; } else if (ipString.ToLower() == "ipv6any") { ipAddress = IPAddress.IPv6Any; return true; } else if (ipString.ToLower() == "ipv6loopback") { ipAddress = IPAddress.IPv6Loopback; return true; } else if (ipString.ToLower() == "ipv6none") { ipAddress = IPAddress.IPv6None; return true; } else if (ipString.ToLower() == "loopback") { ipAddress = IPAddress.Loopback; return true; } else if (ipString.ToLower() == "none") { ipAddress = IPAddress.None; return true; } return IPAddress.TryParse(ipString, out ipAddress); } } }
using System.Runtime.InteropServices; using Prometheus.SystemMetrics.Native; namespace Prometheus.SystemMetrics.Collectors { /// <summary> /// Collects data on system load average /// </summary> public class LoadAverageCollector : ISystemMetricCollector { internal Gauge Load1 { get; private set; } = default!; internal Gauge Load5 { get; private set; } = default!; internal Gauge Load15 { get; private set; } = default!; /// <summary> /// Gets whether this metric is supported on the current system. /// </summary> public bool IsSupported => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); /// <summary> /// Creates the Prometheus metric. /// </summary> /// <param name="factory">Factory to create metric using</param> public void CreateMetrics(MetricFactory factory) { Load1 = factory.CreateGauge("node_load1", "Load average over the last minute."); Load5 = factory.CreateGauge("node_load5", "Load average over the last 5 minutes."); Load15 = factory.CreateGauge("node_load15", "Load average over the last 15 minutes."); } /// <summary> /// Update data for the metrics. Called immediately before the metrics are scraped. /// </summary> public void UpdateMetrics() { var loadAverage = new double[3]; if (LinuxNative.getloadavg(loadAverage, 3) == 3) { Load1.Set(loadAverage[0]); Load5.Set(loadAverage[1]); Load15.Set(loadAverage[2]); } } } }
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using Xunit; using Amazon.KinesisTap.Shared.Ast; using Amazon.KinesisTap.Shared.Binder; using Amazon.KinesisTap.Shared.ObjectDecoration; namespace Amazon.KinesisTap.Shared.Test { public class ObjectDecorationValueEvaluatorTest { private ObjectDecorationInterpreter<object> _evaluator; public ObjectDecorationValueEvaluatorTest() { FunctionBinder binder = new FunctionBinder(new Type[] { typeof(BuiltInFunctions) }); ExpressionEvaluationContext<object> context = new ExpressionEvaluationContext<object>( VariableMock.GetGlobalVariable, VariableMock.GetLocalVariable, binder, null); _evaluator = new ObjectDecorationInterpreter<object>(context); } [Theory] [InlineData("", "")] [InlineData("{'a'}", "a")] [InlineData("{1}", "1")] [InlineData("{1.21}", "1.21")] [InlineData("{null}", "")] [InlineData("{a}", "gav")] [InlineData("{b}", "gbv")] [InlineData("{$a}", "9")] [InlineData("{$'a'}", "9")] [InlineData("{$b}", "hello")] [InlineData("{$c}", "1.24")] [InlineData("{length('abc')}", "3")] [InlineData("{length($b)}", "5")] [InlineData("{lower('ABC')}", "abc")] [InlineData("{upper('abc')}", "ABC")] [InlineData("{lpad($b, $a, '!')}", "!!!!hello")] [InlineData("{rpad($b, $a, '!')}", "hello!!!!")] [InlineData("{ltrim(' a ')}", "a ")] [InlineData("{rtrim(' a ')}", " a")] [InlineData("{trim(' a ')}", "a")] [InlineData("{substr($b, 2)}", "ello")] [InlineData("{substr($b, 2, 1)}", "e")] [InlineData("{regexp_extract('Info: MID 118667291 ICID 197973259 RID 0 To: <jd@acme.com>', 'To: \\\\S+')}", "To: <jd@acme.com>")] [InlineData("{regexp_extract('Info: MID 118667291 ICID 197973259 RID 0 To: <jd@acme.com>', 'To: (\\\\S+)', 1)}", "<jd@acme.com>")] [InlineData("{regexp_extract('Info: MID 118667291 ICID 197973259 RID 0 To: <jd@acme.com>', 'From: \\\\S+')}", "")] [InlineData("{regexp_extract('Info: MID 118667291 ICID 197973259 RID 0 To: <jd@acme.com>', 'From: (\\\\S+)', 1)}", "")] [InlineData("{format(date(2018, 11, 28), 'MMddyyyy')}", "11282018")] [InlineData("{format(parse_date('2018-11-28', 'yyyy-MM-dd'), 'MMddyyyy')}", "11282018")] [InlineData("{substr($b, '2')}", "")] [InlineData("{substr($b, parse_int('2'))}", "ello")] [InlineData("{coalesce(null, 'a')}", "a")] [InlineData("a{'b'}c", "abc")] public void TestObjectDecorationValueEvaluator(string value, string expected) { var tree = ObjectDecorationParserFacade.ParseObjectDecorationValue(value); string actual = (string)_evaluator.Visit(tree, null); Assert.Equal(expected, actual); } } }
using System; using System.Threading; using System.Threading.Tasks; namespace StopGuessing.DataStructures { public class MemoryUsageLimiter : IDisposable { private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); public class ReduceMemoryUsageEventParameters : EventArgs { public readonly double FractionOfMemoryToTryToRemove; public ReduceMemoryUsageEventParameters( double fractionOfMemoryToTryToRemove) { FractionOfMemoryToTryToRemove = fractionOfMemoryToTryToRemove; } } public event EventHandler<ReduceMemoryUsageEventParameters> OnReduceMemoryUsageEventHandler; private readonly double _fractionToRemoveOnCleanup; public MemoryUsageLimiter( double fractionToRemoveOnCleanup = 0.2 /* 20% */, long hardMemoryLimit = 0) { _fractionToRemoveOnCleanup = fractionToRemoveOnCleanup; if (hardMemoryLimit == 0) { Task.Run(() => GenerationalReductionLoop(cancellationTokenSource.Token), cancellationTokenSource.Token); } else { Task.Run(() => ThresholdReductionLoop(hardMemoryLimit, cancellationTokenSource.Token), cancellationTokenSource.Token); } } public void ReduceMemoryUsage() { EventHandler<ReduceMemoryUsageEventParameters> localOnReduceMemoryUsageHandler = OnReduceMemoryUsageEventHandler; if (localOnReduceMemoryUsageHandler != null) { Parallel.ForEach(localOnReduceMemoryUsageHandler.GetInvocationList(), d => { try { d.DynamicInvoke(this, new ReduceMemoryUsageEventParameters(_fractionToRemoveOnCleanup)); } catch (Exception) { // ignored } } ); } } public void GenerationalReductionLoop(CancellationToken cancellationToken) { GC.RegisterForFullGCNotification(10,10); while (true) { int collectionCount = GC.CollectionCount(2); while (GC.WaitForFullGCApproach(100) == GCNotificationStatus.Timeout) cancellationToken.ThrowIfCancellationRequested(); ReduceMemoryUsage(); if (collectionCount == GC.CollectionCount(2)) GC.Collect(); while (GC.WaitForFullGCComplete(100) == GCNotificationStatus.Timeout) cancellationToken.ThrowIfCancellationRequested(); } // ReSharper disable once FunctionNeverReturns } public void ThresholdReductionLoop(long hardMemoryLimit, CancellationToken cancellationToken) { while (true) { try { System.Threading.Thread.Sleep(250); cancellationToken.ThrowIfCancellationRequested(); long currentMemoryConsumptionInBytes = GC.GetTotalMemory(true); if (currentMemoryConsumptionInBytes > hardMemoryLimit) { Console.Error.WriteLine("Starting memory reduction."); ReduceMemoryUsage(); Console.Error.WriteLine("Completing memory reduction."); } } catch (Exception) { // ignored } } // ReSharper disable once FunctionNeverReturns } public void Dispose() { cancellationTokenSource.Cancel(); } } }
using Identity.Core.Entities; using Identity.Core.Managers; using IdentityServer3.AspNetIdentity; namespace Identity.Core.Services { /// <summary> /// The user service, wraps logical operations to the usermanager object /// </summary> public class ApplicationUserService : AspNetIdentityUserService<ApplicationUser, string> { /// <summary> /// .ctor for ApplicationUserService /// </summary> /// <param name="userMgr"><see cref="ApplicationUserManager"/>, contains logic operations for users</param> public ApplicationUserService( ApplicationUserManager userMgr) : base(userMgr) { } } }
using System; using HarvestingFieldsPgm.Engine; class HarvestingFieldsTest { static void Main(string[] args) { string command = Console.ReadLine(); while (!command.Equals("HARVEST")) { string result = Engine.GetFields(command); Console.WriteLine(result.Replace("family", "protected")); command = Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Prism.Container.Extensions.Shared.Mocks; using Prism.Container.Extensions.Shared.Tests; using Prism.Container.Extensions.Tests.Mocks; using Prism.Ioc; using Unity; using Xunit; using Xunit.Abstractions; namespace Prism.Unity.Extensions.Tests { [Collection(nameof(SharedTests))] public class ContainerTests { private readonly object testLock = new object(); private ITestOutputHelper _testOutputHelper; public ContainerTests(ITestOutputHelper testOutputHelper) => _testOutputHelper = testOutputHelper; [Fact] public void StaticInstanceSameAsNewInstance() { lock (testLock) { PrismContainerExtension.Reset(); GC.Collect(); var newInstance = PrismContainerExtension.Init(); Assert.Same(newInstance, PrismContainerExtension.Current); } } [Fact] public void StaticInstanceSameAsCreateInstance() { lock (testLock) { PrismContainerExtension.Reset(); GC.Collect(); var created = PrismContainerExtension.Init(new UnityContainer()); Assert.Same(created, PrismContainerExtension.Current); } } [Fact] public void CreateCanOnlyBeCalledOnce() { lock (testLock) { var newInstance1 = CreateContainer(); Assert.Same(newInstance1, PrismContainerExtension.Current); var ex = Record.Exception(() => PrismContainerExtension.Init()); Assert.NotNull(ex); Assert.IsType<NotSupportedException>(ex); } } [Fact] public void IServiceProviderIsRegistered() { lock (testLock) { PrismContainerExtension.Reset(); GC.Collect(); Assert.True(((IContainerProvider)PrismContainerExtension.Current).IsRegistered<IServiceProvider>()); } } [Fact] public void IContainerProviderIsRegistered() { lock (testLock) { PrismContainerExtension.Reset(); GC.Collect(); Assert.True(((IContainerProvider)PrismContainerExtension.Current).IsRegistered<IContainerProvider>()); } } [Fact] public void RegisterManyHasSameTypeAcrossServices() { lock (testLock) { var c = CreateContainer(); c.RegisterMany<FooBarImpl>(); IFoo foo = null; IBar bar = null; var ex = Record.Exception(() => foo = c.Resolve<IFoo>()); Assert.Null(ex); Assert.NotNull(foo); Assert.IsType<FooBarImpl>(foo); ex = Record.Exception(() => bar = c.Resolve<IBar>()); Assert.Null(ex); Assert.NotNull(bar); Assert.IsType<FooBarImpl>(bar); Assert.NotSame(foo, bar); } } [Fact] public void RegisterManyHasSameInstanceAcrossServices() { lock (testLock) { var c = CreateContainer(); c.RegisterManySingleton<FooBarImpl>(); IFoo foo = null; IBar bar = null; var ex = Record.Exception(() => foo = c.Resolve<IFoo>()); Assert.Null(ex); Assert.NotNull(foo); Assert.IsType<FooBarImpl>(foo); ex = Record.Exception(() => bar = c.Resolve<IBar>()); Assert.Null(ex); Assert.NotNull(bar); Assert.IsType<FooBarImpl>(bar); var fooHash = foo.GetHashCode(); var barHash = bar.GetHashCode(); Assert.Same(foo, bar); } } [Fact] public void RegisterTransientService() { lock (testLock) { var c = CreateContainer(); c.Register<IFoo, Foo>(); IFoo foo = null; var ex = Record.Exception(() => foo = c.Resolve<IFoo>()); Assert.Null(ex); Assert.NotNull(foo); Assert.IsType<Foo>(foo); } } [Fact] public void RegisterTransientNamedService() { lock (testLock) { var c = CreateContainer(); c.Register<IFoo, Foo>("fooBar"); IFoo foo = null; var ex = Record.Exception(() => foo = c.Resolve<IFoo>()); Assert.NotNull(ex); ex = null; ex = Record.Exception(() => foo = c.Resolve<IFoo>("fooBar")); Assert.Null(ex); Assert.NotNull(foo); Assert.IsType<Foo>(foo); } } [Fact] public void RegisterSingletonService() { lock (testLock) { var c = CreateContainer(); c.RegisterSingleton<IFoo, Foo>(); IFoo foo = null; var ex = Record.Exception(() => foo = c.Resolve<IFoo>()); Assert.Null(ex); Assert.NotNull(foo); Assert.IsType<Foo>(foo); Assert.Same(foo, c.Resolve<IFoo>()); } } [Fact] public void RegisterInstanceResolveSameInstance() { lock (testLock) { var c = CreateContainer(); var foo = new Foo(); c.RegisterInstance<IFoo>(foo); Assert.True(((IContainerRegistry)c).IsRegistered<IFoo>()); Assert.Same(foo, c.Resolve<IFoo>()); } } [Fact] public void RegisterInstanceResolveSameNamedInstance() { lock (testLock) { var c = CreateContainer(); var foo = new Foo(); c.RegisterInstance<IFoo>(foo, "test"); Assert.True(((IContainerRegistry)c).IsRegistered<IFoo>("test")); Assert.Same(foo, c.Resolve<IFoo>("test")); } } [Fact] public void RegisterSingletonNamedService() { lock (testLock) { var c = CreateContainer(); c.RegisterSingleton<IFoo, Foo>("fooBar"); IFoo foo = null; var ex = Record.Exception(() => foo = c.Resolve<IFoo>()); Assert.NotNull(ex); ex = null; ex = Record.Exception(() => foo = c.Resolve<IFoo>("fooBar")); Assert.Null(ex); Assert.NotNull(foo); Assert.IsType<Foo>(foo); Assert.Same(foo, c.Resolve<IFoo>("fooBar")); } } [Fact] public void FactoryCreatesTransientTypeWithoutContainerProvider() { lock (testLock) { var c = CreateContainer(); var message = "expected"; c.Register<IFoo>(FooFactory); IFoo foo = null; var ex = Record.Exception(() => foo = c.Resolve<IFoo>()); Assert.Null(ex); Assert.Equal(message, foo.Message); Assert.NotSame(foo, c.Resolve<IFoo>()); } } [Fact] public void FactoryCreatesSingletonTypeWithoutContainerProvider() { lock (testLock) { var c = CreateContainer(); var message = "expected"; c.RegisterSingleton<IFoo>(FooFactory); IFoo foo = null; var ex = Record.Exception(() => foo = c.Resolve<IFoo>()); Assert.Null(ex); Assert.Equal(message, foo.Message); Assert.Same(foo, c.Resolve<IFoo>()); } } //[Fact] //public void FactoryCreatesTransientTypeWithServiceProvider() //{ // lock(testLock) // { // var c = CreateContainer(); // var expectedMessage = "constructed with IServiceProvider"; // c.Register(typeof(IBar), BarFactoryWithIServiceProvider); // c.RegisterInstance<IFoo>(new Foo { Message = expectedMessage }); // IBar bar = null; // var ex = Record.Exception(() => bar = c.Resolve<IBar>()); // Assert.Null(ex); // Assert.False(string.IsNullOrWhiteSpace(bar.Foo.Message)); // Assert.Equal(expectedMessage, bar.Foo.Message); // Assert.NotSame(bar, c.Resolve<IBar>()); // } //} //[Fact] //public void FactoryCreatesTransientTypeWithServiceProviderFromGeneric() //{ // lock(testLock) // { // var c = CreateContainer(); // var expectedMessage = "constructed with IServiceProvider"; // c.Register<IBar>(BarFactoryWithIServiceProvider); // c.RegisterInstance<IFoo>(new Foo { Message = expectedMessage }); // IBar bar = null; // var ex = Record.Exception(() => bar = c.Resolve<IBar>()); // Assert.Null(ex); // Assert.False(string.IsNullOrWhiteSpace(bar.Foo.Message)); // Assert.Equal(expectedMessage, bar.Foo.Message); // Assert.NotSame(bar, c.Resolve<IBar>()); // } //} //[Fact] //public void FactoryCreatesSingletonTypeWithServiceProvider() //{ // lock(testLock) // { // var c = CreateContainer(); // var expectedMessage = "constructed with IServiceProvider"; // c.RegisterSingleton(typeof(IBar), BarFactoryWithIServiceProvider); // c.RegisterInstance<IFoo>(new Foo { Message = expectedMessage }); // IBar bar = null; // var ex = Record.Exception(() => bar = c.Resolve<IBar>()); // Assert.Null(ex); // Assert.False(string.IsNullOrWhiteSpace(bar.Foo.Message)); // Assert.Equal(expectedMessage, bar.Foo.Message); // Assert.Same(bar, c.Resolve<IBar>()); // } //} //[Fact] //public void FactoryCreatesSingletonTypeWithServiceProviderFromGeneric() //{ // lock(testLock) // { // try // { // var c = CreateContainer(); // Assert.NotNull(c); // var expectedMessage = "constructed with IServiceProvider"; // c.RegisterSingleton<IBar>(BarFactoryWithIServiceProvider); // c.RegisterInstance<IFoo>(new Foo { Message = expectedMessage }); // IBar bar = null; // var ex = Record.Exception(() => bar = c.Resolve<IBar>()); // Assert.Null(ex); // Assert.False(string.IsNullOrWhiteSpace(bar.Foo.Message)); // Assert.Equal(expectedMessage, bar.Foo.Message); // Assert.Same(bar, c.Resolve<IBar>()); // } // catch (Exception ex) // { // _testOutputHelper.WriteLine(ex.ToString()); // throw; // } // } //} [Fact] public void FactoryCreatesTransientTypeWithContainerProvider() { lock (testLock) { var c = CreateContainer(); var expectedMessage = "constructed with IContainerProvider"; c.Register(typeof(IBar), BarFactoryWithIContainerProvider); c.RegisterSingleton<IFoo, Foo>(); IBar bar = null; var ex = Record.Exception(() => bar = c.Resolve<IBar>()); Assert.Null(ex); Assert.IsType<Bar>(bar); Assert.Equal(expectedMessage, ((Bar)bar).Message); Assert.Same(c.Resolve<IFoo>(), bar.Foo); Assert.NotSame(c.Resolve<IBar>(), bar); } } [Fact] public void FactoryCreatesTransientTypeWithContainerProviderWithGeneric() { lock (testLock) { var c = CreateContainer(); var expectedMessage = "constructed with IContainerProvider"; c.Register<IBar>(BarFactoryWithIContainerProvider); c.RegisterSingleton<IFoo, Foo>(); IBar bar = null; var ex = Record.Exception(() => bar = c.Resolve<IBar>()); Assert.Null(ex); Assert.IsType<Bar>(bar); Assert.Equal(expectedMessage, ((Bar)bar).Message); Assert.Same(c.Resolve<IFoo>(), bar.Foo); Assert.NotSame(c.Resolve<IBar>(), bar); } } [Fact] public void FactoryCreatesSingletonTypeWithContainerProvider() { lock (testLock) { var c = CreateContainer(); var expectedMessage = "constructed with IContainerProvider"; c.RegisterSingleton(typeof(IBar), BarFactoryWithIContainerProvider); c.RegisterSingleton<IFoo, Foo>(); IBar bar = null; var ex = Record.Exception(() => bar = c.Resolve<IBar>()); Assert.Null(ex); Assert.IsType<Bar>(bar); Assert.Equal(expectedMessage, ((Bar)bar).Message); Assert.Same(c.Resolve<IFoo>(), bar.Foo); Assert.Same(c.Resolve<IBar>(), bar); } } [Fact] public void FactoryCreatesSingletonTypeWithContainerProviderWithGeneric() { lock (testLock) { var c = CreateContainer(); var expectedMessage = "constructed with IContainerProvider"; c.RegisterSingleton<IBar>(BarFactoryWithIContainerProvider); c.RegisterSingleton<IFoo, Foo>(); IBar bar = null; var ex = Record.Exception(() => bar = c.Resolve<IBar>()); Assert.Null(ex); Assert.IsType<Bar>(bar); Assert.Equal(expectedMessage, ((Bar)bar).Message); Assert.Same(c.Resolve<IFoo>(), bar.Foo); Assert.Same(c.Resolve<IBar>(), bar); } } [Fact] public void ResolveWithSpecifiedTypeOverridesRegistration() { lock (testLock) { var c = CreateContainer(); c.Register<IBar, Bar>(); var foo = new Foo { Message = "This shouldn't be resolved" }; c.RegisterInstance<IFoo>(foo); var overrideFoo = new Foo { Message = "We expect this one" }; Assert.Same(foo, c.Resolve<IFoo>()); var bar = c.Resolve<IBar>((typeof(IFoo), overrideFoo)); Assert.Same(overrideFoo, bar.Foo); } } [Fact] public void ResolveNamedInstance() { var genA = new GenericService { Name = "genA" }; var genB = new GenericService { Name = "genB" }; lock (testLock) { var c = CreateContainer(); c.RegisterInstance<IGenericService>(genA, "genA"); c.RegisterInstance<IGenericService>(genB, "genB"); Assert.Same(genA, c.Resolve<IGenericService>("genA")); Assert.Same(genB, c.Resolve<IGenericService>("genB")); } } [Fact] public void ResolveTakesLastIn() { var c = CreateContainer(); c.Register<IGenericService, GenericService>(); c.Register<IGenericService, AltGenericService>(); Assert.IsType<AltGenericService>(c.Resolve<IGenericService>()); } // Unity does not currently support Resolve All #if false [Fact] public void ResolveEnumerableResolvesAll() { var c = CreateContainer(); c.Register<IGenericService, GenericService>(); c.Register<IGenericService, AltGenericService>(); IEnumerable<IGenericService> all = null; var ex = Record.Exception(() => all = c.Resolve<IEnumerable<IGenericService>>()); Assert.Null(ex); Assert.NotNull(all); Assert.NotEmpty(all); Assert.Equal(2, all.Count()); Assert.Contains(all, x => x is GenericService); Assert.Contains(all, x => x is AltGenericService); } #endif public static IFoo FooFactory() => new Foo { Message = "expected" }; public static IBar BarFactoryWithIContainerProvider(IContainerProvider containerProvider) => new Bar(containerProvider.Resolve<IFoo>()) { Message = "constructed with IContainerProvider" }; //public static IBar BarFactoryWithIServiceProvider(IServiceProvider serviceProvider) => // new Bar((IFoo)serviceProvider.GetService(typeof(IFoo))); private static IContainerExtension CreateContainer() { PrismContainerExtension.Reset(); GC.Collect(); return PrismContainerExtension.Current; } } internal class MockListener : TraceListener { public readonly List<string> Messages = new List<string>(); public override void Write(string message) { } public override void WriteLine(string message) { Messages.Add(message); } } }
/************************************************************************************************* * Copyright (c) 2018 Gilles Khouzam * * 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 withou * 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. /*************************************************************************************************/ namespace MagikInfo.YouMailAPI.Tests { using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; [TestClass] public class TranscriptionTests { YouMailService service = YouMailTestService.Service; const int delay = 1000; [TestMethod] public async Task TranscriptionStatus() { var status = await service.GetTranscriptionStatusAsync(); Assert.IsNotNull(status); } [TestMethod] public async Task TranscriptionSetttings() { var settings = await service.GetTranscriptionSettingsAsync(); Assert.IsNotNull(settings); } // This test is flaky, ignore it temporarily [TestMethod, Ignore] public async Task ChangeTranscriptionSettings() { // Use my private account var service = YouMailTestService.MyService; var settings = await service.GetTranscriptionSettingsAsync(); var oldEnabled = settings.Enabled; var newEnabled = !oldEnabled; if (oldEnabled) { await VerifySmsCountAsync(settings, service); } await service.SetTranscriptionSettingAsync(YMST.c_enabled, newEnabled.ToString().ToLower()); await Task.Delay(delay); var settings2 = await service.GetTranscriptionSettingsAsync(); Assert.AreEqual(newEnabled, settings2.Enabled); if (newEnabled) { await VerifySmsCountAsync(settings2, service); } await service.SetTranscriptionSettingAsync(YMST.c_enabled, oldEnabled.ToString().ToLower()); await Task.Delay(delay); var settings3 = await service.GetTranscriptionSettingsAsync(); Assert.AreEqual(oldEnabled, settings3.Enabled); } private static async Task VerifySmsCountAsync(TranscriptionSettings settings, YouMailService service) { var oldCount = settings.SmsCount; int newCount = 0; if (oldCount == 0) { newCount = 3; } await service.SetTranscriptionSettingAsync(YMST.c_smsCount, newCount.ToString()); await Task.Delay(delay); var newSettings = await service.GetTranscriptionSettingsAsync(); Assert.AreEqual(newCount, newSettings.SmsCount); await service.SetTranscriptionSettingAsync(YMST.c_smsCount, oldCount.ToString()); await Task.Delay(delay); var oldSettings = await service.GetTranscriptionSettingsAsync(); Assert.AreEqual(oldCount, oldSettings.SmsCount); } } }
using System; using Nuve.Orthographic; namespace Nuve.Condition { internal static class ConditionFactory { public static ConditionBase Create(string name, string morphemeLocation, string operand, Alphabet alphabet) { switch (name) { case "EndsWithConsonant": return new EndsWithConsonant(morphemeLocation, operand, alphabet); case "EndsWithVowel": return new EndsWithVowel(morphemeLocation, operand, alphabet); case "FirstLetterEquals": return new FirstLetterEquals(morphemeLocation, operand, alphabet); case "LastLetterEquals": return new LastLetterEquals(morphemeLocation, operand, alphabet); case "LastVowelEquals": return new LastVowelEquals(morphemeLocation, operand, alphabet); case "MorphemeEquals": return new MorphemeEquals(morphemeLocation, operand, alphabet); case "MorphemeExists": return new MorphemeExists(morphemeLocation, operand, alphabet); case "MorphemeNotEquals": return new MorphemeNotEquals(morphemeLocation, operand, alphabet); case "MorphemeSequenceEquals": return new MorphemeSequenceEquals(morphemeLocation, operand, alphabet); case "PenultVowelEquals": return new PenultVowelEquals(morphemeLocation, operand, alphabet); case "StartsWithConsonant": return new StartsWithConsonant(morphemeLocation, operand, alphabet); case "StartsWithVowel": return new StartsWithVowel(morphemeLocation, operand, alphabet); case "HasFlags": return new HasLabel(morphemeLocation, operand, alphabet); case "HasNotFlags": return new HasNotLabel(morphemeLocation, operand, alphabet); case "IsLastMorpheme": return new IsLastMorpheme(morphemeLocation, operand, alphabet); default: throw new ArgumentException("Invalid Condition: " + name); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using ATBase.OssCore.Domain; namespace ATBase.OssProvider.AliOss.Util { internal class AliOssUtil { public static void EnsureObjectKey(ref String objectKey) { if (!String.IsNullOrWhiteSpace(objectKey)) { objectKey = HttpUtility.UrlDecode(objectKey); objectKey = objectKey.TrimStart('~', '/').Replace('\\', '/'); } } public static void EnsureObjectKeys(ref String[] objectKeys) { if (objectKeys != null && objectKeys.Length > 0) { for (var i = 0; i < objectKeys.Length; i++) { EnsureObjectKey(ref objectKeys[i]); } } } public static void EnsureXOssObject(XOssObject obj) { if (obj != null && !String.IsNullOrWhiteSpace(obj.ObjectKey)) { obj.ObjectKey = HttpUtility.UrlDecode(obj.ObjectKey); obj.ObjectKey = obj.ObjectKey.TrimStart('~', '/').Replace('\\', '/'); } } public static void EnsureXOssObjects(IEnumerable<XOssObject> objects) { if (objects != null) { foreach (var obj in objects) { EnsureXOssObject(obj); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; using Photon.Realtime; using System.Linq; public class NetworkManager : MonoBehaviourPunCallbacks { public static NetworkManager Instance = null; //Photon Settings [SerializeField] private bool isConnected = false; public delegate void OnPhotonConnectedToMaster(); public static OnPhotonConnectedToMaster onPhotonConnectedToMaster; public delegate void OnMyPlayerJoinedRoom(); public static OnMyPlayerJoinedRoom onMyPlayerJoinedRoom; private void Awake() { if(Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(this); } PhotonNetwork.ConnectUsingSettings(); } public override void OnEnable() { base.OnEnable(); onPhotonConnectedToMaster += OnPhotonNetworkGotConnected; } public override void OnDisable() { base.OnDisable(); onPhotonConnectedToMaster -= OnPhotonNetworkGotConnected; } private void OnPhotonNetworkGotConnected() { isConnected = true; PhotonNetwork.AutomaticallySyncScene = true; } #region Public Methods public bool IsConnected() { return isConnected; } public int GetPlayerCount() { return PhotonNetwork.CurrentRoom.PlayerCount; } public bool RoomExists(string roomName) { if (!IsConnected()) { return true; } return PhotonNetwork.GetCustomRoomList(TypedLobby.Default, "C0=" + roomName); } public List<Player> GetCurrentRoomPlayers() { return PhotonNetwork.CurrentRoom.Players.Values.ToList(); } public bool IsMasterClient() { return PhotonNetwork.IsMasterClient; } public void CreateRoom(string roomName) { PhotonNetwork.CreateRoom(roomName); } public void CreateRoom(string roomName, int playerCount) { RoomOptions roomOptions = new RoomOptions { MaxPlayers = (byte)playerCount }; PhotonNetwork.CreateRoom(roomName, roomOptions); } public void JoinRoom(string roomName) { PhotonNetwork.JoinRoom(roomName); } #endregion #region Photon Callbacks public override void OnConnectedToMaster() { Debug.Log("OnConnectedToMaster"); onPhotonConnectedToMaster?.Invoke(); } public override void OnCreatedRoom() { Debug.Log("OnCreatedRoom: " + PhotonNetwork.CurrentRoom.Name); } public override void OnJoinedRoom() { Debug.Log("OnJoinedRoom: " + PhotonNetwork.CurrentRoom.Name); onMyPlayerJoinedRoom?.Invoke(); } public override void OnPlayerEnteredRoom(Player newPlayer) { Debug.Log("OnPlayerEnteredRoom: " + PhotonNetwork.CurrentRoom.Name + ", " + newPlayer.NickName); } #endregion }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIManager : MonoSingleton<UIManager> { /* This script provides behaviour for UI.*/ public Color blueMountains; [Header("UI Screens.")] [Header("Main menu.")] public GameObject mainMenuScreen; public Button start; public Button backgroundsBtn; public Button settingsBtn; public Button aboutBtn; public Button exitBtn; [Header("Pause menu.")] public GameObject pauseMenuScreen; public Button resumeBtn; public Button restartBtn; public Button mainMenuBtn; public Button exitBtn2; [Header("Gameplay screen.")] public GameObject gameplayScreen; public Button pauseBtn; [Header("Backgrounds screen.")] public GameObject backgroundsScreen; [Header("Settings screen.")] public GameObject settingsScreen; [Header("About screen.")] public GameObject aboutScreen; [Header("Game over screen.")] public GameObject gameOverScreen; public enum UIModes { Start = 0, MainMenu = 1, Pause = 2, Resume = 3, Backgrounds = 4, Settings = 5, About = 6, GameOver = 7, DisableSecondary = 8, Exit = 9 } void Start () { //assigning main menu screen buttons start.onClick.AddListener(() => SwitchUIMode(0)); backgroundsBtn.onClick.AddListener(() => SwitchUIMode(4)); settingsBtn.onClick.AddListener(() => SwitchUIMode(5)); aboutBtn.onClick.AddListener(() => SwitchUIMode(6)); //assigning pause screen menu buttons resumeBtn.onClick.AddListener(() => SwitchUIMode(3)); mainMenuBtn.onClick.AddListener(() => SwitchUIMode(1)); //assigning gameplay screen buttons pauseBtn.onClick.AddListener(() => SwitchUIMode(2)); //assigning backgrounds screen buttons //assigning settings screen buttons //assigning about screen buttons //assigning game over screen buttons } void Update () { } public void SwitchUIMode(int uiMode) { UIModes selectedMode = (UIModes)uiMode; switch (selectedMode) { case UIModes.Start: GameManager.Instance.StartGame(); LevelGenerator.Instance.GenerateLevel(); LevelGenerator.Instance.GenerateBottomPlatforms(); gameplayScreen.SetActive(true); pauseMenuScreen.SetActive(false); mainMenuScreen.SetActive(false); break; case UIModes.MainMenu: GameManager.Instance.FinishGame(); GameManager.Instance.ResumeGame(); mainMenuScreen.SetActive(true); gameplayScreen.SetActive(false); pauseMenuScreen.SetActive(false); break; case UIModes.Pause: GameManager.Instance.PauseGame(); pauseMenuScreen.SetActive(true); break; case UIModes.Resume: GameManager.Instance.ResumeGame(); pauseMenuScreen.SetActive(false); break; case UIModes.Backgrounds: backgroundsScreen.SetActive(true); break; case UIModes.Settings: settingsScreen.SetActive(true); break; case UIModes.About: aboutScreen.SetActive(true); break; case UIModes.GameOver: gameOverScreen.SetActive(true); break; case UIModes.DisableSecondary: backgroundsScreen.SetActive(false); settingsScreen.SetActive(false); gameOverScreen.SetActive(false); aboutScreen.SetActive(false); break; case UIModes.Exit: Application.Quit(); break; } } }
using LanguageExt; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using static LanguageExt.Prelude; namespace LanguageExtTests { public class CompositionTests { private readonly Func<string> _f; private readonly Func<string, string> _g; private readonly Func<string, int> _h; public CompositionTests() { _f = () => "Bob"; _g = (string name) => $"Hello, {name}"; _h = (string s) => s.Length; } [Fact] public void Sanity() { string expected = "Hello, Bob"; Assert.Equal(_g(_f()), expected); Assert.Equal(_h(_g(_f())), expected.Length); } [Fact] public void ComposeFuncWithNoArgFunc() { Assert.Equal(_g.Compose(_f)(), _g(_f())); } [Fact] public void BackComposeNoArgFuncWithFunc() { Assert.Equal(_f.BackCompose(_g)(), _g(_f())); } [Fact] public void ComposeActionWithNoArgFunc() { string result; var g = act((string name) => { result = _g(name); }); result = null; g.Compose(_f)(); Assert.Equal(result, _g(_f())); } [Fact] public void BackComposeNoArgFuncWithAction() { string result; var g = act((string name) => { result = _g(name); }); result = null; _f.BackCompose(g)(); Assert.Equal(result, _g(_f())); } [Fact] public void ComposeFuncWithFunc() { Assert.Equal(_h.Compose(_g)(_f()), _h(_g(_f()))); } [Fact] public void BackComposeFuncWithFunc() { Assert.Equal(_g.BackCompose(_h)(_f()), _h(_g(_f()))); } [Fact] public void ComposeActionWithFunc() { int? result; var h = act((string s) => { result = _h(s); }); result = null; h.Compose(_g)(_f()); Assert.Equal(result, _h(_g(_f()))); } [Fact] public void BackComposeFuncWithAction() { int? result; var h = act((string s) => { result = _h(s); }); result = null; _g.BackCompose(h)(_f()); Assert.Equal(result, _h(_g(_f()))); } } }
using System.Text; namespace NsqClient.Commands { internal class SubscribeCommand : ICommand { private string template = "SUB {0} {1}\n"; private readonly string topic; private readonly string channel; public SubscribeCommand(string topic, string channel) { this.topic = topic; this.channel = channel; } public byte[] ToBytes() { string payload = string.Format(this.template, this.topic, this.channel); return Encoding.ASCII.GetBytes(payload); } } }
[EnableCors(origins: "http://www.contoso.com,http://www.example.com", headers: "*", methods: "*")]
[TrackColorAttribute] // RVA: 0x145060 Offset: 0x145161 VA: 0x145060 [TrackClipTypeAttribute] // RVA: 0x145060 Offset: 0x145161 VA: 0x145060 [TrackBindingTypeAttribute] // RVA: 0x145060 Offset: 0x145161 VA: 0x145060 public class TransformTweenTrack : TrackAsset // TypeDefIndex: 6098 { // Methods // RVA: 0x1D2D1D0 Offset: 0x1D2D2D1 VA: 0x1D2D1D0 Slot: 24 public override Playable CreateTrackMixer(PlayableGraph graph, GameObject go, int inputCount) { } // RVA: 0x1D2D270 Offset: 0x1D2D371 VA: 0x1D2D270 Slot: 29 public override void GatherProperties(PlayableDirector director, IPropertyCollector driver) { } // RVA: 0x1D2D280 Offset: 0x1D2D381 VA: 0x1D2D280 public void .ctor() { } }
/* * DarkHouse * Horror Exploration Game * Copyright (c) 2019 Mohammad Najmi */ namespace DarkHouse { /// <summary> /// IWindow Interface /// </summary> /// <remarks>Defines a window</remarks> public interface IWindow : IIdentity, ILockable, IOpenable, IShape3D { } }
using UnityEngine; using System.Collections; using System.Collections.Generic; [RequireComponent (typeof (SynthControl))] public class TouchKey : MonoBehaviour { public Camera gameCam; [Range(0.003f, 3.0f)] public float env_atk = 1.0f; [Range(0.003f, 3.0f)] public float env_rel = 1.0f; [Range(24,48)] public int scale = 24; public LayerMask touchInputMask; private GameObject[] touchesOld; private int lastNoteDegree = -1; private List<GameObject> touchList = new List<GameObject>(); private Lope envelope; private RaycastHit2D hit; private string lastNoteDegreeString; private SynthControl synth; private GameObject recipient; public NReverb reverb; public void Start() { synth = GetComponent<SynthControl>(); envelope = GetComponent<Lope>(); envelope.sustain = false; reverb = GetComponent<NReverb> (); // barTexture = new Texture2D(8, 8); // noise = FindObjectOfType(NoiseController); // seq = GetComponent.<AutoSequencer>(); // SYNTH.LOPE.SUSTAIN = false; } public void Update() { // #if UNITY_EDITOR if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0)) { touchesOld = new GameObject[touchList.Count]; touchList.CopyTo(touchesOld); touchList.Clear(); RaycastHit2D hit = Physics2D.Raycast(gameCam.ScreenToWorldPoint (Input.mousePosition), Vector2.zero); GameObject recipient = hit.transform.gameObject; var tDetails = recipient.GetComponent<TileDetails>(); reverb.wetMix = hit.transform.position.x / 24; Debug.Log (recipient.gameObject.name + "hit"); if(hit.collider!=null) { touchList.Add(recipient); // Debug.Log (recipient.name); //lastNoteDegreeString = recipient.name; //lastNoteDegree = int.Parse(lastNoteDegreeString); if (Input.GetMouseButtonDown(0)) { lastNoteDegree = scale + (int)tDetails.note; envelope = synth.KeyOn(lastNoteDegree, envelope); tDetails.OnTouchDown(); // recipient.SendMessage("OnTouchDown",hit.point, // SendMessageOptions.DontRequireReceiver); } if (Input.GetMouseButtonUp(0)) { envelope.KeyOff(); tDetails.OnTouchExit(); //recipient.SendMessage("OnTouchUp",hit.point, // SendMessageOptions.DontRequireReceiver); } if (Input.GetMouseButton(0)) { lastNoteDegree = scale + (int)tDetails.note; envelope = synth.KeyOn(lastNoteDegree, envelope); tDetails.OnTouchStay(); //recipient.SendMessage("OnTouchStay",hit.point, // SendMessageOptions.DontRequireReceiver); } } foreach (GameObject g in touchesOld) { if (!touchList.Contains(g)) { g.SendMessage("OnTouchExit",hit.point, SendMessageOptions.DontRequireReceiver); } } } // #endif envelope.attack = env_atk; envelope.release = env_rel; /* if (Input.touchCount > 0){ // touchesOld = new GameObject[touchList.Count]; // touchList.CopyTo(touchesOld); // touchList.Clear(); // foreach (Touch touch in Input.touches) { // var touch = Input.touches; for (int i = 0; i < Input.touchCount; i++) { Touch touch = Input.GetTouch(i); RaycastHit2D hit = Physics2D.Raycast(gameCam.ScreenToWorldPoint (Input.mousePosition), Vector2.zero); reverb.wetMix = hit.transform.position.x / 30; if(hit.collider!=null) { GameObject recipient = hit.transform.gameObject; var tDetails = recipient.GetComponent<TileDetails>(); touchList.Add(recipient); //Debug.Log (recipient.name); //lastNoteDegreeString = recipient.name; //lastNoteDegree = int.Parse(lastNoteDegreeString); if (touch.phase == TouchPhase.Began) { lastNoteDegree = scale + (int)recipient.GetComponent<TileDetails>().note; envelope = synth.KeyOn(lastNoteDegree, envelope); tDetails.OnTouchDown(); // recipient.SendMessage("OnTouchDown",hit.point, // SendMessageOptions.DontRequireReceiver); } if (touch.phase == TouchPhase.Moved) { lastNoteDegree = scale + (int)tDetails.note; envelope = synth.KeyOn(lastNoteDegree, envelope); // recipient.GetComponent<TileDetails>().OnTouchDown(); //lastNoteDegree = recipient.name; //noteRange * (int)Input.mousePosition.y / (int)Screen.height; } if (touch.phase == TouchPhase.Ended) { envelope.KeyOff(); tDetails.OnTouchExit(); // recipient.SendMessage("OnTouchUp",hit.point, // SendMessageOptions.DontRequireReceiver); } if (touch.phase == TouchPhase.Stationary) { lastNoteDegree = scale + (int)recipient.GetComponent<TileDetails>().note; envelope = synth.KeyOn(lastNoteDegree, envelope); tDetails.OnTouchStay(); // recipient.SendMessage("OnTouchStay",hit.point, // SendMessageOptions.DontRequireReceiver); } if (touch.phase == TouchPhase.Canceled) { envelope.KeyOff(); tDetails.OnTouchExit(); // recipient.SendMessage("OnTouchExit",hit.point, // SendMessageOptions.DontRequireReceiver); } } } // for/ for each each closeing bracket foreach (GameObject g in touchesOld) { if (!touchList.Contains(g)) { g.SendMessage("OnTouchExit",hit.point, SendMessageOptions.DontRequireReceiver); } } } */ } }
using Xunit; using static Dommel.DommelMapper; namespace Dommel.Tests { public class AnyTests { private static readonly ISqlBuilder SqlBuilder = new SqlServerSqlBuilder(); [Fact] public void GeneratesAnyAllSql() { var sql = BuildAnyAllSql(SqlBuilder, typeof(Foo)); Assert.Equal($"select 1 from [Foos] {SqlBuilder.LimitClause(1)}", sql); } [Fact] public void GeneratesAnySql() { var sql = BuildAnySql<Foo>(SqlBuilder, x => x.Bar == "Baz", out var parameters); Assert.Equal($"select 1 from [Foos] where ([Bar] = @p1) {SqlBuilder.LimitClause(1)}", sql); Assert.Single(parameters.ParameterNames); } private class Foo { public string? Bar { get; set; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using com.pacifica.slot.core; namespace com.pacifica.slot.objects{ /*! \brief * * WHAT IT DOES: * - * * REQUIREMENTS: * - */ public class LineNumbers : MonoBehaviour { public List<LineNumberButton> linenumbers; SlotModel slotModel; public void UpdateActiveLines(int ActiveLines){ for(int i=0; i<linenumbers.Count; i++){ if(i<ActiveLines){ linenumbers[i].OnEnable(); }else{ linenumbers[i].OnDeactivate(); } } } public void DisableAllButtons(){ for (int i=0; i<linenumbers.Count; i++) { linenumbers[i].OnDisable(); } } } }
using UNKO.Utils; namespace UNKO.ManageResource { [System.Serializable] public class EffectPlayCommand : ResourcePlayCommandBase<IEffectPlayer> { // NOTE inspector 노출용 - 유니티 에디터는 제네릭 클래스를 인스펙터에 노출을 못하기 때문에 [System.Serializable] public class Pool : SimplePool<EffectPlayCommand> { public Pool(EffectPlayCommand originItem) : base(originItem) { } public Pool(System.Func<EffectPlayCommand> onCreateInstance) : base(onCreateInstance) { } } public string GetEffectID() => ResourcePlayer.GetEffectID(); } }
using System; using System.Collections.Generic; namespace Discord { /// <summary> /// Represents a message object. /// </summary> public interface IMessage : ISnowflakeEntity, IDeletable { /// <summary> /// Gets the type of this system message. /// </summary> MessageType Type { get; } /// <summary> /// Gets the source type of this message. /// </summary> MessageSource Source { get; } /// <summary> /// Gets the value that indicates whether this message was meant to be read-aloud by Discord. /// </summary> /// <returns> /// <c>true</c> if this message was sent as a text-to-speech message; otherwise <c>false</c>. /// </returns> bool IsTTS { get; } /// <summary> /// Gets the value that indicates whether this message is pinned. /// </summary> /// <returns> /// <c>true</c> if this message was added to its channel's pinned messages; otherwise <c>false</c>. /// </returns> bool IsPinned { get; } /// <summary> /// Gets the content for this message. /// </summary> /// <returns> /// A string that contains the body of the message; note that this field may be empty if there is an embed. /// </returns> string Content { get; } /// <summary> /// Gets the time this message was sent. /// </summary> /// <returns> /// Time of when the message was sent. /// </returns> DateTimeOffset Timestamp { get; } /// <summary> /// Gets the time of this message's last edit. /// </summary> /// <returns> /// Time of when the message was last edited; <c>null</c> when the message is never edited. /// </returns> DateTimeOffset? EditedTimestamp { get; } /// <summary> /// Gets the source channel of the message. /// </summary> IMessageChannel Channel { get; } /// <summary> /// Gets the author of this message. /// </summary> IUser Author { get; } /// <summary> /// Returns all attachments included in this message. /// </summary> /// <returns> /// A read-only collection of attachments. /// </returns> IReadOnlyCollection<IAttachment> Attachments { get; } /// <summary> /// Returns all embeds included in this message. /// </summary> /// <returns> /// A read-only collection of embed objects. /// </returns> IReadOnlyCollection<IEmbed> Embeds { get; } /// <summary> /// Returns all tags included in this message's content. /// </summary> IReadOnlyCollection<ITag> Tags { get; } /// <summary> /// Returns the IDs of channels mentioned in this message. /// </summary> /// <returns> /// A read-only collection of channel IDs. /// </returns> IReadOnlyCollection<ulong> MentionedChannelIds { get; } /// <summary> /// Returns the IDs of roles mentioned in this message. /// </summary> /// <returns> /// A read-only collection of role IDs. /// </returns> IReadOnlyCollection<ulong> MentionedRoleIds { get; } /// <summary> /// Returns the IDs of users mentioned in this message. /// </summary> /// <returns> /// A read-only collection of user IDs. /// </returns> IReadOnlyCollection<ulong> MentionedUserIds { get; } } }
// Copyright Finbuckle LLC, Andrew White, and Contributors. // Refer to the solution LICENSE file for more inforation. using System; namespace Finbuckle.MultiTenant { /// <summary> /// Marks a class as multitenant when used with a database context /// derived from MultiTenantDbContext or MultiTenantIdentityDbContext. /// </summary> [AttributeUsage(AttributeTargets.Class, Inherited = false)] public class MultiTenantAttribute : Attribute { } }
using System.ComponentModel.DataAnnotations; namespace Cofoundry.Web.Admin.Internal { public class CompleteAccountRecoveryViewModel { /// <summary> /// The value to set as the new account password. The password will go through /// additional validation depending on the password policy configuration. /// </summary> [Required] [Display(Name = "New password")] [DataType(DataType.Password)] public string NewPassword { get; set; } /// <summary> /// The token used to verify the request. /// </summary> [Required] [Display(Name = "Confirm new password")] [DataType(DataType.Password)] [Compare(nameof(NewPassword), ErrorMessage = "Password does not match")] public string ConfirmNewPassword { get; set; } } }
using static TNoodle.Puzzles.Puzzle; namespace TNoodle.Puzzles { public class PuzzleStateAndGenerator { public PuzzleStateAndGenerator(PuzzleState state, string generator) { State = state; Generator = generator; } public PuzzleState State { get; } public string Generator { get; } } }
// // ContainerRegistrationConfigElement.cs // // Copyright 2018 Craig Fowler et al // // 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. // // For further copyright info, including a complete author/contributor // list, please refer to the file NOTICE.txt #if !BODI_LIMITEDRUNTIME && !BODI_DISABLECONFIGFILESUPPORT using System; using System.Configuration; namespace BoDi { /// <summary> /// A configuration element representing a single service registration. /// </summary> public class ContainerRegistrationConfigElement : ConfigurationElement { const string ServiceType = "as", ImplementationType = "type", RegistrationName = "name"; /// <summary> /// Gets or sets the interface/service/component type registered by this element. /// </summary> /// <value>The interface.</value> [ConfigurationProperty(ServiceType, IsRequired = true)] public string Interface { get { return (string) this[ServiceType]; } set { this[ServiceType] = value; } } /// <summary> /// Gets or sets the concrete implementation type for this element. /// </summary> /// <value>The implementation.</value> [ConfigurationProperty(ImplementationType, IsRequired = true)] public string Implementation { get { return (string) this[ImplementationType]; } set { this[ImplementationType] = value; } } /// <summary> /// Gets or sets an optional registration name for this element. /// </summary> /// <value>The name.</value> [ConfigurationProperty(RegistrationName, IsRequired = false, DefaultValue = null)] public string Name { get { return (string) this[RegistrationName]; } set { this[RegistrationName] = value; } } } } #endif
using System.Text.Json.Serialization; namespace SimpleFormsService.Domain.Entities.Base; public interface IEntityBase { Guid Id { get; } } public abstract class EntityBase : IEntityBase { protected EntityBase(Guid id) { if (id == default) throw new ArgumentNullException(nameof(id)); Id = id; } [JsonIgnore] public Guid Id { get; set; } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using AgentHeisenbug.QuickFixes; namespace AgentHeisenbug.Tests.Of.QuickFixes { [TestFixture] public class MakeFieldReadOnlyFixTests : HeisenbugQuickFixTestBase<MakeFieldReadOnlyFix> { [TestCase("ReadOnlyClass_Simple.cs")] [TestCase("ThreadSafeClass_Simple.cs")] public void Test(string fileName) { DoTestFiles(fileName); } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace Gallio.Common.Splash.Internal { /// <summary> /// Internal structure that maps a visual line onto a particular range of runs /// within a paragraph and includes the character position of required line breaks. /// </summary> [StructLayout(LayoutKind.Sequential)] internal struct ScriptLine { /// <summary> /// The absolute vertical offset of the line in the document when rendered. /// </summary> public int Y; /// <summary> /// The absolute horizontal offset of the line in the document when rendered. /// </summary> public int X; /// <summary> /// The height of the line. /// </summary> public int Height; /// <summary> /// The descent height of the line (below text baseline). /// </summary> public int Descent; /// <summary> /// The ascent height of the line (above text baseline). /// </summary> public int Ascent { get { return Height - Descent; } } /// <summary> /// The index of the paragraph that appears on the line. /// </summary> public int ParagraphIndex; /// <summary> /// The index of the paragraph's first script run that appears on the line. /// </summary> public int ScriptRunIndex; /// <summary> /// The number of script runs that appear on the line. /// </summary> public int ScriptRunCount; /// <summary> /// The number of leading chars in the first script run to truncate due to word wrap. /// </summary> public int TruncatedLeadingCharsCount; /// <summary> /// The number of trailing chars in the last script run to truncate due to word wrap. /// </summary> public int TruncatedTrailingCharsCount; public void Initialize(int paragraphIndex, int scriptRunIndex, int y) { ParagraphIndex = paragraphIndex; ScriptRunIndex = scriptRunIndex; Y = y; X = 0; Height = 0; Descent = 0; ScriptRunCount = 0; TruncatedLeadingCharsCount = 0; TruncatedTrailingCharsCount = 0; } } }
using System.Linq; namespace Songhay.Extensions { /// <summary> /// Extensions of <see cref="string"/>. /// </summary> public static partial class StringExtensions { /// <summary> /// Converts the <see cref="string"/> into a numeric format for parsing. /// </summary> /// <param name="input">The input.</param> /// <returns> /// Returns a numeric string ready for integer or float parsing. /// </returns> public static string ToNumericString(this string input) { return input.ToNumericString("0"); } /// <summary> /// Converts the <see cref="string"/> into a numeric format for parsing. /// </summary> /// <param name="input">The input.</param> /// <param name="defaultValue">The default value ("0" by default).</param> /// <returns> /// Returns a numeric string ready for integer or float parsing. /// </returns> public static string ToNumericString(this string input, string defaultValue) { if(string.IsNullOrWhiteSpace(input)) return defaultValue; if(string.IsNullOrWhiteSpace(input)) return defaultValue; return new string(input.Trim().Where(i => char.IsDigit(i) || i.Equals('.')).ToArray()); } } }
// // Attribute to mark properties as transient, so that we don't keep // a managed reference to them more than absolutely required. // // Copyright 2013 Xamarin Inc // // Authors: // Rolf Bjarne Kvinge <rolf@xamarin.com> // using System; namespace ObjCRuntime { [AttributeUsage (AttributeTargets.Parameter, AllowMultiple=false)] #if XAMCORE_2_0 sealed #endif public class TransientAttribute : Attribute { } }
using ControllerLib.Driver; using System; namespace ControllerLib.Input { public enum BatteryType { Disconnected = 0, Wired = 1, Alkaline = 2, Nimh = 3, Unknown = 4 } public enum BatteryLevel { Empty = 0, Low = 1, Medium = 2, Full = 3 } public class BatteryState : IEquatable<BatteryState> { public BatteryState(XINPUT_BATTERY_INFORMATION batteryInformation) { Type = Helper.EnumParse<BatteryType>(batteryInformation.BatteryType.ToString()); Level = Helper.EnumParse<BatteryLevel>(batteryInformation.BatteryLevel.ToString()); } public BatteryType Type { get; private set; } public BatteryLevel Level { get; private set; } public Boolean Equals(BatteryState other) { return this.Type == other?.Type && this.Level == other?.Level; } public override Boolean Equals(Object obj) { return this.Equals(obj as BatteryState); } public override Int32 GetHashCode() { return this.Type.GetHashCode() ^ this.Level.GetHashCode(); } } }
// ***************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // ***************************************************************** using System.Collections.Generic; using System.IO; namespace MBF.IO { /// <summary> /// This is an abstract class that provides some basic operations common to sequence /// formatters. It is meant to be used as the base class for formatter implementations /// if the implementer wants to make use of default behavior. /// </summary> public abstract class BasicSequenceFormatter : ISequenceFormatter { #region Constructors /// <summary> /// Default constructor. /// </summary> public BasicSequenceFormatter() { } #endregion #region ISequenceFormatter Members /// <summary> /// Gets the name of the formatter. Intended to be filled in /// by classes deriving from BasicSequenceFormatter class /// with the exact name of the formatter type. /// </summary> public abstract string Name { get; } /// <summary> /// Gets the description of the formatter. Intended to be filled in /// by classes deriving from BasicSequenceFormatter class /// with the exact details of the formatter. /// </summary> public abstract string Description { get; } /// <summary> /// Gets the filetypes supported by the formatter. Intended to be filled in /// by classes deriving from BasicSequenceFormatter class /// with the exact details of the filetypes supported. /// </summary> public abstract string FileTypes { get; } /// <summary> /// Writes an ISequence to the location specified by the writer. /// </summary> /// <param name="sequence">The sequence to format.</param> /// <param name="writer">The TextWriter used to write the formatted sequence text.</param> public abstract void Format(ISequence sequence, TextWriter writer); /// <summary> /// Writes an ISequence to the specified file. /// </summary> /// <param name="sequence">The sequence to format.</param> /// <param name="filename">The name of the file to write the formatted sequence text.</param> public void Format(ISequence sequence, string filename) { TextWriter writer = null; try { writer = new StreamWriter(filename); Format(sequence, writer); } catch { // If format failed, remove the created file. if (File.Exists(filename)) { if (writer != null) { writer.Close(); } File.Delete(filename); } throw; } finally { if (writer != null) { writer.Dispose(); } } } /// <summary> /// Write a collection of ISequences to a file. /// </summary> /// <remarks> /// This method should be overridden by any formatters that need to format file-scope /// metadata that applies to all of the sequences in the file. /// </remarks> /// <param name="sequences">The sequences to write</param> /// <param name="writer">the TextWriter</param> public virtual void Format(ICollection<ISequence> sequences, TextWriter writer) { foreach (ISequence sequence in sequences) { Format(sequence, writer); } } /// <summary> /// Write a collection of ISequences to a file. /// </summary> /// <param name="sequences">The sequences to write.</param> /// <param name="filename">The name of the file to write the formatted sequences to.</param> public void Format(ICollection<ISequence> sequences, string filename) { TextWriter writer = null; try { writer = new StreamWriter(filename); Format(sequences, writer); } catch { // If format failed, remove the created file. if (File.Exists(filename)) { if (writer != null) { writer.Close(); } File.Delete(filename); } throw; } finally { if (writer != null) { writer.Dispose(); } } } /// <summary> /// Converts an ISequence to a formatted text. /// </summary> /// <param name="sequence">The sequence to format.</param> /// <returns>A string of the formatted text.</returns> public string FormatString(ISequence sequence) { using (TextWriter writer = new StringWriter()) { Format(sequence, writer); return writer.ToString(); } } #endregion } }
using Bb.Sdk.Decompiler.IlParser; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace Bb.Sdk.Decompiler.Methods { public sealed class MethodBody { readonly internal MethodDefinition method; //internal ParameterDefinition this_parameter; internal int max_stack_size; internal int code_size; internal bool init_locals; //internal MetadataToken local_var_token; internal Collection<ILInstruction> instructions; //internal Collection<ExceptionHandler> exceptions; //internal Collection<VariableDefinition> variables; public MethodDefinition Method { get { return method; } } public int MaxStackSize { get { return max_stack_size; } set { max_stack_size = value; } } public int CodeSize { get { return code_size; } } public bool InitLocals { get { return init_locals; } set { init_locals = value; } } //public MetadataToken LocalVarToken //{ // get { return local_var_token; } // set { local_var_token = value; } //} //public Collection<ILInstruction> Instructions //{ // get { return instructions ?? (instructions = new InstructionCollection(method)); } //} //public bool HasExceptionHandlers //{ // get { return !exceptions.IsNullOrEmpty(); } //} //public Collection<ExceptionHandler> ExceptionHandlers //{ // get { return exceptions ?? (exceptions = new Collection<ExceptionHandler>()); } //} //public bool HasVariables //{ // get { return !variables.IsNullOrEmpty(); } //} //public Collection<VariableDefinition> Variables //{ // get { return variables ?? (variables = new VariableDefinitionCollection()); } //} //public ParameterDefinition ThisParameter //{ // get // { // if (method == null || method.DeclaringType == null) // throw new NotSupportedException(); // if (!method.HasThis) // return null; // if (this_parameter == null) // Interlocked.CompareExchange(ref this_parameter, CreateThisParameter(method), null); // return this_parameter; // } //} //static ParameterDefinition CreateThisParameter(MethodDefinition method) //{ // var parameter_type = method.DeclaringType as TypeReference; // if (parameter_type.HasGenericParameters) // { // var instance = new GenericInstanceType(parameter_type); // for (int i = 0; i < parameter_type.GenericParameters.Count; i++) // instance.GenericArguments.Add(parameter_type.GenericParameters[i]); // parameter_type = instance; // } // if (parameter_type.IsValueType || parameter_type.IsPrimitive) // parameter_type = new ByReferenceType(parameter_type); // return new ParameterDefinition(parameter_type, method); //} public MethodBody(MethodDefinition method) { this.method = method; } public ILInstructionReader GetILProcessor() { return ILReaderFactory.Create(method, 0); } } }
using MarvelousSoftware.QueryLanguage.Config; using MarvelousSoftware.QueryLanguage.Lexing.Tokens.Abstract; namespace MarvelousSoftware.QueryLanguage.Lexing.Tokens { /// <summary> /// Token for keywords such as 'Equals' or 'StartsWith'. /// </summary> public class CompareOperatorToken : KeywordTokenBase { public override TokenType TokenType => TokenType.CompareOperator; public CompareOperatorToken(Keyword keyword) : base(keyword) { } } }
using System.Collections.Generic; using Telerik.JustDecompiler.Decompiler.LogicFlow.Common; using Telerik.JustDecompiler.Cil; namespace Telerik.JustDecompiler.Decompiler.LogicFlow.DTree { class DTNode : TreeNode { /// <summary> /// Gets a set of all the nodes that dominate this node. /// </summary> public HashSet<DTNode> Dominators { get { HashSet<DTNode> dominators = new HashSet<DTNode>(); DTNode currentNode = this; while(currentNode != null) { dominators.Add(currentNode); currentNode = currentNode.Predecessor as DTNode; } return dominators; } } /// <summary> /// Gets the set of all the nodes that are in the domination frontier of this node. /// </summary> public HashSet<DTNode> DominanceFrontier { get; private set; } /// <summary> /// Gets the immediate dominator of this node. /// </summary> public DTNode ImmediateDominator { get { return Predecessor as DTNode; } } public DTNode(ISingleEntrySubGraph construct) : base(construct) { DominanceFrontier = new HashSet<DTNode>(); } } }
namespace SimpleUwpTwoWayComms { using System; using System.Collections.Generic; using System.Net; using Windows.Devices.Bluetooth.Advertisement; class BluetoothLEStreamSocketWatcher { public event EventHandler<BluetoothLEStreamSocketDiscoveredEventArgs> StreamSocketDiscovered; public BluetoothLEStreamSocketWatcher(IPAddress localAddress) { this.localAddress = localAddress; this.uniqueAdvertisements = new List<BluetoothLEStreamSocketAdvertisement>(); } public void Start() { if (this.bluetoothWatcher != null) { throw new InvalidOperationException("Already started"); } // Listen for remote advertisements. this.bluetoothWatcher = new BluetoothLEAdvertisementWatcher(); this.bluetoothWatcher.AdvertisementFilter.Advertisement.ManufacturerData.Add( new BluetoothLEManufacturerData() { CompanyId = BluetoothLEStreamSocketAdvertisement.MS_BLUETOOTH_LE_ID } ); this.bluetoothWatcher.Received += OnBluetoothAdvertisementSpotted; this.bluetoothWatcher.Start(); } public void Stop() { if (this.bluetoothWatcher != null) { this.bluetoothWatcher.Received -= this.OnBluetoothAdvertisementSpotted; this.bluetoothWatcher.Stop(); this.bluetoothWatcher = null; } else { throw new InvalidOperationException("Not watching"); } this.uniqueAdvertisements.Clear(); } void OnBluetoothAdvertisementSpotted( BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { foreach (var item in args.Advertisement.GetManufacturerDataByCompanyId( BluetoothLEStreamSocketAdvertisement.MS_BLUETOOTH_LE_ID)) { var advertisement = BluetoothLEStreamSocketAdvertisement.ReadFromBuffer(item.Data); if (advertisement != null) { if ((advertisement.Address.ToString() != this.localAddress.ToString()) && !IsRepeatAdvertisement(advertisement)) { this.StreamSocketDiscovered?.Invoke(this, new BluetoothLEStreamSocketDiscoveredEventArgs() { Advertisement = advertisement }); this.uniqueAdvertisements.Add(advertisement); } } } } bool IsRepeatAdvertisement(BluetoothLEStreamSocketAdvertisement advertisement) { return ( this.uniqueAdvertisements.Exists( e => ((e.Port == advertisement.Port) && (e.Address.ToString() == advertisement.Address.ToString())))); } BluetoothLEAdvertisementWatcher bluetoothWatcher; List<BluetoothLEStreamSocketAdvertisement> uniqueAdvertisements; IPAddress localAddress; } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.ServiceModel.XamlIntegration { using System; using System.Diagnostics.CodeAnalysis; using System.Runtime; using System.Windows.Markup; using System.ServiceModel.Activities; [SuppressMessage(FxCop.Category.Naming, FxCop.Rule.IdentifiersShouldBeSpelledCorrectly, Justification = "Upn is an acronym")] [MarkupExtensionReturnType(typeof(UpnEndpointIdentity))] public class UpnEndpointIdentityExtension : MarkupExtension { public UpnEndpointIdentityExtension() { } public UpnEndpointIdentityExtension(UpnEndpointIdentity identity) { if (identity == null) { throw FxTrace.Exception.ArgumentNull("identity"); } Fx.Assert(identity.IdentityClaim.Resource is string, "UpnEndpointIdentity claim resource is not string"); this.UpnName = (string)identity.IdentityClaim.Resource; } [SuppressMessage(FxCop.Category.Naming, FxCop.Rule.IdentifiersShouldBeSpelledCorrectly, Justification = "Upn is an acronym")] public string UpnName { get; set; } public override object ProvideValue(IServiceProvider serviceProvider) { return new UpnEndpointIdentity(this.UpnName); } } }
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0 { using System; using System.Runtime.CompilerServices; using System.Reflection; using static Root; using static core; partial struct Resources { [MethodImpl(Inline), Op, Closures(UnsignedInts)] public unsafe static ResMember member<T>(MemberInfo member, ReadOnlySpan<T> src) => new ResMember(member, MemorySegs.define(recover<T,byte>(src))); [MethodImpl(Inline), Op] public unsafe static ResMember member(FieldInfo field, uint size) => new ResMember(field, MemorySegs.define(field.FieldHandle.Value, size)); [MethodImpl(Inline), Op] public unsafe static ResMember member(W8 w, FieldInfo field) => new ResMember(field, MemorySegs.define(field.FieldHandle.Value, 1)); [MethodImpl(Inline), Op] public unsafe static ResMember member(W16 w, FieldInfo field) => new ResMember(field, MemorySegs.define(field.FieldHandle.Value, 2)); [MethodImpl(Inline), Op] public unsafe static ResMember member(W32 w, FieldInfo field) => new ResMember(field, MemorySegs.define(field.FieldHandle.Value, 4)); [MethodImpl(Inline), Op] public unsafe static ResMember member(W64 w, FieldInfo field) => new ResMember(field, MemorySegs.define(field.FieldHandle.Value, 8)); } }
using ComparerCode.Base; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Text; namespace ComparerCode { [TestClass] public class BuildStrings : PerformanceTestClass { static List<string> toAppend; //good value 30e3 static double string_list_size = 45e3; static BuildStrings() { toAppend = GetStringList(string_list_size, 10); AddToLog(new { string_list_size }); } [TestMethod] public void Test01_AppendWithPlus() { string result = string.Empty; for (int i = 0; i < string_list_size; i++) { result += toAppend[i]; } } [TestMethod] public void Test02_AppendWithConcat() { string result = string.Empty; for (int i = 0; i < string_list_size; i++) { result = string.Concat(result, toAppend[i]); } } [TestMethod] public void Test03_AppendWithOneConcat() { string result = string.Concat(toAppend); } [TestMethod] public void Test04_AppendWithSB() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < string_list_size; i++) { sb.Append(toAppend[i]); } string result = sb.ToString(); } [TestMethod] public void TestConstant01_interpolationAndBreakLineSupport() { int param = 2; string query = $@"select count(guidPointer) from BACATALOGREFERENCE group by guidPointer having count(guidPointer)>{param}"; } [TestMethod] public void TestConstant02_stringByParts() { int param = 2; string oldQuery = "select count(guidPointer) from BACATALOGREFERENCE \r\n" + "group by guidPointer\r\n" + "having count(guidPointer) >" + param; } } }
/* * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com> * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name of the Git Development Community nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GitSharp.Tests { [TestFixture] public class PushProcessTest : RepositoryTestCase { #if false private PushProcess process; private MockTransport transport; private HashSet<RemoteRefUpdate> refUpdates; private HashSet<Ref> advertisedRefs; private Status connectionUpdateStatus; @Override public void setUp() throws Exception { super.setUp(); transport = new MockTransport(db, new URIish()); refUpdates = new HashSet<RemoteRefUpdate>(); advertisedRefs = new HashSet<Ref>(); connectionUpdateStatus = Status.OK; } /** * Test for fast-forward remote update. * * @throws IOException */ public void testUpdateFastForward() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, "2c349335b7f797072cf729c4f3bb0914ecb6dec9", "refs/heads/master", false, null, null); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("ac7e7e44c1885efb472ad54a78327d66bfc4ecef")); testOneUpdateStatus(rru, ref, Status.OK, true); } /** * Test for non fast-forward remote update, when remote object is not known * to local repository. * * @throws IOException */ public void testUpdateNonFastForwardUnknownObject() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, "2c349335b7f797072cf729c4f3bb0914ecb6dec9", "refs/heads/master", false, null, null); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("0000000000000000000000000000000000000001")); testOneUpdateStatus(rru, ref, Status.REJECTED_NONFASTFORWARD, null); } /** * Test for non fast-forward remote update, when remote object is known to * local repository, but it is not an ancestor of new object. * * @throws IOException */ public void testUpdateNonFastForward() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, "ac7e7e44c1885efb472ad54a78327d66bfc4ecef", "refs/heads/master", false, null, null); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("2c349335b7f797072cf729c4f3bb0914ecb6dec9")); testOneUpdateStatus(rru, ref, Status.REJECTED_NONFASTFORWARD, null); } /** * Test for non fast-forward remote update, when force update flag is set. * * @throws IOException */ public void testUpdateNonFastForwardForced() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, "ac7e7e44c1885efb472ad54a78327d66bfc4ecef", "refs/heads/master", true, null, null); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("2c349335b7f797072cf729c4f3bb0914ecb6dec9")); testOneUpdateStatus(rru, ref, Status.OK, false); } /** * Test for remote ref creation. * * @throws IOException */ public void testUpdateCreateRef() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, "ac7e7e44c1885efb472ad54a78327d66bfc4ecef", "refs/heads/master", false, null, null); testOneUpdateStatus(rru, null, Status.OK, true); } /** * Test for remote ref deletion. * * @throws IOException */ public void testUpdateDelete() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, null, "refs/heads/master", false, null, null); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("2c349335b7f797072cf729c4f3bb0914ecb6dec9")); testOneUpdateStatus(rru, ref, Status.OK, true); } /** * Test for remote ref deletion (try), when that ref doesn't exist on remote * repo. * * @throws IOException */ public void testUpdateDeleteNonExisting() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, null, "refs/heads/master", false, null, null); testOneUpdateStatus(rru, null, Status.NON_EXISTING, null); } /** * Test for remote ref update, when it is already up to date. * * @throws IOException */ public void testUpdateUpToDate() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, "2c349335b7f797072cf729c4f3bb0914ecb6dec9", "refs/heads/master", false, null, null); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("2c349335b7f797072cf729c4f3bb0914ecb6dec9")); testOneUpdateStatus(rru, ref, Status.UP_TO_DATE, null); } /** * Test for remote ref update with expected remote object. * * @throws IOException */ public void testUpdateExpectedRemote() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, "2c349335b7f797072cf729c4f3bb0914ecb6dec9", "refs/heads/master", false, null, ObjectId .fromString("ac7e7e44c1885efb472ad54a78327d66bfc4ecef")); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("ac7e7e44c1885efb472ad54a78327d66bfc4ecef")); testOneUpdateStatus(rru, ref, Status.OK, true); } /** * Test for remote ref update with expected old object set, when old object * is not that expected one. * * @throws IOException */ public void testUpdateUnexpectedRemote() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, "2c349335b7f797072cf729c4f3bb0914ecb6dec9", "refs/heads/master", false, null, ObjectId .fromString("0000000000000000000000000000000000000001")); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("ac7e7e44c1885efb472ad54a78327d66bfc4ecef")); testOneUpdateStatus(rru, ref, Status.REJECTED_REMOTE_CHANGED, null); } /** * Test for remote ref update with expected old object set, when old object * is not that expected one and force update flag is set (which should have * lower priority) - shouldn't change behavior. * * @throws IOException */ public void testUpdateUnexpectedRemoteVsForce() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, "2c349335b7f797072cf729c4f3bb0914ecb6dec9", "refs/heads/master", true, null, ObjectId .fromString("0000000000000000000000000000000000000001")); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("ac7e7e44c1885efb472ad54a78327d66bfc4ecef")); testOneUpdateStatus(rru, ref, Status.REJECTED_REMOTE_CHANGED, null); } /** * Test for remote ref update, when connection rejects update. * * @throws IOException */ public void testUpdateRejectedByConnection() throws IOException { connectionUpdateStatus = Status.REJECTED_OTHER_REASON; final RemoteRefUpdate rru = new RemoteRefUpdate(db, "2c349335b7f797072cf729c4f3bb0914ecb6dec9", "refs/heads/master", false, null, null); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("ac7e7e44c1885efb472ad54a78327d66bfc4ecef")); testOneUpdateStatus(rru, ref, Status.REJECTED_OTHER_REASON, null); } /** * Test for remote refs updates with mixed cases that shouldn't depend on * each other. * * @throws IOException */ public void testUpdateMixedCases() throws IOException { final RemoteRefUpdate rruOk = new RemoteRefUpdate(db, null, "refs/heads/master", false, null, null); final Ref refToChange = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("2c349335b7f797072cf729c4f3bb0914ecb6dec9")); final RemoteRefUpdate rruReject = new RemoteRefUpdate(db, null, "refs/heads/nonexisting", false, null, null); refUpdates.add(rruOk); refUpdates.add(rruReject); advertisedRefs.add(refToChange); executePush(); assertEquals(Status.OK, rruOk.getStatus()); assertEquals(true, rruOk.isFastForward()); assertEquals(Status.NON_EXISTING, rruReject.getStatus()); } /** * Test for local tracking ref update. * * @throws IOException */ public void testTrackingRefUpdateEnabled() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, "2c349335b7f797072cf729c4f3bb0914ecb6dec9", "refs/heads/master", false, "refs/remotes/test/master", null); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("ac7e7e44c1885efb472ad54a78327d66bfc4ecef")); refUpdates.add(rru); advertisedRefs.add(ref); final PushResult result = executePush(); final TrackingRefUpdate tru = result .getTrackingRefUpdate("refs/remotes/test/master"); assertNotNull(tru); assertEquals("refs/remotes/test/master", tru.getLocalName()); assertEquals(Result.NEW, tru.getResult()); } /** * Test for local tracking ref update disabled. * * @throws IOException */ public void testTrackingRefUpdateDisabled() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, "2c349335b7f797072cf729c4f3bb0914ecb6dec9", "refs/heads/master", false, null, null); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("ac7e7e44c1885efb472ad54a78327d66bfc4ecef")); refUpdates.add(rru); advertisedRefs.add(ref); final PushResult result = executePush(); assertTrue(result.getTrackingRefUpdates().isEmpty()); } /** * Test for local tracking ref update when remote update has failed. * * @throws IOException */ public void testTrackingRefUpdateOnReject() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, "ac7e7e44c1885efb472ad54a78327d66bfc4ecef", "refs/heads/master", false, null, null); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("2c349335b7f797072cf729c4f3bb0914ecb6dec9")); final PushResult result = testOneUpdateStatus(rru, ref, Status.REJECTED_NONFASTFORWARD, null); assertTrue(result.getTrackingRefUpdates().isEmpty()); } /** * Test for push operation result - that contains expected elements. * * @throws IOException */ public void testPushResult() throws IOException { final RemoteRefUpdate rru = new RemoteRefUpdate(db, "2c349335b7f797072cf729c4f3bb0914ecb6dec9", "refs/heads/master", false, "refs/remotes/test/master", null); final Ref ref = new Ref(Ref.Storage.LOOSE, "refs/heads/master", ObjectId.fromString("ac7e7e44c1885efb472ad54a78327d66bfc4ecef")); refUpdates.add(rru); advertisedRefs.add(ref); final PushResult result = executePush(); assertEquals(1, result.getTrackingRefUpdates().size()); assertEquals(1, result.getAdvertisedRefs().size()); assertEquals(1, result.getRemoteUpdates().size()); assertNotNull(result.getTrackingRefUpdate("refs/remotes/test/master")); assertNotNull(result.getAdvertisedRef("refs/heads/master")); assertNotNull(result.getRemoteUpdate("refs/heads/master")); } private PushResult testOneUpdateStatus(final RemoteRefUpdate rru, final Ref advertisedRef, final Status expectedStatus, Boolean fastForward) throws NotSupportedException, TransportException { refUpdates.add(rru); if (advertisedRef != null) advertisedRefs.add(advertisedRef); final PushResult result = executePush(); assertEquals(expectedStatus, rru.getStatus()); if (fastForward != null) assertEquals(fastForward.booleanValue(), rru.isFastForward()); return result; } private PushResult executePush() throws NotSupportedException, TransportException { process = new PushProcess(transport, refUpdates); return process.execute(new TextProgressMonitor()); } private class MockTransport extends Transport { MockTransport(Repository local, URIish uri) { super(local, uri); } @Override public FetchConnection openFetch() throws NotSupportedException, TransportException { throw new NotSupportedException("mock"); } @Override public PushConnection openPush() throws NotSupportedException, TransportException { return new MockPushConnection(); } @Override public void close() { // nothing here } } private class MockPushConnection extends BaseConnection implements PushConnection { MockPushConnection() { final Map<String, Ref> refsMap = new HashMap<String, Ref>(); for (final Ref r : advertisedRefs) refsMap.put(r.getName(), r); available(refsMap); } @Override public void close() { // nothing here } public void push(ProgressMonitor monitor, Map<String, RemoteRefUpdate> refsToUpdate) throws TransportException { for (final RemoteRefUpdate rru : refsToUpdate.values()) { assertEquals(Status.NOT_ATTEMPTED, rru.getStatus()); rru.setStatus(connectionUpdateStatus); } } } #endif } }
namespace Cosmos.Security.Cryptography { public interface IRsaKeyConverter { /// <summary> /// Public Key Convert pem->xml /// </summary> /// <param name="publicKey"></param> /// <returns></returns> string PublicKeyPemPkcs8ToXml(string publicKey); /// <summary> /// Public Key Convert xml->pem /// </summary> /// <param name="publicKey"></param> /// <returns></returns> string PublicKeyXmlToPem(string publicKey); /// <summary> /// Private Key Convert Pkcs1->xml /// </summary> /// <param name="privateKey"></param> /// <returns></returns> string PrivateKeyPkcs1ToXml(string privateKey); /// <summary> /// Private Key Convert xml->Pkcs1 /// </summary> /// <param name="privateKey"></param> /// <returns></returns> string PrivateKeyXmlToPkcs1(string privateKey); /// <summary> /// Private Key Convert Pkcs8->xml /// </summary> /// <param name="privateKey"></param> /// <returns></returns> string PrivateKeyPkcs8ToXml(string privateKey); /// <summary> /// Private Key Convert xml->Pkcs8 /// </summary> /// <param name="privateKey"></param> /// <returns></returns> string PrivateKeyXmlToPkcs8(string privateKey); /// <summary> /// Private Key Convert Pkcs1->Pkcs8 /// </summary> /// <param name="privateKey"></param> /// <returns></returns> string PrivateKeyPkcs1ToPkcs8(string privateKey); /// <summary> /// Private Key Convert Pkcs8->Pkcs1 /// </summary> /// <param name="privateKey"></param> /// <returns></returns> string PrivateKeyPkcs8ToPkcs1(string privateKey); } }
using System.Runtime.Serialization; namespace Khernet.Services.Messages { [DataContract] public enum PeerState : sbyte { [EnumMember] New = -1, [EnumMember] Offline = 0, [EnumMember] Idle = 1, [EnumMember] Online = 2, [EnumMember] Busy = 3 } [DataContract] public class Peer { [DataMember] public string AccountToken { get; set; } [DataMember] public string UserName { get; set; } [DataMember] public string HexColor { get; set; } [DataMember] public string Initials { get; set; } [DataMember] public string Slogan { get; set; } [DataMember] public byte[] Avatar { get; set; } [DataMember] public PeerState State { get; set; } [DataMember] public string Group { get; set; } [DataMember] public byte[] FullName { get; set; } [DataMember] public byte[] DisplayName { get; set; } } }
namespace EvMSBuildTest.Stubs { internal class StubEvaluatingProperty: EvMSBuilderAcs { public override string GetPropValue(string name, string project) { if(UVars.IsExist(name, project)) { return GetUVarValue(name, project); } return $"[P~{name}~{project}]"; } protected override string Obtain(string unevaluated, string project) { return $"[E~{unevaluated}~{project}]"; } } }
using nHydrate.Generator.Common.GeneratorFramework; using nHydrate.Generator.Common.Util; using System; using System.Xml; namespace nHydrate.Generator.Common.Models { /// <summary> /// This is the base for all column classes /// </summary> public abstract class ColumnBase : BaseModelObject, ICodeFacadeObject { #region Member Variables protected const System.Data.SqlDbType _def_type = System.Data.SqlDbType.VarChar; protected const int _def_length = 50; protected const int _def_scale = 0; protected const bool _def_allowNull = true; protected const string _def_description = ""; protected const string _def_prompt = ""; protected const string _def_codefacade = ""; protected System.Data.SqlDbType _dataType = _def_type; protected int _length = _def_length; protected int _scale = _def_scale; protected bool _allowNull = _def_allowNull; #endregion #region Constructor protected ColumnBase(INHydrateModelObject root) : base(root) { } #endregion #region Property Implementations public virtual string Description { get; set; } = _def_description; public virtual string Prompt { get; set; } = _def_prompt; public virtual int Length { get { var retval = this.PredefinedSize; if (retval == -1) retval = _length; return retval; } set { if (value < 0) value = 0; _length = value; } } public virtual int Scale { get { var retval = this.PredefinedScale; if (retval == -1) retval = _scale; return retval; } set { if (value < 0) value = 0; _scale = value; } } public virtual System.Data.SqlDbType DataType { get { return _dataType; } set { _length = this.GetDefaultSize(value); _dataType = value; } } public virtual bool AllowNull { get { return this.DataType != System.Data.SqlDbType.Variant && _allowNull; } set { _allowNull = value; } } public virtual string DatabaseType => this.GetSQLDefaultType(); #region ICodeFacadeObject Members public virtual string CodeFacade { get; set; } = _def_codefacade; public virtual string GetCodeFacade() => this.CodeFacade.IfEmptyDefault(this.Name); #endregion #endregion #region Methods /// <summary> /// Determines if this data type supports a user-defined size /// </summary> public virtual bool IsDefinedSize => this.PredefinedSize != -1; /// <summary> /// Determines if this data type supports a user-defined scale /// </summary> public virtual bool IsDefinedScale { get { return this.PredefinedScale == 0; } } /// <summary> /// Determines if this field has no max length defined /// </summary> /// <returns></returns> public virtual bool IsMaxLength() { switch (this.DataType) { case System.Data.SqlDbType.VarChar: case System.Data.SqlDbType.NVarChar: case System.Data.SqlDbType.VarBinary: return (this.Length == 0); case System.Data.SqlDbType.Text: case System.Data.SqlDbType.NText: return true; default: return false; } } public virtual string GetLengthString() => (this.DataType.SupportsMax() && this.Length == 0) ? "max" : this.Length.ToString(); /// <summary> /// This is the length used for annotations and meta data for class descriptions /// </summary> public virtual int GetAnnotationStringLength() { switch (this.DataType) { case System.Data.SqlDbType.NText: return 1073741823; case System.Data.SqlDbType.Text: return int.MaxValue; case System.Data.SqlDbType.Image: return int.MaxValue; } return (this.DataType.SupportsMax() && this.Length == 0) ? int.MaxValue : this.Length; } public override string ToString() => this.Name; #endregion public abstract override XmlNode XmlAppend(XmlNode node); public abstract override XmlNode XmlLoad(XmlNode node); #region Helpers public abstract Reference CreateRef(); public abstract Reference CreateRef(string key); public virtual string CamelName => StringHelper.FirstCharToLower(this.PascalName); public virtual string PascalName => this.GetCodeFacade(); public virtual string DatabaseName => this.Name; /// <summary> /// Gets the SQL Server type mapping for this data type /// </summary> public virtual string GetSQLDefaultType() => GetSQLDefaultType(false); /// <summary> /// Gets the SQL Server type mapping for this data type /// </summary> /// <param name="isRaw">Determines if the square brackets '[]' are around the type</param> /// <returns>The SQL ready datatype like '[Int]' or '[Varchar] (100)'</returns> public virtual string GetSQLDefaultType(bool isRaw) { var retval = string.Empty; if (!isRaw) retval += "["; retval += this.DataType.ToString(); if (!isRaw) retval += "]"; if (this.DataType == System.Data.SqlDbType.Variant) { retval = string.Empty; if (!isRaw) retval += "["; retval += "sql_variant"; if (!isRaw) retval += "]"; } else if (this.DataType == System.Data.SqlDbType.Binary || this.DataType == System.Data.SqlDbType.Char || this.DataType == System.Data.SqlDbType.Decimal || this.DataType == System.Data.SqlDbType.DateTime2 || this.DataType == System.Data.SqlDbType.NChar || this.DataType == System.Data.SqlDbType.NVarChar || this.DataType == System.Data.SqlDbType.VarBinary || this.DataType == System.Data.SqlDbType.VarChar) { if (this.DataType == System.Data.SqlDbType.Decimal) retval += $" ({this.Length}, {this.Scale})"; else if (this.DataType == System.Data.SqlDbType.DateTime2) retval += $" ({this.Length})"; else retval += $" ({this.GetLengthString()})"; } return retval; } /// <summary> /// Gets a string reprsenting the data length for comments /// </summary> /// <remarks>This is not to be used for actual C# code or SQL</remarks> public virtual string GetCommentLengthString() { if (this.DataType == System.Data.SqlDbType.Binary || this.DataType == System.Data.SqlDbType.Char || this.DataType == System.Data.SqlDbType.Decimal || this.DataType == System.Data.SqlDbType.DateTime2 || this.DataType == System.Data.SqlDbType.NChar || this.DataType == System.Data.SqlDbType.NVarChar || this.DataType == System.Data.SqlDbType.VarBinary || this.DataType == System.Data.SqlDbType.VarChar) { if (this.DataType == System.Data.SqlDbType.Decimal) return this.Length + $" (scale:{this.Scale})"; else if (this.DataType == System.Data.SqlDbType.DateTime2) return this.Length.ToString(); else return this.GetLengthString(); } return string.Empty; } public virtual string GetCodeType() => GetCodeType(true, false); public virtual string GetCodeType(bool allowNullable) => GetCodeType(allowNullable, false); public virtual string GetCodeType(bool allowNullable, bool forceNull) { string retval; if (StringHelper.Match(this.DataType.ToString(), "bigint", true)) retval = "long"; else if (StringHelper.Match(this.DataType.ToString(), "binary", true)) return "System.Byte[]"; else if (StringHelper.Match(this.DataType.ToString(), "bit", true)) retval = "bool"; else if (StringHelper.Match(this.DataType.ToString(), "char", true)) return "string"; else if (StringHelper.Match(this.DataType.ToString(), "datetime", true)) retval = "DateTime"; else if (StringHelper.Match(this.DataType.ToString(), "datetime2", true)) retval = "DateTime"; else if (StringHelper.Match(this.DataType.ToString(), "date", true)) retval = "DateTime"; else if (StringHelper.Match(this.DataType.ToString(), "time", true)) retval = "TimeSpan"; else if (StringHelper.Match(this.DataType.ToString(), "datetimeoffset", true)) retval = "DateTimeOffset"; else if (StringHelper.Match(this.DataType.ToString(), "decimal", true)) retval = "decimal"; else if (StringHelper.Match(this.DataType.ToString(), "float", true)) retval = "double"; else if (StringHelper.Match(this.DataType.ToString(), "image", true)) return "System.Byte[]"; else if (StringHelper.Match(this.DataType.ToString(), "int", true)) retval = "int"; else if (StringHelper.Match(this.DataType.ToString(), "money", true)) retval = "decimal"; else if (StringHelper.Match(this.DataType.ToString(), "nchar", true)) return "string"; else if (StringHelper.Match(this.DataType.ToString(), "ntext", true)) return "string"; else if (StringHelper.Match(this.DataType.ToString(), "numeric", true)) retval = "decimal"; else if (StringHelper.Match(this.DataType.ToString(), "nvarchar", true)) return "string"; else if (StringHelper.Match(this.DataType.ToString(), "real", true)) retval = "System.Single"; else if (StringHelper.Match(this.DataType.ToString(), "smalldatetime", true)) retval = "DateTime"; else if (StringHelper.Match(this.DataType.ToString(), "smallint", true)) retval = "short"; else if (StringHelper.Match(this.DataType.ToString(), "smallmoney", true)) retval = "decimal"; else if (StringHelper.Match(this.DataType.ToString(), "variant", true)) retval = "object"; else if (StringHelper.Match(this.DataType.ToString(), "text", true)) return "string"; else if (StringHelper.Match(this.DataType.ToString(), "tinyint", true)) retval = "byte"; else if (StringHelper.Match(this.DataType.ToString(), "uniqueidentifier", true)) retval = "System.Guid"; else if (StringHelper.Match(this.DataType.ToString(), "varbinary", true)) return "System.Byte[]"; else if (StringHelper.Match(this.DataType.ToString(), "varchar", true)) return "string"; else if (StringHelper.Match(this.DataType.ToString(), "timestamp", true)) return "System.Byte[]"; else if (StringHelper.Match(this.DataType.ToString(), "xml", true)) return "string"; else throw new Exception("Cannot Map Sql Value '" + this.DataType.ToString() + "' To C# Value"); if (allowNullable && (this.AllowNull || forceNull)) retval += "?"; return retval; } /// <summary> /// Determines if the Datatype supports the 'Parse' method /// </summary> public virtual bool AllowStringParse { get { if (StringHelper.Match(this.DataType.ToString(), "bigint", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "binary", true)) return false; else if (StringHelper.Match(this.DataType.ToString(), "bit", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "char", true)) return false; else if (StringHelper.Match(this.DataType.ToString(), "datetime", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "datetime2", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "datetimeoffset", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "date", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "time", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "decimal", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "float", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "image", true)) return false; else if (StringHelper.Match(this.DataType.ToString(), "int", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "money", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "nchar", true)) return false; else if (StringHelper.Match(this.DataType.ToString(), "ntext", true)) return false; else if (StringHelper.Match(this.DataType.ToString(), "numeric", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "nvarchar", true)) return false; else if (StringHelper.Match(this.DataType.ToString(), "real", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "smalldatetime", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "smallint", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "smallmoney", true)) return true; else if (StringHelper.Match(this.DataType.ToString(), "variant", true)) return false; else if (StringHelper.Match(this.DataType.ToString(), "text", true)) return false; else if (StringHelper.Match(this.DataType.ToString(), "tinyint", true)) return false; else if (StringHelper.Match(this.DataType.ToString(), "uniqueidentifier", true)) return false; else if (StringHelper.Match(this.DataType.ToString(), "varbinary", true)) return false; else if (StringHelper.Match(this.DataType.ToString(), "varchar", true)) return false; else if (StringHelper.Match(this.DataType.ToString(), "timestamp", true)) return false; else return false; } } public static int GetPredefinedSize(System.Data.SqlDbType dataType) { //Returns -1 if variable switch (dataType) { case System.Data.SqlDbType.BigInt: return 8; case System.Data.SqlDbType.Bit: return 1; case System.Data.SqlDbType.DateTime: return 8; case System.Data.SqlDbType.Date: return 3; case System.Data.SqlDbType.Time: return 5; case System.Data.SqlDbType.DateTimeOffset: return 10; case System.Data.SqlDbType.Float: return 8; case System.Data.SqlDbType.Int: return 4; case System.Data.SqlDbType.Money: return 8; case System.Data.SqlDbType.Real: return 4; case System.Data.SqlDbType.SmallDateTime: return 4; case System.Data.SqlDbType.SmallInt: return 2; case System.Data.SqlDbType.SmallMoney: return 4; case System.Data.SqlDbType.Timestamp: return 8; case System.Data.SqlDbType.TinyInt: return 1; case System.Data.SqlDbType.UniqueIdentifier: return 16; //case System.Data.SqlDbType.Image: //case System.Data.SqlDbType.Text: //case System.Data.SqlDbType.NText: //case System.Data.SqlDbType.Xml: // return 1; default: return -1; } } /// <summary> /// Gets the size of the data type /// </summary> /// <returns></returns> /// <remarks>Returns -1 for variable types and 1 for blob fields</remarks> public virtual int PredefinedSize => GetPredefinedSize(this.DataType); public static int GetPredefinedScale(System.Data.SqlDbType dataType) { //Returns -1 if variable switch (dataType) { case System.Data.SqlDbType.Decimal: return -1; default: return 0; } } public virtual int PredefinedScale => GetPredefinedScale(this.DataType); private int GetDefaultSize(System.Data.SqlDbType dataType) { var size = _length; switch (dataType) { case System.Data.SqlDbType.Decimal: case System.Data.SqlDbType.Real: size = 18; break; case System.Data.SqlDbType.Binary: case System.Data.SqlDbType.NVarChar: case System.Data.SqlDbType.VarBinary: case System.Data.SqlDbType.VarChar: size = 50; break; case System.Data.SqlDbType.Char: case System.Data.SqlDbType.NChar: size = 10; break; case System.Data.SqlDbType.DateTime2: size = 7; break; } return size; } #endregion } }
using System; namespace Network.Models { public class RetryModel { public TimeSpan SleepPeriod { get; set; } public int RetryCount { get; set; } } }
/* Copyright 2007-2017 The NGenerics Team (https://github.com/ngenerics/ngenerics/wiki/Team) This program is licensed under the MIT License. You should have received a copy of the license along with the source code. If not, an online copy of the license can be found at https://opensource.org/licenses/MIT. */ using System; using System.Diagnostics.CodeAnalysis; namespace NGenerics.DataStructures.Queues { /// <summary> /// A queue interface. /// </summary> /// <typeparam name="T">The type of the elements in the queue.</typeparam> [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public interface IQueue<T> { /// <summary> /// Enqueues the item at the back of the queue. /// </summary> /// <param name="item">The item.</param> void Enqueue(T item); /// <summary> /// Dequeues the item at the front of the queue. /// </summary> /// <returns>The item at the front of the queue.</returns> /// <exception cref="InvalidOperationException">The <see cref="Deque{T}"/> is empty.</exception> T Dequeue(); /// <summary> /// Peeks at the item in the front of the queue, without removing it. /// </summary> /// <returns>The item at the front of the queue.</returns> /// <exception cref="InvalidOperationException">The <see cref="Deque{T}"/> is empty.</exception> T Peek(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace crass { public class PlayerPrefsEraserMenu : MonoBehaviour { [MenuItem("Tools/Clear Player Prefs")] static void erase () { PlayerPrefs.DeleteAll(); } } }
using Autofac; using JetBrains.Annotations; using MAVN.Service.QuorumOperationExecutor.Settings; using Lykke.Service.QuorumTransactionSigner.Client; using Lykke.SettingsReader; namespace MAVN.Service.QuorumOperationExecutor.Modules { [UsedImplicitly] public class ClientsModule : Module { private readonly AppSettings _appSettings; public ClientsModule( IReloadingManager<AppSettings> appSettings) { _appSettings = appSettings.CurrentValue; } protected override void Load( ContainerBuilder builder) { builder .RegisterQuorumTransactionSignerClient(_appSettings.QuorumTransactionSignerService, null); } } }
using System.Xml.Linq; namespace Iodd2AmlConverter.Library.Iodd { public interface IDeserializableIodd { void Deserialize(XElement element); } }
using System; using Rebus.Activation; using Rebus.Bus; using Rebus.Config; using Rebus.Handlers; namespace Rebus.Tests.Contracts.Activation { public interface IActivationContext { IHandlerActivator CreateActivator(Action<IHandlerRegistry> configureHandlers, out IActivatedContainer container); IBus CreateBus(Action<IHandlerRegistry> configureHandlers, Func<RebusConfigurer, RebusConfigurer> configureBus, out IActivatedContainer container); } public interface IHandlerRegistry { IHandlerRegistry Register<THandler>() where THandler : class, IHandleMessages; } public interface IActivatedContainer : IDisposable { IBus ResolveBus(); } }
using System.Collections.Generic; using System.Linq; using Bechtle.A365.ConfigService.Common; using Xunit; namespace Bechtle.A365.ConfigService.Tests.Common { public class QueryRangeTests { public static IEnumerable<object[]> QueryData => new[] { new object[] { 0, 0 }, new object[] { 0, int.MinValue }, new object[] { 0, int.MaxValue }, new object[] { int.MinValue, 0 }, new object[] { int.MaxValue, 0 }, new object[] { int.MinValue, int.MinValue }, new object[] { int.MinValue, int.MaxValue }, new object[] { int.MaxValue, int.MaxValue }, new object[] { int.MaxValue, int.MinValue } }; [Fact] public void AllIsValid() { QueryRange queryRange = QueryRange.All; Assert.Equal(0, queryRange.Offset); Assert.Equal(int.MaxValue, queryRange.Length); } // we only check if the constructor throws up // ReSharper disable once ObjectCreationAsStatement [Theory] [MemberData(nameof(QueryData))] public void CreateNew(int offset, int length) => new QueryRange(offset, length); // we only check if the constructor throws up // ReSharper disable once ObjectCreationAsStatement [Fact] public void CreateNewBasic() => new QueryRange(); [Theory] [MemberData(nameof(QueryData))] public void Equality(int offset, int length) { var left = new QueryRange(offset, length); var right = new QueryRange(offset, length); Assert.True(left.Equals(right)); Assert.True(left == right); Assert.False(left != right); } [Theory] [MemberData(nameof(QueryData))] public void GetHashCodeStable(int offset, int length) { var range = new QueryRange(offset, length); List<int> hashes = Enumerable.Range(0, 1000) .Select(_ => range.GetHashCode()) .ToList(); int example = range.GetHashCode(); Assert.True(hashes.All(h => h == example), "hashes.All(h => h == example)"); } [Theory] [MemberData(nameof(QueryData))] public void MakeSanitizesLength(int offset, int length) => Assert.InRange(QueryRange.Make(offset, length).Length, 1, int.MaxValue); [Theory] [MemberData(nameof(QueryData))] public void NoToStringExceptions(int offset, int length) => Assert.NotNull(new QueryRange(offset, length).ToString()); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PlanetbaseMultiplayer.SharedLibs.DataPackages { [Serializable] public class UpdateResourceDataPackage : IDataPackage { public Guid ResourceId; public ResourceAction Action; public ResourceData Data; public UpdateResourceDataPackage(Guid resourceId, ResourceAction action, ResourceData data) { ResourceId = resourceId; Action = action; Data = data; } } }
using OrchardCore.ContentManagement; namespace OrchardCore.Lists.Models { public class ListPart : ContentPart { } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using Microsoft.Performance.SDK.Extensibility; using Microsoft.Performance.SDK.Extensibility.DataCooking; using Microsoft.Performance.SDK.Processing; namespace Microsoft.Performance.SDK.Runtime.Extensibility.DataExtensions.DataCookers { /// <summary> /// This class wraps a set of source data parsers to make it easy to retrieve data /// output from any associated source data cookers. /// </summary> internal class CrossParserSourceDataCookerRetrieval : ICookedDataRetrieval { private readonly IDictionary<string, ICustomDataProcessorWithSourceParser> processorsByParser = new Dictionary<string, ICustomDataProcessorWithSourceParser>(StringComparer.Ordinal); internal CrossParserSourceDataCookerRetrieval( IEnumerable<ICustomDataProcessorWithSourceParser> processors) { Guard.NotNull(processors, nameof(processors)); foreach (var processor in processors) { this.processorsByParser.Add(processor.SourceParserId, processor); } } /// <summary> /// Retrieves data by name, typecast to the given type. /// The caller is coupled to the data extension and expected to know the /// data type. /// </summary> /// <typeparam name="T">Type of the data to retrieve</typeparam> /// <param name="dataOutputPath">Unique identifier for the data to retrieve</param> /// <returns>The uniquely identified data</returns> public T QueryOutput<T>(DataOutputPath dataOutputPath) { if (!this.processorsByParser.TryGetValue(dataOutputPath.SourceParserId, out var processor)) { throw new ArgumentException($"The specified source parser ({dataOutputPath.SourceParserId}) was not found."); } return processor.QueryOutput<T>(dataOutputPath); } /// <summary> /// Retrieves data by name. /// </summary> /// <param name="dataOutputPath">Unique identifier for the data to retrieve</param> /// <returns>The uniquely identified data, as an object</returns> public object QueryOutput(DataOutputPath dataOutputPath) { if (!this.processorsByParser.TryGetValue(dataOutputPath.SourceParserId, out var processor)) { throw new ArgumentException($"The specified source parser ({dataOutputPath.SourceParserId}) was not found."); } return processor.QueryOutput(dataOutputPath); } /// <inheritdoc /> public bool TryQueryOutput(DataOutputPath dataOutputPath, out object result) { if (!this.processorsByParser.TryGetValue(dataOutputPath.SourceParserId, out var processor)) { result = default; return false; } return processor.TryQueryOutput(dataOutputPath, out result); } /// <inheritdoc /> public bool TryQueryOutput<TOutput>(DataOutputPath dataOutputPath, out TOutput result) { if (!this.processorsByParser.TryGetValue(dataOutputPath.SourceParserId, out var processor)) { result = default; return false; } try { result = processor.QueryOutput<TOutput>(dataOutputPath); return true; } catch (Exception) { } result = default; return false; } } }
namespace ExrinSampleMobileApp.Framework.Locator { public enum Containers { Authentication, Main, Tabbed } }
@model IssuesListingViewModel @* When issues are listed in carousel (New Issues page) *@ @*@if (Model.UseCarousel) { @Html.DisplayFor(m => m.Issues) }*@ @* When issues are listed normally (Approved Issues page) *@ <div class="row"> <ul class="list-group"> @Html.DisplayFor(m => m.Issues) </ul> <input type="hidden" id="pagesCount" value="@Model.PagesCount" /> <input type="hidden" id="page" value="@Model.Page"/> </div>
namespace SystemCommandLine.Demo { public class GreetOptions { public object Greeting { get; set; } } }
using SadConsole.Input; using SadConsole.UI.Themes; using SadRogue.Primitives; using System; using System.Collections.ObjectModel; using System.Runtime.Serialization; namespace SadConsole.UI.Controls { /// <summary> /// A scrollable list control. /// </summary> [DataContract] public class ListBox : CompositeControl { /// <summary> /// The event args used when the selected item changes. /// </summary> public class SelectedItemEventArgs : EventArgs { /// <summary> /// The item selected. /// </summary> public readonly object Item; /// <summary> /// Creates a new instance of this type with the specified item. /// </summary> /// <param name="item">The selected item from the list.</param> public SelectedItemEventArgs(object item) => Item = item; } [DataMember(Name = "SelectedIndex")] private int _selectedIndex = -1; private object _selectedItem; private DateTime _leftMouseLastClick = DateTime.Now; [DataMember] private Orientation _serializedScrollOrientation; [DataMember] private Point _serializedScrollPosition; [DataMember] private int _serializedScrollSizeValue; /// <summary> /// An event that triggers when the <see cref="SelectedItem"/> changes. /// </summary> public event EventHandler<SelectedItemEventArgs> SelectedItemChanged; /// <summary> /// An event that triggers when an item is double clicked or the Enter key is pressed while the listbox has focus. /// </summary> public event EventHandler<SelectedItemEventArgs> SelectedItemExecuted; /// <summary> /// The theme used by the listbox items. /// </summary> public ListBoxItemTheme ItemTheme { get; private set; } /// <summary> /// Internal use only; used in rendering. /// </summary> public bool IsScrollBarVisible { get => ScrollBar.IsVisible; set => ScrollBar.IsVisible = value; } /// <summary> /// Used in rendering. /// </summary> [DataMember(Name = "ScrollBar")] public ScrollBar ScrollBar { get; private set; } /// <summary> /// Used in rendering. /// </summary> public int RelativeIndexMouseOver { get; private set; } /// <summary> /// The total items visible in the listbox. /// </summary> public int VisibleItemsTotal { get; set; } /// <summary> /// The maximum amount of items that can be shown in the listbox. /// </summary> public int VisibleItemsMax { get; set; } /// <summary> /// When the <see cref="SelectedItem"/> changes, and this property is true, objects will be compared by reference. If false, they will be compared by value. /// </summary> [DataMember] public bool CompareByReference { get; set; } /// <summary> /// When set to <see langword="true"/>, the <see cref="SelectedItemExecuted"/> event will fire when an item is single-clicked instead of double-clicked. /// </summary> [DataMember] public bool SingleClickItemExecute { get; set; } /// <summary> /// The items in the listbox. /// </summary> [DataMember] public ObservableCollection<object> Items { get; private set; } /// <summary> /// Gets or sets the index of the selected item. /// </summary> public int SelectedIndex { get => _selectedIndex; set { if (value == -1) { _selectedIndex = -1; _selectedItem = null; IsDirty = true; OnSelectedItemChanged(); } else if (value < 0 || value >= Items.Count) throw new IndexOutOfRangeException(); else { _selectedIndex = value; _selectedItem = Items[value]; IsDirty = true; OnSelectedItemChanged(); } } } /// <summary> /// Gets or sets the selected item. /// </summary> public object SelectedItem { get => _selectedItem; set { if (value == null) { _selectedIndex = -1; _selectedItem = null; IsDirty = true; OnSelectedItemChanged(); } else { // Find the item by index. int index = -1; for (int i = 0; i < Items.Count; i++) { if (CompareByReference) { if (object.ReferenceEquals(Items[i], value)) { index = i; break; } } else { if (object.Equals(Items[i], value)) { index = i; break; } } } if (index == -1) throw new ArgumentOutOfRangeException("Item does not exist in collection."); _selectedIndex = index; _selectedItem = Items[index]; IsDirty = true; OnSelectedItemChanged(); } } } /// <summary> /// Creates a new instance of the listbox control with the default theme for the items. /// </summary> /// <param name="width">The width of the listbox.</param> /// <param name="height">The height of the listbox.</param> public ListBox(int width, int height) : base(width, height) { Items = new ObservableCollection<object>(); Items.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Items_CollectionChanged); ItemTheme = new ListBoxItemTheme(); } /// <summary> /// Creates a new instance of the listbox control with the specified item theme. /// </summary> /// <param name="width">The width of the listbox.</param> /// <param name="height">The height of the listbox.</param> /// <param name="itemTheme">The theme to use with rendering the listbox items.</param> public ListBox(int width, int height, ListBoxItemTheme itemTheme) : this(width, height) => ItemTheme = itemTheme; private void _scrollbar_ValueChanged(object sender, EventArgs e) => IsDirty = true; /// <summary> /// Invokes the <see cref="SelectedItemChanged"/> event. /// </summary> protected virtual void OnSelectedItemChanged() => SelectedItemChanged?.Invoke(this, new SelectedItemEventArgs(_selectedItem)); /// <summary> /// Invokes the <see cref="SelectedItemExecuted"/> event. /// </summary> protected virtual void OnItemAction() => SelectedItemExecuted?.Invoke(this, new SelectedItemEventArgs(_selectedItem)); /// <summary> /// Configures the associated <see cref="ScrollBar"/>. /// </summary> /// <param name="orientation">The orientation of the scrollbar.</param> /// <param name="sizeValue">The size of the scrollbar.</param> /// <param name="position">The position of the scrollbar.</param> public void SetupScrollBar(Orientation orientation, int sizeValue, Point position) { bool scrollBarExists = false; int value = 0; int max = 0; if (ScrollBar != null) { ScrollBar.ValueChanged -= _scrollbar_ValueChanged; value = ScrollBar.Value; max = ScrollBar.Maximum; RemoveControl(ScrollBar); scrollBarExists = true; } //_scrollBar.Width, height < 3 ? 3 : height - _scrollBarSizeAdjust ScrollBar = new ScrollBar(Orientation.Vertical, sizeValue); if (scrollBarExists) { ScrollBar.Maximum = max; ScrollBar.Value = value; } ScrollBar.ValueChanged += _scrollbar_ValueChanged; ScrollBar.Position = position; AddControl(ScrollBar); _serializedScrollSizeValue = sizeValue; _serializedScrollPosition = position; _serializedScrollOrientation = orientation; OnThemeChanged(); DetermineState(); } /// <summary> /// Scrolls the list to the item currently selected. /// </summary> public void ScrollToSelectedItem() { if (IsScrollBarVisible) { if (_selectedIndex < VisibleItemsMax) ScrollBar.Value = 0; else if (SelectedIndex > Items.Count - VisibleItemsTotal) ScrollBar.Value = ScrollBar.Maximum; else ScrollBar.Value = _selectedIndex - VisibleItemsTotal; } } /// <summary> /// Sets the scrollbar's theme to the current theme's <see cref="ListBoxTheme.ScrollBarTheme"/>. /// </summary> protected override void OnThemeChanged() { if (ScrollBar == null) return; if (Theme is ListBoxTheme theme) ScrollBar.Theme = theme.ScrollBarTheme; else ScrollBar.Theme = null; } private void Items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add) { } else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Move) { } else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove) { } else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Reset) { ScrollBar.Value = 0; } if (SelectedItem != null && !Items.Contains(_selectedItem)) { SelectedItem = null; } IsDirty = true; } /// <inheritdoc /> public override bool ProcessKeyboard(Input.Keyboard info) { //if (_hasFocus) if (info.IsKeyReleased(Keys.Up)) { int index = Items.IndexOf(_selectedItem); if (_selectedItem != null) { if (index != 0) { SelectedItem = Items[index - 1]; if (index <= ScrollBar.Value) { ScrollBar.Value -= 1; } } } return true; } else if (info.IsKeyReleased(Keys.Down)) { int index = Items.IndexOf(_selectedItem); if (_selectedItem != null) { if (index != Items.Count - 1) { SelectedItem = Items[index + 1]; if (index + 1 >= ScrollBar.Value + (Height - 2)) { ScrollBar.Value += 1; } } } else if (Items.Count != 0) { SelectedItem = Items[0]; } return true; } else if (info.IsKeyReleased(Keys.Enter)) { if (_selectedItem != null) { OnItemAction(); } return true; } return false; } /// <inheritdoc /> protected override void OnMouseIn(ControlMouseState state) { base.OnMouseIn(state); if (!(Theme is ListBoxTheme theme)) return; int rowOffset = ((ListBoxTheme)theme).DrawBorder ? 1 : 0; int rowOffsetReverse = ((ListBoxTheme)theme).DrawBorder ? 0 : 1; int columnOffsetEnd = IsScrollBarVisible || !((ListBoxTheme)theme).DrawBorder ? 1 : 0; Point mouseControlPosition = state.MousePosition; if (mouseControlPosition.Y >= rowOffset && mouseControlPosition.Y < Height - rowOffset && mouseControlPosition.X >= rowOffset && mouseControlPosition.X < Width - columnOffsetEnd) { if (IsScrollBarVisible) { RelativeIndexMouseOver = mouseControlPosition.Y - rowOffset + ScrollBar.Value; } else if (mouseControlPosition.Y <= Items.Count - rowOffsetReverse) { RelativeIndexMouseOver = mouseControlPosition.Y - rowOffset; } else { RelativeIndexMouseOver = -1; } } else { RelativeIndexMouseOver = -1; } if (state.OriginalMouseState.Mouse.ScrollWheelValueChange != 0) { if (state.OriginalMouseState.Mouse.ScrollWheelValueChange < 0) ScrollBar.Value -= 1; else ScrollBar.Value += 1; } } /// <inheritdoc /> protected override void OnLeftMouseClicked(ControlMouseState state) { base.OnLeftMouseClicked(state); if (!(Theme is ListBoxTheme theme)) return; DateTime click = DateTime.Now; bool doubleClicked = (click - _leftMouseLastClick).TotalSeconds <= 0.5; _leftMouseLastClick = click; int rowOffset = ((ListBoxTheme)theme).DrawBorder ? 1 : 0; int rowOffsetReverse = ((ListBoxTheme)theme).DrawBorder ? 0 : 1; int columnOffsetEnd = IsScrollBarVisible || !((ListBoxTheme)theme).DrawBorder ? 1 : 0; Point mouseControlPosition = state.MousePosition; if (mouseControlPosition.Y >= rowOffset && mouseControlPosition.Y < Height - rowOffset && mouseControlPosition.X >= rowOffset && mouseControlPosition.X < Width - columnOffsetEnd) { object oldItem = _selectedItem; bool noItem = false; if (IsScrollBarVisible) { _selectedIndex = mouseControlPosition.Y - rowOffset + ScrollBar.Value; SelectedItem = Items[_selectedIndex]; } else if (mouseControlPosition.Y <= Items.Count - rowOffsetReverse) { _selectedIndex = mouseControlPosition.Y - rowOffset; SelectedItem = Items[_selectedIndex]; } else { noItem = true; } if (!noItem && (SingleClickItemExecute || (doubleClicked && oldItem == SelectedItem))) { _leftMouseLastClick = DateTime.MinValue; OnItemAction(); } } } [OnSerializing] private void BeforeSerializing(StreamingContext context) { if (_selectedItem != null) { _selectedIndex = Items.IndexOf(_selectedItem); } else { _selectedIndex = -1; } } [OnDeserializedAttribute] private void AfterDeserialized(StreamingContext context) { SetupScrollBar(_serializedScrollOrientation, _serializedScrollSizeValue, _serializedScrollPosition); Items.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Items_CollectionChanged); if (_selectedIndex != -1) { SelectedItem = Items[_selectedIndex]; } DetermineState(); IsDirty = true; } } }
namespace Mvc3Host.Services { using Mvc3Host.Models; using MvcTurbine.ComponentModel; public class ServiceRegistry : IServiceRegistration { public void Register(IServiceLocator locator) { locator.Register<IFooService, FooService>(); locator.Register(() => new Person {Name = "Bob Smith"}); } } }
//____________________________________________________________________________ // // Copyright (C) 2018, Mariusz Postol LODZ POLAND. // // To be in touch join the community at GITTER: https://gitter.im/mpostol/TP //____________________________________________________________________________ namespace TPA.Reflection.DynamicType { public class DynamicExampleClass { public dynamic Increment(dynamic value) { //object vs dynamic differences object _error = 10; //_error += 1; //compiler error dynamic _dyn = 0; _dyn += 1; return value + _dyn; } public dynamic ExampleMethod(dynamic d) { dynamic _local = "Local variable"; int _two = 2; if (d is int) return _local; else return _two; } } }
namespace Switchvox.Backups { class Apply { } }
using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Exentials.MdcBlazor.ServerDemo.Components { public partial class DemoComponent { [Parameter] public RenderFragment TopBar { get; set; } [Parameter] public RenderFragment Content { get; set; } [Parameter] public RenderFragment TopOption { get; set; } [Parameter] public RenderFragment Options { get; set; } } }
using System.Collections.Generic; namespace Configurator { public interface IReader { List<string> Read(string path); } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Options; using Google.Apis.Customsearch.v1; using ApiServer.Models; using Newtonsoft.Json.Linq; using System.Linq; namespace ApiServer { public class GoogleCustomSearchModule : ISearchModule { private static GoogleCustomSearchModule _instance = new GoogleCustomSearchModule(); public static GoogleCustomSearchModule Instance => _instance; public SearchEngineTypes SearchEngingType => SearchEngineTypes.GoogleCustomJson; private bool _isAvailable = false; public bool IsAvailable { get => _isAvailable; set => _isAvailable = value; } private string cx; private CustomsearchService customSearchService; private readonly IReadOnlyList<string> thumbnailKeyCandidates = new List<string> { "thumbnail", "cse_thumbnail", "cse_image" }.AsReadOnly(); public bool Initialize(SearchEngineApiSettings apiSettings) { try { customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiSettings.googleCustomSearchApiSettings.ApiKey }); cx = apiSettings.googleCustomSearchApiSettings.Cx; _isAvailable = true; return true; } catch (Exception e) { _isAvailable = false; return false; } } /// <summary> /// 검색 결과를 리스트로 반환 /// TODO: 리스트 풀링하도록 수정 /// </summary> /// <param name="keyword">검색할 키워드</param> public List<SearchResultObject> Search(string keyword) { CseResource.ListRequest listRequest = customSearchService.Cse.List(); listRequest.Q = keyword; listRequest.Cx = cx; Console.WriteLine($"Search... {keyword}"); var items = listRequest.Execute().Items; var results = new List<SearchResultObject>(); foreach (var item in items) { string thumbnail = null; if (item.Pagemap != null) { // JObject 에서 썸네일 추출 foreach (var key in thumbnailKeyCandidates) { // 이미 썸네일을 찾았다면 탈출 if (!string.IsNullOrEmpty(thumbnail)) { break; } // 후보키를 JObject에서 찾을 수 없다면 스킵 if (!item.Pagemap.TryGetValue(key, out var jArrayObject)) { continue; } var jsonArray = JArray.FromObject(jArrayObject); foreach (var jsonObj in jsonArray) { dynamic obj = jsonObj; string src = obj.src; if (src == null) { continue; } // 찾은 썸네일 저장하고 탈출 thumbnail = src; break; } } } results.Add(new SearchResultObject { Title = item.Title, // Snippet이 비어있는 데이터는 Title로 대체 Snippet = item.Snippet ?? item.Title, Link = item.Link, Thumbnail = thumbnail }); } return results; } } }
namespace SpecFirst.Core.DecisionTable.Parser { using System; using System.Linq; using System.Xml.Linq; public sealed class TableTypeParser { public TableType Parse(XElement table) { var firstRow = table.Descendants("tr").First(); var column = firstRow.Descendants("th").Union(firstRow.Descendants("td")).First(); var splitValue = column.Value.Split(':'); if (splitValue.Length > 1) { return (TableType)Enum.Parse(typeof(TableType), splitValue[0].Trim(), true); } return TableType.Decision; } } }
using System; using System.Runtime.InteropServices; using ClangNet.Native; namespace ClangNet { /// <summary> /// Managed Clang Index Objective-C Property Declaration Info /// </summary> public class ClangIndexObjCPropertyDeclarationInfo : ClangIndexInfo { /// <summary> /// Native Clang Index Objective-C Property Declaration Info /// </summary> internal CXIdxObjCPropertyDeclInfo Info { get; } /// <summary> /// Clang Index Declaration Info /// </summary> public ClangIndexDeclarationInfo Declaration { get { return this.Info.DeclInfo.ToManaged<ClangIndexDeclarationInfo>(); } } /// <summary> /// Getter Clang Index Entity Info /// </summary> public ClangIndexEntityInfo Getter { get { return this.Info.Getter.ToManaged<ClangIndexEntityInfo>(); } } /// <summary> /// Setter Clang Index Entity Info /// </summary> public ClangIndexEntityInfo Setter { get { return this.Info.Setter.ToManaged<ClangIndexEntityInfo>(); } } /// <summary> /// Constructor /// </summary> /// <param name="address">Native Clang Index Objective-C Property Declaration Info Address</param> internal ClangIndexObjCPropertyDeclarationInfo(IntPtr address) : base(address) { this.Info = this.Address.ToNativeStuct<CXIdxObjCPropertyDeclInfo>(); } } }
namespace Memories.Business.Models { public class BookImageUI : BookUI { private byte[] _imageSource; public byte[] ImageSource { get { return _imageSource; } set { SetProperty(ref _imageSource, value); } } public BookImageUI() { UIType = Enums.BookUIEnum.ImageUI; } } }
namespace ComputerBlueprintContext { public class PowerConnectorDetails : IConnectionDetails, IPinoutProvider { public Pinout Pinout { get; } } }
using System; using System.Collections.Generic; namespace Cortside.Health.Models { /// <summary> /// Health /// </summary> public class HealthModel : ServiceStatusModel { /// <summary> /// The service identifier /// </summary> public string Service { get; set; } /// <summary> /// Build /// </summary> public BuildModel Build { get; set; } /// <summary> /// Checks /// </summary> public Dictionary<string, ServiceStatusModel> Checks { get; set; } /// <summary> /// Amount of time that the service has been running /// </summary> public TimeSpan Uptime { get; set; } } }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Oakland Software Incorporated" email="general@oaklandsoftware.com"/> // <version>$Revision$</version> // </file> using System; using System.Windows.Forms; using ICSharpCode.Core; using NoGoop.Util; namespace NoGoop.ObjBrowser.Panels { internal class ButtonPanel : System.Windows.Forms.Panel { internal const bool CANCEL = true; internal ButtonPanel(Form parent) : this(parent, CANCEL) { } internal ButtonPanel(Form parent, bool includeCancel) { Label l = new Label(); l.Dock = DockStyle.Fill; Controls.Add(l); Button ok = Utils.MakeButton(StringParser.Parse("${res:Global.OKButtonText}")); ok.Dock = DockStyle.Right; ok.DialogResult = DialogResult.OK; parent.AcceptButton = ok; Controls.Add(ok); if (includeCancel) { l = new Label(); l.Dock = DockStyle.Right; l.Width = 5; Controls.Add(l); Button cancel = Utils.MakeButton(StringParser.Parse("${res:Global.CancelButtonText}")); cancel.Dock = DockStyle.Right; cancel.DialogResult = DialogResult.Cancel; Controls.Add(cancel); } Height = Utils.BUTTON_HEIGHT; } } }
namespace Vimeo.Api.NetStandards.Types { public class File { } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using HorseShow.Model; using Parse; namespace HorseShow.Droid { public class ParseStorage : IParseStorage { static ParseStorage HsEventServiceInstance = new ParseStorage(); public static ParseStorage Default { get { return HsEventServiceInstance; } } public List<HSEventModel> Events { get; private set; } // Constructor protected ParseStorage() { Events = new List<HSEventModel>(); // https://parse.com/apps/YOUR_APP_NAME/edit#app_keys // ApplicationId, Windows/.NET/Client key //ParseClient.Initialize ("APPLICATION_ID", ".NET_KEY"); ParseClient.Initialize(Constants.ApplicationId, Constants.Key); } static HSEventModel DisciplineFromParseObject(ParseObject po) { var t = new HSEventModel(); t.discipline = Convert.ToString(po["discipline"]); return t; } static HSEventModel ScheduleFromParseObject(ParseObject po) { var t = new HSEventModel(); t.objectId = po.ObjectId; t.bubbleCnt = Convert.ToString(po["bubbleCnt"]); t.classGosCount = Convert.ToString(po["classGosCount"]); t.classId = Convert.ToString(po["classId"]); ////t.createdAt = Convert.ToString(po["createdAt"]); t.defaultScheduleGroup = Convert.ToString(po["defaultScheduleGroup"]); t.discipline = Convert.ToString(po["discipline"]); t.drawHeldWith = Convert.ToString(po["drawHeldWith"]); t.eventId = Convert.ToString(po["eventId"]); t.goCd = Convert.ToString(po["goCd"]); t.type = Convert.ToString(po["type"]); t.location = Convert.ToString(po["location"]); t.name = Convert.ToString(po["name"]); t.numRanked = Convert.ToString(po["numRanked"]); t.reportScores = Convert.ToString(po["reportScores"]); t.resultType = Convert.ToString(po["resultType"]); t.srcShowDb_showId = Convert.ToString(po["srcShowDb_showId"]); t.startDateTime = Convert.ToString(po["startDateTime"]); ////t.updatedAt = Convert.ToString(po["updatedAt"]); return t; } async public Task<List<HSEventModel>> GetSchedule(string _discipline) { bool exists = false; var query = ParseObject.GetQuery("HSEvent").WhereEqualTo("discipline", _discipline).OrderBy("stardatetime"); query = query.Limit(1000); var ie = await query.FindAsync(); var returnModel = new HSEventModel(); var tl = new List<HSEventModel>(); foreach (var t in ie) { returnModel = DisciplineFromParseObject(t); if (tl.Count == 0) tl.Add(returnModel); for (int i = 0; i < tl.Count; i++) { if (tl[i].discipline.Contains(returnModel.discipline)) exists = true; } if (!exists) tl.Add(returnModel); exists = false; } return tl; } async public Task<List<HSEventModel>> GetDiscipline() { bool exists = false; var query = ParseObject.GetQuery("HSEvent").Select("discipline"); query = query.Limit(1000); var ie = await query.FindAsync(); var returnModel = new HSEventModel(); var tl = new List<HSEventModel>(); foreach (var t in ie) { returnModel = DisciplineFromParseObject(t); if (tl.Count == 0) tl.Add(returnModel); for (int i = 0; i < tl.Count; i++) { if (tl[i].discipline.Contains(returnModel.discipline)) exists = true; } if (!exists) tl.Add(returnModel); exists = false; } return tl; } async public Task<List<HSEventModel>> GetSchedule(string _discipline) { //bool exists = false; var query = ParseObject.GetQuery("HSEvent").WhereEqualTo("discipline", _discipline).OrderBy("stardatetime"); query = query.Limit(1000); var ie = await query.FindAsync(); var returnModel = new HSEventModel(); var tl = new List<HSEventModel>(); foreach (var t in ie) { returnModel = ScheduleFromParseObject(t); //if (tl.Count == 0) // tl.Add(returnModel); //for (int i = 0; i < tl.Count; i++) //{ // if (tl[i].discipline.Contains(returnModel.discipline)) // exists = true; //} //if (!exists) tl.Add(returnModel); //exists = false; } return tl; } } }
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; using System.Threading.Tasks; namespace Gov.Jag.PillPressRegistry.Public.ViewModels { public enum ProductPurpose { [EnumMember(Value = "Producing Own Product")] ProducingOwnProduct = 931490000, [EnumMember(Value = "Manufacturing For Others")] ManufacturingForOthers = 931490001, } public class CustomProduct { public string id { get; set; } public string productdescriptionandintendeduse { get; set; } [JsonConverter(typeof(StringEnumConverter))] public ProductPurpose Purpose { get; set; } public string incidentId { get; set; } } }
namespace Schierle.Documentor.Test.Utils.EnumerableExtensionsTests { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public partial class EnumerableExtensionsTest { } }
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using DynamicSugar; using System.Dynamic; namespace DynamicSugarSharp_UnitTests{ [TestClass] public class StringFormat_UnitTests { [TestMethod] public void string_format() { var s = String.Format("[{0}] Age={1:000}", "TORRES", 45); Assert.AreEqual("[TORRES] Age=045",s); s = "[{0}] Age={1:000}".FormatString("TORRES", 45); Assert.AreEqual("[TORRES] Age=045",s); } [TestMethod] public void String_Format() { var s = String.Format("[{0}] Age={1:000}", "TORRES", 45); Assert.AreEqual("[TORRES] Age=045", s); string a = "[{0}] Age={1:000}"; s = a.FormatString("TORRES", 45); Assert.AreEqual("[TORRES] Age=045", s); } [TestMethod] public void String_Format__WithDictionary() { var dic = new Dictionary<string,object>() { { "LastName" , "TORRES" }, { "Age" , 45 } }; var s = "[{LastName}] Age={Age:000}".Template(dic); Assert.AreEqual("[TORRES] Age=045",s); } [TestMethod] public void String_Format__WithAnonymousType() { var s = "[{LastName}] Age={Age:000}".Template(new { LastName = "TORRES", Age = 45 }); Assert.AreEqual("[TORRES] Age=045", s); } [TestMethod,ExpectedException(typeof(ExtendedFormatException))] public void String_Format__WithAnonymousType_WithTypoInFormat() { var s = "[{LastName_BAD}] Age={Age:000}".Template(new { LastName = "TORRES", Age = 45 }); Assert.AreEqual("[TORRES] Age=045", s); } [TestMethod] public void String_Format__WithExpandoObject() { dynamic eo = new ExpandoObject(); eo.LastName = "TORRES"; eo.Age = 45; var s = "[{LastName}] Age={Age:000}".Template(eo as ExpandoObject); Assert.AreEqual("[TORRES] Age=045",s); } } }
// Copyright 2013 Cultural Heritage Agency of the Netherlands, Dutch National Military Museum and Trezorix bv // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Moq; using MvcContrib.TestHelper; using NUnit.Framework; using Trezorix.Checkers.DocumentChecker.Profiles; using Trezorix.ResourceRepository; using Trezorix.Checkers.ManagerApp.Controllers; using Trezorix.Checkers.ManagerApp.Models.Profile; namespace DocumentCheckerAppTests { [TestFixture] public class ProfileControllerTests { private const string PROFILE_ID = "theProfileId"; private const string SKOS_SOURCE = "mySkos"; private Mock<IProfileRepository> _mockedRepository; private ProfileController _profileController; [SetUp] public void Setup() { _mockedRepository = new Mock<IProfileRepository>(); _profileController = new ProfileController(_mockedRepository.Object); } [Test] public void Edit_post_with_a_null_id_should_create_new_profile() { // arrange _mockedRepository.Setup(r => r.Create(It.IsAny<Profile>())) .Returns(new Resource<Profile>(new Profile(), "somepath")) .Verifiable("No create called on repository"); _mockedRepository .Setup(r => r.Update(It.IsAny<Resource<Profile>>())) .Verifiable("the new profile wasn't saved"); var edit = new ProfileEditModel() { Key = "a profile key", Id = null }; // act var result = _profileController.Edit(edit); // assert _mockedRepository.VerifyAll(); } [Test] public void Edit_post_should_update_profile() { // arrange const string theId = "the_id"; var theProfile = new Resource<Profile>(new Profile(), "somepath"); _mockedRepository .Setup(r => r.Get(It.Is<string>(p => p == theId))) .Returns(theProfile) .Verifiable("No attempt was made to get the profile from the repository"); _mockedRepository .Setup(r => r.Update(It.Is<Resource<Profile>>(p => p == theProfile))) .Verifiable("no save call was made to the repository for the updated profile"); var edit = new ProfileEditModel() { Key = "a profile key", Id = theId }; // act var result = _profileController.Edit(edit); // assert _mockedRepository.VerifyAll(); } [Test] [ExpectedException(typeof(HttpException))] public void Edit_post_non_existing_profile_should_throw() { // arrange _mockedRepository .Setup(r => r.Get(It.IsAny<string>())) .Returns((Resource<Profile>) null); var edit = new ProfileEditModel() { Key = "a profile key", Id = "non existing id" }; // act var result = _profileController.Edit(edit); // assert } [Test] public void Edit_post_with_modelerrors_should_return_view() { // arrange var edit = new ProfileEditModel() { }; _profileController.ModelState.AddModelError("Key", "Missing name"); // act var result = _profileController.Edit(edit); // assert result.AssertResultIs<ViewResult>().ForView("Edit"); } [Test] public void Edit_post_valid_update_should_update_profile() { // arrange var profile = new Profile() { Key = "OrgProfileName", }; _mockedRepository .Setup(r => r.Get(It.IsAny<string>())) .Returns(new Resource<Profile>(profile, "somepath")); const string theKey = "new key"; var edit = new ProfileEditModel(profile, new List<SkosSourceBinding>() { new SkosSourceBinding() { Key = "skos1" }, new SkosSourceBinding() { Key = "skos2" }, new SkosSourceBinding() { Key = "skos3" }, }); edit.Id = "a-ID"; edit.Key = theKey; edit.Bindings = new List<BindingEditModel>() { new BindingEditModel() { Enabled = true, Key = "skos1"}, new BindingEditModel() { Enabled = true, Key = "skos2"}, new BindingEditModel() { Enabled = false, Key = "skos3"} }; // act var result = _profileController.Edit(edit); // assert Assert.AreEqual(theKey, profile.Key, "Key change didn't get through"); Assert.AreEqual(2, profile.SkosSourceBindings.Count(), "Should have 2 skossources"); Assert.IsTrue(profile.SkosSourceBindings.Any(b => b.Key == "skos1"), "Enabling skos source 1 didn't get through"); Assert.IsTrue(profile.SkosSourceBindings.Any(b => b.Key == "skos2"), "Enabling skos source 2 didn't get through"); } } }
namespace Anvil.Payloads.Request.Types { public class GeneratePdfHtml { public string? Html { get; set; } public string? Css { get; set; } } }
namespace Stopify.Services.Models { using System; using Microsoft.AspNetCore.Http; public class ProductCreateServiceModel { public string Name { get; set; } public decimal Price { get; set; } public IFormFile Picture { get; set; } public DateTime ManufacturedOn { get; set; } public int TypeId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Web; namespace CodapaloozaAPI.Models { [DataContract] public class Search { public class Coordinate { public double latitude { get; set; } public double longitude { get; set; } } public class Location { public List<string> address { get; set; } public string city { get; set; } public Coordinate coordinate { get; set; } public string country_code { get; set; } public string cross_streets { get; set; } public List<string> display_address { get; set; } public double geo_accuracy { get; set; } public List<string> neighborhoods { get; set; } public string postal_code { get; set; } public string state_code { get; set; } } public class Business { public List<List<string>> categories { get; set; } public string display_phone { get; set; } public string id { get; set; } public string image_url { get; set; } public bool is_claimed { get; set; } public bool is_closed { get; set; } public Location location { get; set; } public string mobile_url { get; set; } public string name { get; set; } public string phone { get; set; } public double rating { get; set; } public string rating_img_url { get; set; } public string rating_img_url_large { get; set; } public string rating_img_url_small { get; set; } public int review_count { get; set; } public string snippet_image_url { get; set; } public string snippet_text { get; set; } public string url { get; set; } } [DataMember] public List<Business> businesses { get; set; } [DataMember] public int total { get; set; } } }
using Bisner.Constants; using Bisner.Mobile.Core.Helpers; using Bisner.Mobile.Core.ViewModels; using Bisner.Mobile.Core.ViewModels.Chat; using Bisner.Mobile.Core.ViewModels.Dashboard; using Bisner.Mobile.Core.ViewModels.Feed; using MvvmCross.Core.ViewModels; namespace Bisner.Mobile.Core { public class BisnerAppStart : MvxNavigatingObject, IMvxAppStart { public void Start(object hint = null) { if (!string.IsNullOrWhiteSpace(Settings.RefreshToken)) { if (App.AppPlatform == AppPlatform.iOS && Settings.CustomLogin) { ShowViewModel<LauncherViewModel>(); } else { ShowViewModel<MainViewModel>(); } } else { // User has not logged in before ShowViewModel<LoginViewModel>(); } CheckNotifications(); } /// <summary> /// Checks on the App instance if any of the id's from a push notification have been set /// </summary> /// <returns></returns> private void CheckNotifications() { if (App.ConversationId != null) { ShowViewModel<ChatConversationViewModel>(new { id = App.ConversationId.Value }); App.ConversationId = null; } if (App.EventId != null) { ShowViewModel<EventViewModel>(new { id = App.EventId.Value }); App.EventId = null; } if (App.PostId != null) { ShowViewModel<DetailsViewModel>(new { postId = App.PostId.Value }); App.PostId = null; } if (App.GroupId != null) { ShowViewModel<FeedViewModel>(new { id = App.GroupId.Value, feedType = FeedType.Group }); App.GroupId = null; } } } }
using Abp; using System; using System.Collections.Generic; using System.Text; namespace PearAdmin.AbpTemplate.DataExporting.Excel.Dto { /// <summary> /// 从Excel导入记录请求参数 /// </summary> public class ImportRecordsFromExcelJobArgs { public int? TenantId { get; set; } public Guid BinaryObjectId { get; set; } public UserIdentifier User { get; set; } public byte[] Files { get; set; } } }
using WebMarkupMin.Core; namespace WebMarkupMin.Yui { /// <summary> /// YUI JS Minifier factory /// </summary> public sealed class YuiJsMinifierFactory : IJsMinifierFactory { /// <summary> /// Gets or sets a minification settings used to configure the YUI JS Minifier /// </summary> public YuiJsMinificationSettings MinificationSettings { get; set; } /// <summary> /// Constructs an instance of the YUI JS Minifier factory /// </summary> public YuiJsMinifierFactory() : this(new YuiJsMinificationSettings()) { } /// <summary> /// Constructs an instance of the YUI JS Minifier factory /// </summary> /// <param name="settings">Minification settings used to configure the YUI JS Minifier</param> public YuiJsMinifierFactory(YuiJsMinificationSettings settings) { MinificationSettings = settings; } #region IJsMinifierFactory implementation /// <summary> /// Creates a instance of the YUI JS Minifier /// </summary> /// <returns>Instance of the YUI JS Minifier</returns> public IJsMinifier CreateMinifier() { return new YuiJsMinifier(MinificationSettings); } #endregion } }
using System.IO; using System.Linq; namespace Forge.Forms.LiveReloading.Extensions { internal static class DirectoryExtensions { /// <summary> /// Finds the project root. /// </summary> /// <param name="directoryPath">The directory path.</param> /// <param name="maxUpwards">The maximum folders to search upwards.</param> /// <returns></returns> public static string FindProjectRoot(this string directoryPath, int maxUpwards = 6) { var directory = new DirectoryInfo(directoryPath); var count = 0; while (directory?.Parent != null && count < maxUpwards) { if (directory.GetFiles().Any(i => i.Extension == ".csproj")) { return directory.FullName; } directory = directory.Parent; count++; } return ""; } } }
/*Copyright 2015 Sean Finch Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ using UnityEngine; using System.Collections.Generic; public class BoardCursorMirror:BoardCursorCore { private BoardCursorActualCore parent; private float maxY; public void Setup(BoardCursorActualCore p, TweenHandler t, bool show = true) { parent = p; isShown = show; th = t; InitializeMembers(); x = 4; y = 0; maxY = 1.85f - (boardheight - 1) * Consts.TILE_SIZE; UpdateMirrorCursorPos(true); FinishUpdate(); } public override void DoUpdate(int max = -1) { cursor.GetComponent<SpriteRenderer>().sprite = sheet[parent.frozen?2:(parent.penetr?1:0)]; x = boardwidth - 1 - parent.getX(); y = boardheight - 1 - parent.getY(); UpdateMirrorCursorPos(); FinishUpdate(); } private void UpdateMirrorCursorPos(bool skipTween = false) { if(!isShown) { return; } if(prevx == x && prevy == y) { return; } Vector3 pos = new Vector3((xOffset + x) * Consts.TILE_SIZE, maxY + y * Consts.TILE_SIZE); if(skipTween) { cursor.transform.position = pos; } else { th.DoTween(cursor, pos); } } }
namespace P03_StudentSystem { using System; class StartUp { static void Main(string[] args) { StudentSystem studentSystem = new StudentSystem(); while (true) { string input = Console.ReadLine(); studentSystem.ParseCommand(input); } } } }
using Subsonic.Client.EventArgs; using Subsonic.Client.Handlers; using Subsonic.Client.Models; using System; namespace Subsonic.Client.Monitors { public class ChatMonitor<T> : IObserver<ChatModel> where T : class, IDisposable { private IDisposable _cancellation; public event Action<ChatMonitor<T>, ChatEventArgs> PropertyChanged; public ChatHandler<T> ChatHandler { get; set; } public bool Disposed { get; set; } public void OnCompleted() { Disposed = true; } public void OnError(Exception error) { } public void OnNext(ChatModel value) { try { OnPropertyChanged(value); } catch (Exception) { //throw; } } public void Subscribe(ChatHandler<T> provider) { ChatHandler = provider; _cancellation = provider.Subscribe(this); } public void Unsubscribe() { Disposed = true; _cancellation.Dispose(); OnPropertyChanged(null); } protected virtual void OnPropertyChanged(ChatModel chatItem) { var handler = PropertyChanged; handler?.Invoke(this, new ChatEventArgs(chatItem)); } } }
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/Beef using Beef.Entities; using NUnit.Framework; using System.Collections.Generic; namespace Beef.Core.UnitTest.Core { [TestFixture] public class ValidationExceptionTest { [Test] public void Ctor_NullMessages() { var vex = new ValidationException("Blah", (IEnumerable<MessageItem>)null); Assert.IsNotNull(vex); Assert.AreEqual("Blah", vex.Message); Assert.AreEqual(0, vex.Messages.Count); } } }
using System; using System.Collections.Generic; using System.Text; using Traveller.Core.Providers; using Traveller.Models; using Traveller.Models.Abstractions; using Traveller.Models.Vehicles.Abstractions; namespace Traveller.Core { public class Engine { private const string TerminationCommand = "Exit"; private const string NullProvidersExceptionMessage = "cannot be null."; private static readonly Engine instanceHolder = new Engine(); private readonly List<IVehicle> vehicles; private readonly List<IJourney> journeys; private readonly List<ITicket> tickets; private StringBuilder Builder = new StringBuilder(); private Engine() { this.vehicles = new List<IVehicle>(); this.journeys = new List<IJourney>(); this.tickets = new List<ITicket>(); } public static Engine Instance { get { return instanceHolder; } } public IList<IVehicle> Vehicles { get { return this.vehicles; } } public IList<IJourney> Journeys { get { return this.journeys; } } public IList<ITicket> Tickets { get { return this.tickets; } } public void Start() { while (true) { try { var commandAsString = Console.ReadLine(); if (commandAsString.ToLower() == TerminationCommand.ToLower()) { Console.Write(this.Builder.ToString()); break; } this.ProcessCommand(commandAsString); } catch (Exception ex) { this.Builder.AppendLine(ex.Message); } } } private void ProcessCommand(string commandAsString) { if (string.IsNullOrWhiteSpace(commandAsString)) { throw new ArgumentNullException("Command cannot be null or empty."); } var parser = new CommandParser(); var command = parser.ParseCommand(commandAsString); var parameters = parser.ParseParameters(commandAsString); var executionResult = command.Execute(parameters); this.Builder.AppendLine(executionResult); } } }