content
stringlengths
23
1.05M
// Copyright (c) XRTK. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. namespace XRTK.Extensions { public static class SystemNumericsExtensions { /// <summary> /// Converts a Numerics <see cref="System.Numerics.Vector3"/> to a Unity <see cref="UnityEngine.Vector3"/>. /// </summary> /// <param name="v">Vector value to convert.</param> /// <returns><see cref="UnityEngine.Vector3"/>.</returns> public static UnityEngine.Vector3 ToUnity(this System.Numerics.Vector3 v) { return new UnityEngine.Vector3(v.X, v.Y, -v.Z); } /// <summary> /// Converts a Unity <see cref="UnityEngine.Vector3"/> to a Numerics <see cref="System.Numerics.Vector3"/>. /// </summary> /// <param name="v">Vector value to convert.</param> /// <returns><see cref="System.Numerics.Vector3"/>.</returns> public static System.Numerics.Vector3 ToNumericsVector3(this UnityEngine.Vector3 v) { return new System.Numerics.Vector3(v.x, v.y, -v.z); } /// <summary> /// Converts a Numerics <see cref="System.Numerics.Quaternion"/> to a Unity <see cref="UnityEngine.Quaternion"/>. /// </summary> /// <param name="q">Quaternion value to convert.</param> /// <returns><see cref="UnityEngine.Quaternion"/>.</returns> public static UnityEngine.Quaternion ToUnity(this System.Numerics.Quaternion q) { return new UnityEngine.Quaternion(-q.X, -q.Y, q.Z, q.W); } /// <summary> /// Converts a Unity <see cref="UnityEngine.Quaternion"/> to a Numerics <see cref="System.Numerics.Quaternion"/>. /// </summary> /// <param name="q">Quaternion value to convert.</param> /// <returns><see cref="System.Numerics.Quaternion"/>.</returns> public static System.Numerics.Quaternion ToNumericsQuaternion(this UnityEngine.Quaternion q) { return new System.Numerics.Quaternion(-q.x, -q.y, q.z, q.w); } } }
using Data.Entities; using Domain; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Data { public class UserRepository : IUserRepository { private readonly HLContext _db; public UserRepository(HLContext db) { _db = db; } public IEnumerable<Domain.User> GetUsers() { return _db.User.Select(x => Mapper.Map(x)); } public Domain.User GetUserByUserid(int userid) { var element = _db.User.Where(a => a.Id == userid).FirstOrDefault(); if (element != null) return Mapper.Map(element); else return null; } public Domain.User GetUserByUsername(string username) { var element = _db.User.Where(a => a.Username == username).FirstOrDefault(); if (element != null) return Mapper.Map(element); else return null; } public bool AddUser(Domain.User user) { bool check = false; Data.Entities.User x = _db.User.Where(a => a.Username.Equals(user.username)).FirstOrDefault(); if (x != null) { check = false; } else { _db.User.Add(Mapper.Map(user)); check = true; } return check; } public bool DeleteUser(Domain.User user) { bool success = false; Data.Entities.User x = _db.User.Where(a => a.Username.Equals(user.username)).FirstOrDefault(); if (x != null) { _db.User.Remove(x); //_db.SaveChanges(); success = true; } return success; } public bool validatelogin(string username, string password) { bool validate = false; var element = _db.User.Where(a => a.Username == username).FirstOrDefault(); if (element.Password == password) { validate = true; } return validate; } public bool validateusername(string username) { bool validateuser = false; var element = _db.User.Where(a => a.Username == username).FirstOrDefault(); if (element != null) { validateuser = true; } return validateuser; } public List<Domain.User> TeamUsers(string teamname) { List<Domain.User> usersinteam = new List<Domain.User>(); var teamwanted = _db.Team.Where(a => a.Teamname == teamname).FirstOrDefault(); var teamwantedid = teamwanted.Id; var usersteaminteam = _db.UserTeam.Where(a => a.Teamid == teamwantedid).Include("User"); foreach (var userteaminteam in usersteaminteam) { usersinteam.Add(GetUserByUserid(userteaminteam.Userid)); } return usersinteam; } public void Save() { _db.SaveChanges(); } } }
// // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SharePointPnP.ProvisioningApp.Infrastructure.DomainModel.Provisioning { public class SharePointSite { public String Id { get; set; } public String DisplayName { get; set; } public String Name { get; set; } public DateTime CreatedDateTime { get; set; } public DateTime LastModifiedDateTime { get; set; } public String WebUrl { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace LogMagic.Tokenisation { class MessageToken { public MessageToken(TokenType tokenType, string name, string format) { } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using ControlledByTests.Server.Services; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Philadelphia.ServerSideUtils; using Philadelphia.Common; using Philadelphia.Server.Common; using Philadelphia.Server.ForAspNetCore; using Philadelphia.Testing.DotNetCore; namespace ControlledByTests.Server { public class ForwardToServerControllerLoggerImplementation : ILoggerImplementation { private readonly ConsoleBasedControllerAsLifeTimeFilter _impl; public ForwardToServerControllerLoggerImplementation(ConsoleBasedControllerAsLifeTimeFilter impl) { _impl = impl; } private void LogImpl(string level, Type sender, string message, object[] args) { _impl.LogAsReply( DateTime.UtcNow.ToString("o") + " " + this.FlattenSafe(level, sender, message, args)); } public void Error(Type sender, string message, params object[] args) { LogImpl("ERROR", sender, message, args); } public void Info(Type sender, string message, params object[] args) { LogImpl("INFO", sender, message, args); } public void Debug(Type sender, string message, params object[] args) { LogImpl("DEBUG", sender, message, args); } } public class Startup { private readonly BaseStartup _baseStartup; private readonly ConsoleBasedControllerAsLifeTimeFilter _ltFilter; private readonly LifeStyleContainer _lsc = new LifeStyleContainer(); public Startup() { _lsc.set(LifeStyle.Transient); //least surprising var assemblies = new [] { typeof(Startup).Assembly, typeof(ControlledByTests.Domain.Dummy).Assembly }; var dllsLoc = Path.GetDirectoryName(typeof(Startup).Assembly.Location); Directory.SetCurrentDirectory(dllsLoc); //to make configuration reading from disk working _ltFilter = new ConsoleBasedControllerAsLifeTimeFilter(); var staticResourcesDir = Path.Combine(dllsLoc, "../../.."); Logger.ConfigureImplementation(new ForwardToServerControllerLoggerImplementation(_ltFilter)); _baseStartup = new BaseStartup( _lsc, _ => {}, assemblies, ServerSettings.CreateDefault() .With(x => x.CustomStaticResourceDirs = new []{ staticResourcesDir })); } public void ConfigureServices(IServiceCollection services) { var di = new ServiceCollectionAdapterAsDiContainer(services, _lsc); di.RegisterInstance<IRegisterServiceInvocation>(_ltFilter, LifeStyle.Singleton); _baseStartup.ConfigureServices(services, _ltFilter); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { _baseStartup.Configure(app, env); } } public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) { Logger.ConfigureImplementation(new ConsoleWritelineLoggerImplementation()); return WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseUrls(Configuration.getConfigVarOrDefault("http://0.0.0.0:8090/", "SERVER_LISTEN_URL")) .SuppressStatusMessages(true) //to disable messages such as "Hosting environment: <blah>" etc .ConfigureLogging(b => b.AddFilter(_ => false)); //to disable per request messages } } }
using System.ComponentModel; namespace StackingEntities.Model.Enums { public enum VillagerCareer { Default=0, Farmer = 1, Fisherman = 2, Shepherd = 3, Fletcher = 4, Librarian = 1, Cleric = 1, Armorer = 1, [Description("Weapon Smith")] WeaponSmith = 2, [Description("Tool Smith")] ToolSmith = 3, Butcher = 1, Leatherworker = 2 } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GeoIP.Models { public class DataSource { public string MaxMind { get; set; } public string IP2Location { get; set; } } }
using Content.Client.Weapons.Ranged.Systems; namespace Content.Client.Weapons.Ranged.Components; /// <summary> /// Visualizer for gun mag presence; can change states based on ammo count or toggle visibility entirely. /// </summary> [RegisterComponent, Friend(typeof(GunSystem))] public sealed class MagazineVisualsComponent : Component { /// <summary> /// What RsiState we use. /// </summary> [DataField("magState")] public string? MagState; /// <summary> /// How many steps there are /// </summary> [DataField("steps")] public int MagSteps; /// <summary> /// Should we hide when the count is 0 /// </summary> [DataField("zeroVisible")] public bool ZeroVisible; } public enum GunVisualLayers : byte { Base, BaseUnshaded, Mag, MagUnshaded, }
using System.Collections.Generic; namespace Marked.Serializer.Test { public class PrimitiveTestObject { public int IntegerValue { get; set; } public string StringValue { get; set; } public float SingleValue { get; set; } } public class ComplexTestObject { public int IntegerValue { get; set; } public ComplexChildObject Child { get; set; } } public class ComplexChildObject { public string Text { get; set; } public ComplexTestObject Parent { get; set; } } public class DirectCycleTestObject { public int Value { get; set; } public DirectCycleTestObject Child { get; set; } } public class ListCycleTestObject { public int Value { get; set; } public List<ListCycleTestObject> Children { get; set; } } public class BackingFieldTestObject { [SerializerUseBackingField] public string Value { get; } public BackingFieldTestObject() { Value = null; } public BackingFieldTestObject(string value) { Value = value; } } }
namespace act.core.data { public enum JustificationTypeConstant { Feature, Application, Package, Port } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Data; using Microsoft.EntityFrameworkCore; using Models.Diagnosis; using Xunit; namespace Tests.Diagnosis { public class AssessmentTest { readonly DbContextOptions<CloudCureDbContext> _options; public AssessmentTest() { _options = new DbContextOptionsBuilder<CloudCureDbContext>() .UseSqlite("Filename = AssessmentTest.db; Foreign Keys=False").Options; Seed(); } [Fact] public void SearchByDiagnosisIdShouldReturnResults() { using (var context = new CloudCureDbContext(_options)) { IAssessmentRepository repository = new AssessmentRepository(context); var patient = repository.SearchByDiagnosisId(1); Assert.NotNull(patient); } } [Fact] public void SearchByDiagnosisIdShouldThrowNullExceptionOnNoResults() { using (var context = new CloudCureDbContext(_options)) { IAssessmentRepository repository = new AssessmentRepository(context); Assert.Empty(repository.SearchByDiagnosisId(-1)); } } [Fact] public void GetbyIdShouldReturnAssessmentId() { using (var context = new CloudCureDbContext(_options)) { IAssessmentRepository repository = new AssessmentRepository(context); var assessment = repository.GetById(1); Assert.Equal(1, assessment.Id); } } // [Fact] // public void GetPatientAssessmentShouldThrowException() // { // using ( var context = new CloudCureDbContext(_options)) // { // IAssessmentRepository repository = new AssessmentRepository(context); // Assert.Empty(repository.SearchByDiagnosisId(-1)); // } // } void Seed() { using (var context = new CloudCureDbContext(_options)) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); context.Assessments.AddRange( new Assessment { DiagnosisId = 1, PainAssessment = "asdfas", PainScale = 2, ChiefComplaint = "dfdssdf", HistoryOfPresentIllness = "dssdfs", }, new Assessment { DiagnosisId = 2, PainAssessment = "asdfas", PainScale = 2, ChiefComplaint = "dfdssdf", HistoryOfPresentIllness = "dssdfs", }); context.SaveChanges(); } } } }
using System; namespace NControls { public class PropertyItemWString : PropertyItemString { protected unsafe override string GetValue() { uint num = (uint)(*(int*)this.Var); return new string((char*)((num == 0u) ? <Module>.?EmptyString@?$GBaseString@_W@@1PB_WB : num)); } protected unsafe override void SetValue(string value) { GBaseString<wchar_t> gBaseString<wchar_t>; GBaseString<wchar_t>* ptr = <Module>.GBaseString<wchar_t>.{ctor}(ref gBaseString<wchar_t>, value); bool flag; try { flag = (((<Module>.GBaseString<wchar_t>.Compare(this.Var, ptr, false) != 0) ? 1 : 0) != 0); } catch { <Module>.___CxxCallUnwindDtor(ldftn(GBaseString<wchar_t>.{dtor}), (void*)(&gBaseString<wchar_t>)); throw; } if (gBaseString<wchar_t> != null) { <Module>.free(gBaseString<wchar_t>); } if (flag) { <Module>.GBaseString<wchar_t>.=(this.Var, value); this.Host.RaiseItemChanged(); } } public new void {dtor}() { GC.SuppressFinalize(this); this.Finalize(); } } }
using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using stellar_dotnet_sdk; using stellar_dotnet_sdk.responses; using stellar_dotnet_sdk.responses.page; namespace stellar_dotnet_sdk_test.responses { [TestClass] public class OfferPageDeserializerTest { [TestMethod] public void TestDeserialize() { var json = File.ReadAllText(Path.Combine("testdata", "offerPage.json")); var offerResponsePage = JsonSingleton.GetInstance<Page<OfferResponse>>(json); AssertTestData(offerResponsePage); } [TestMethod] public void TestSerializeDeserialize() { var json = File.ReadAllText(Path.Combine("testdata", "offerPage.json")); var offerResponsePage = JsonSingleton.GetInstance<Page<OfferResponse>>(json); var serialized = JsonConvert.SerializeObject(offerResponsePage); var back = JsonConvert.DeserializeObject<Page<OfferResponse>>(serialized); AssertTestData(back); } //Before Horizon 1.0.0 the ID in the json was a long. [TestMethod] public void TestDeserializePre100() { var json = File.ReadAllText(Path.Combine("testdata", "offerPagePre100.json")); var offerResponsePage = JsonSingleton.GetInstance<Page<OfferResponse>>(json); AssertTestData(offerResponsePage); } //Before Horizon 1.0.0 the ID in the json was a long. [TestMethod] public void TestSerializeDeserializePre100() { var json = File.ReadAllText(Path.Combine("testdata", "offerPagePre100.json")); var offerResponsePage = JsonSingleton.GetInstance<Page<OfferResponse>>(json); var serialized = JsonConvert.SerializeObject(offerResponsePage); var back = JsonConvert.DeserializeObject<Page<OfferResponse>>(serialized); AssertTestData(back); } public static void AssertTestData(Page<OfferResponse> offerResponsePage) { Assert.AreEqual(offerResponsePage.Records[0].Id, "241"); Assert.AreEqual(offerResponsePage.Records[0].Seller, "GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD"); Assert.AreEqual(offerResponsePage.Records[0].PagingToken, "241"); Assert.AreEqual(offerResponsePage.Records[0].Selling, Asset.CreateNonNativeAsset("INR", "GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD")); Assert.AreEqual(offerResponsePage.Records[0].Buying, Asset.CreateNonNativeAsset("USD", "GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD")); Assert.AreEqual(offerResponsePage.Records[0].Amount, "10.0000000"); Assert.AreEqual(offerResponsePage.Records[0].Price, "11.0000000"); Assert.AreEqual(offerResponsePage.Records[0].LastModifiedLedger, 22200794); Assert.AreEqual(offerResponsePage.Records[0].LastModifiedTime, "2019-01-28T12:30:38Z"); Assert.AreEqual(offerResponsePage.Links.Next.Href, "https://horizon-testnet.stellar.org/accounts/GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD/offers?order=asc&limit=10&cursor=241"); Assert.AreEqual(offerResponsePage.Links.Prev.Href, "https://horizon-testnet.stellar.org/accounts/GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD/offers?order=desc&limit=10&cursor=241"); Assert.AreEqual(offerResponsePage.Links.Self.Href, "https://horizon-testnet.stellar.org/accounts/GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD/offers?order=asc&limit=10&cursor="); } } }
using System; using UnityEngine; using UnityEngine.Serialization; using UnityEngine.UI; namespace MaterialLibrary.Hexagons { [ExecuteAlways] public class HexShaderExposer : MonoBehaviour { [SerializeField] private Image image; [FormerlySerializedAs("_glowIntensity")] [SerializeField] private float glowIntensity; private float _glowIntensityCache; private static readonly int GlowIntensity = Shader.PropertyToID("_GlowIntensity"); private const float Tolerance = 0.1f; private void Awake() { _glowIntensityCache = image.material.GetFloat(GlowIntensity); } private void LateUpdate() { if (!(Math.Abs(glowIntensity - _glowIntensityCache) > Tolerance)) return; _glowIntensityCache = glowIntensity; image.material.SetFloat(GlowIntensity, glowIntensity); } } }
using Panama.Core.Entities; using System.Collections.Generic; namespace Panama.Core.Commands { public interface ICommand { void Execute(List<IModel> data); } }
using System; using System.Collections.Generic; using HealthClubs.Data.Core.Models; namespace HealthClubs.Data.Store.Contracts { public interface IBusinessRepository : IDisposable { IEnumerable<Business> GetBusinessEntities(); } }
using System.Threading; using Qsi.Data; using Qsi.Parsing; using Qsi.Tree; using Qsi.Trino.Internal; using Qsi.Trino.Tree.Visitors; using Qsi.Utilities; namespace Qsi.Trino { using static SqlBaseParser; public class TrinoParser : IQsiTreeParser { public IQsiTreeNode Parse(QsiScript script, CancellationToken cancellationToken = default) { var (_, result) = SqlParser.Parse(script.Script, p => p.singleStatement()); var statement = result.statement(); switch (statement) { case InsertIntoContext insertInto: return ActionVisitor.VisitInsertInto(insertInto); case UpdateContext update: return ActionVisitor.VisitUpdate(update); case DeleteContext delete: return ActionVisitor.VisitDelete(delete); case StatementDefaultContext statementDefault: return TableVisitor.VisitQuery(statementDefault.query()); case MergeContext merge: return ActionVisitor.VisitMerge(merge); case CreateViewContext createView: return ActionVisitor.VisitCreateView(createView); case UseContext use: return ActionVisitor.VisitUse(use); default: throw TreeHelper.NotSupportedTree(statement); } } } }
@model Piranha.Models.Manager.CategoryModels.EditModel @section Head { <script type="text/javascript"> $(document).ready(function () { $('#Category_Name').focus(); }); </script> } @section Toolbar { @Html.Partial("Partial/Tabs") <div class="toolbar"> <div class="inner"> <ul> <li><a class="save submit">@Piranha.Resources.Global.ToolbarSave</a></li> <li><a href="@Url.Action("delete", new { id = Model.Category.Id })" class="delete">@Piranha.Resources.Global.ToolbarDelete</a></li> <li><a href="@Url.Action("index", "category")" class="back">@Piranha.Resources.Global.ToolbarBack</a></li> <li><a href="@Url.Action("edit", new { id = Model.Category.Id })" class="refresh">@Piranha.Resources.Global.ToolbarReload</a></li> </ul> <div class="clear"></div> </div> </div> } @{ Html.BeginForm() ; } @Html.HiddenFor(m => m.Category.Id) @Html.HiddenFor(m => m.Category.PermalinkId) @Html.HiddenFor(m => m.Category.IsNew) @Html.HiddenFor(m => m.Category.Created) @Html.HiddenFor(m => m.Category.CreatedBy) @Html.HiddenFor(m => m.Permalink.IsNew) @Html.HiddenFor(m => m.Permalink.Id) @Html.HiddenFor(m => m.Permalink.Type) @Html.HiddenFor(m => m.Permalink.Created) @Html.HiddenFor(m => m.Permalink.CreatedBy) <div class="grid_12"> <div class="box"> <div class="title"><h2>@Piranha.Resources.Global.Information</h2></div> <div class="inner"> <ul class="form"> <li> @Html.LabelFor(m => m.Category.Name) <div class="input"> @Html.TextBoxFor(m => m.Category.Name)</div> @Html.ValidationMessageFor(m => m.Category.Name) </li> <li class="protected"> @Html.LabelFor(m => m.Category.Permalink) @if (!Model.Category.IsNew) { <p>@Piranha.WebPages.WebPiranha.GetSiteUrl()@Url.GetPermalink(Model.Category.Permalink).ToLower()</p> } else { <p><i>@Piranha.Resources.Category.PermalinkDescription</i></p> } <div class="input"> @Html.TextBoxFor(m => m.Permalink.Name)</div> <a class="locked"></a> </li> <li> @Html.LabelFor(m => m.Category.Description) <div class="input"> @Html.TextAreaFor(m => m.Category.Description)</div> </li> <li> @Html.LabelFor(m => m.Category.ParentId) <div class="input"> @Html.DropDownListFor(m => m.Category.ParentId, Model.Categories)</div> </li> </ul> </div> </div> @if (Model.Extensions.Count > 0) { @Html.EditorFor(m => m.Extensions) } </div> @{ Html.EndForm() ; }
namespace Zaaby.Extensions.Configuration.Consul; public static class ConsulConfigurationExtensions { public static IConfigurationBuilder AddConsul(this IConfigurationBuilder builder, Action<ConsulClientConfiguration>? configOverride = null, Action<HttpClient>? clientOverride = null, Action<HttpClientHandler>? handlerOverride = null, string folder = "/", string? key = null) { builder.Add(new ConsulConfigurationSource(configOverride, clientOverride, handlerOverride, folder, key)); return builder; } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Unosquare.Tubular.AspNetCoreSample.Models { public class Order { public Order() { Details = new HashSet<OrderDetail>(); } [Key] public int OrderId { get; set; } public string CustomerName { get; set; } public string CarrierName { get; set; } public bool IsShipped { get; set; } public decimal Amount { get; set; } public DateTime ShippedDate { get; set; } public string CreatedUserId { get; set; } public int? WarehouseId { get; set; } public int OrderType { get; set; } public string Address { get; set; } public string ShipperCity { get; set; } public string PhoneNumber { get; set; } public string PostalCode { get; set; } public string Comments { get; set; } //public virtual SystemUser CreatedUser { get; set; } public ICollection<OrderDetail> Details { get; set; } } }
using System; using System.Linq; using Autofac.Multitenant; using Microsoft.AspNetCore.Http; namespace AutofacNetcore2 { public class TenantIdentitificationStrategy : ITenantIdentificationStrategy { private readonly IHttpContextAccessor httpContextAccessor; public static readonly string[] TenantIds = { "tenantId1", "tenantId2" }; public TenantIdentitificationStrategy(IHttpContextAccessor httpContextAccessor) { this.httpContextAccessor = httpContextAccessor; } public bool TryIdentifyTenant(out object tenantId) { tenantId = httpContextAccessor?.HttpContext?.Request.Headers["tenantId"]; var tenantIdStringed = tenantId?.ToString(); return !string.IsNullOrWhiteSpace(tenantIdStringed) && TenantIdentitificationStrategy.TenantIds.Contains(tenantIdStringed, StringComparer.InvariantCultureIgnoreCase); } } }
using System; using System.Collections.Generic; using FrameworkTester.ViewModels.Interfaces; using GalaSoft.MvvmLight.Command; using WinBiometricDotNet; namespace FrameworkTester.DesignTimes { public sealed class WinBioAsyncOpenSessionViewModel : WinBioViewModel, IWinBioAsyncOpenSessionViewModel { public RelayCommand AddWindowCommand { get; } public RelayCommand CancelCommand { get; } public bool EnableWait { get; set; } public bool Async { get; set; } public bool EnableChildWindows { get; } public bool EnableMessageCode { get; } public IHandleRepositoryViewModel<ISessionHandleViewModel> HandleRepository { get; } public uint MessageCode { get; set; } public IEnumerable<AsyncNotificationMethod> Methods { get; set; } public AsyncNotificationMethod SelectedMethod { get; set; } public UIntPtr SessionHandle { get; } } }
using System.Collections.Generic; namespace OmniSharp.MSBuild.Models.Events { public class MSBuildProjectDiagnosticsEvent { public const string Id = "MsBuildProjectDiagnostics"; public string FileName { get; set; } public IEnumerable<MSBuildDiagnosticsMessage> Warnings { get; set; } public IEnumerable<MSBuildDiagnosticsMessage> Errors { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileExplorer.ViewModels { public class FE_ThisPC_Page_VM : FE_Base_VM { #region Private Variables private string saneep; #endregion #region Public Variables #endregion #region Constructors #endregion #region Methods #endregion } }
using System; namespace MQTTnetApp.Pages.Connection.State; public static class ConnectionPageStateFactory { public static ConnectionPageState Create(ConnectionPageViewModel viewModel) { if (viewModel == null) { throw new ArgumentNullException(nameof(viewModel)); } var state = new ConnectionPageState(); foreach (var item in viewModel.Items.Collection) { state.Connections.Add(new ConnectionState { Name = item.Name, Host = item.ServerOptions.Host, Port = item.ServerOptions.Port, ClientId = item.SessionOptions.ClientId, UserName = item.SessionOptions.UserName, AuthenticationMethod = item.SessionOptions.AuthenticationMethod, ProtocolVersion = item.ServerOptions.SelectedProtocolVersion.Value, KeepAliveInterval = item.SessionOptions.KeepAliveInterval, Transport = item.ServerOptions.SelectedTransport.Value, TlsVersion = item.ServerOptions.SelectedTlsVersion.Value }); } return state; } }
using NUnit.Framework; using System.Collections.Generic; using System.Threading; using System; namespace Tests { public class Tests { [SetUp] public void Setup() { } [Test] [SetCulture("tr-TR")] public void Test1() { TestHashSetComparison(StringComparer.OrdinalIgnoreCase); } [Test] public void Test2() { TestHashSetComparison(StringComparer.OrdinalIgnoreCase); } [Test] [SetCulture("tr-TR")] public void Test3() { TestHashSetComparison(StringComparer.OrdinalIgnoreCase); } private static void TestHashSetComparison(IEqualityComparer<string> comparer) { Console.WriteLine(Thread.CurrentThread.CurrentCulture); var set = new HashSet<string>(comparer) { "A", }; Assert.IsTrue(set.Contains("a")); } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.ComponentModel; using MS.Internal.PresentationCore; namespace MS.Internal { /// <summary> /// Allows for localizing custom categories. /// </summary> /// <remarks> /// This class could be shared amongst any of the assemblies if desired. /// </remarks> internal sealed class CustomCategoryAttribute : CategoryAttribute { internal CustomCategoryAttribute() : base() { } internal CustomCategoryAttribute(string category) : base(category) { } protected override string GetLocalizedString(string value) { string s = SR.Get(value); if (s != null) { return s; } else { return value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ServiceModel; namespace WcfService { [ServiceContract] public interface IWcfReliableService { [OperationContract] int GetNextNumber(); [OperationContract] string Echo(string echo); } [ServiceContract] public interface IOneWayWcfReliableService { [OperationContract(IsOneWay = true)] void OneWay(string text); } [ServiceContract(CallbackContract = typeof(IWcfReliableDuplexService))] public interface IWcfReliableDuplexService { [OperationContract] string DuplexEcho(string echo); } }
using System.Threading.Tasks; namespace Ray.DistributedTx.Abstractions { public interface IDistributedTx { Task CommitTransaction(string transactionId); Task FinishTransaction(string transactionId); Task RollbackTransaction(string transactionId); } }
using System; using System.Collections.Generic; using System.Linq; using NeodymiumDotNet.Optimizations; namespace NeodymiumDotNet { internal class RawNdArrayImpl<T> : MutableNdArrayImpl<T>, IBufferNdArrayImpl<T> { private readonly Allocation<T> _bufferCollector; /// <summary> /// NOTE: This array may be managed by ArrayPool. /// Do not capture with potential of lifetime extension. /// </summary> public Memory<T> Buffer => _bufferCollector.Memory; ReadOnlyMemory<T> IBufferNdArrayImpl<T>.Buffer => Buffer; /// <inheritdoc /> /// <summary> /// The element count when this NdArray was flatten. /// </summary> public override int Length { get; } /// <inheritdoc /> /// <summary> /// Create new RawNdArrayImpl{T} object. /// </summary> /// <param name="shape"></param> public RawNdArrayImpl(IndexArray shape) : base(shape) { Length = Shape.TotalLength; _bufferCollector = new Allocation<T>(Length); } protected override ref T GetItemRef(int flattenIndex) => ref Buffer.Span[flattenIndex]; protected override ref T GetItemRef(ReadOnlySpan<int> shapedIndices) => ref Buffer.Span[ToFlattenIndex(Shape, shapedIndices)]; protected override void CopyToCore(Span<T> dest) { Buffer.Span.CopyTo(dest); } public override T[] ToArray() => Buffer.ToArray(); } }
// See https://aka.ms/new-console-template for more information using Microsoft.EntityFrameworkCore; using SamuraiApp.Data; using SamuraiApp.Domain; SamuraiContext _context = new SamuraiContext(); await StartProgram(); async Task StartProgram() { _context.Database.EnsureCreated(); await GetSamurais("Before Add:"); await AddSamurai(); await GetSamurais("After Add:"); Console.WriteLine("After Add:"); Console.Write("Press any key..."); Console.ReadKey(); } async Task AddSamurai() { var samurai = new Samurai {Name = "Julie"}; await _context.Samurais.AddAsync(samurai); await _context.SaveChangesAsync(); } async Task GetSamurais(string text) { var samurais = await _context.Samurais.ToListAsync(); Console.WriteLine($"{text}: Samurai count is {samurais.Count}"); foreach (var samurai in samurais) { Console.WriteLine(samurai.Name); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Com.Ctrip.Soa.Caravan.Collections.Concurrent.CircularBuffer.TimeBucket.Buffer { public abstract class Bucket { public long TimeInMilliseconds { get; protected set; } protected Bucket(long timeInMilliseconds) { TimeInMilliseconds = timeInMilliseconds; } } }
namespace p07._01.InfernoInfinity.Models.Weapons { using System.Collections.Generic; using System.Linq; using System.Text; using Contracts; using p07._01.InfernoInfinity.Enums; using p07._01.InfernoInfinity.Models.Gems.Contracts; public abstract class Weapon : IWeapon { private int minDamage; private int maxDamage; private IGem[] sockets; protected Weapon( string name, int minDamage, int maxDamage, int numSockets, LevelRarity levelRarity) { this.Name = name; this.LevelRarity = levelRarity; this.MinDamage = minDamage; this.MaxDamage = maxDamage; this.NumSockets = numSockets; this.sockets = new IGem[numSockets]; } public string Name { get; private set; } public int MinDamage { get { return this.minDamage; } private set { this.minDamage = value * (int)this.LevelRarity; } } public int MaxDamage { get { return this.maxDamage; } private set { this.maxDamage = value * (int)this.LevelRarity; } } public int NumSockets { get; private set; } public LevelRarity LevelRarity { get; private set; } public IReadOnlyCollection<IGem> Sockets => this.sockets; public void AddGem(IGem gem, int index) { if (index < 0 || index >= this.sockets.Length) { return; } this.sockets[index] = gem; IncreaseDemageValuesByGem(gem); } public void RemoveGem(int index) { if (index < 0 || index >= this.sockets.Length) { return; } IGem gemToRemove = this.sockets[index]; this.sockets[index] = null; DecreaseDemageValuesByGem(gemToRemove); } private void IncreaseDemageValuesByGem(IGem gem) { this.minDamage += gem.Strength * 2 + gem.Agility; this.maxDamage += gem.Strength * 3 + gem.Agility * 4; } private void DecreaseDemageValuesByGem(IGem gemToRemove) { this.minDamage -= gemToRemove.Strength * 2; this.maxDamage -= gemToRemove.Strength * 3; this.minDamage -= gemToRemove.Agility; this.maxDamage -= gemToRemove.Agility * 4; } public override string ToString() { int strenght = this.Sockets .Where(x => x != null) .Sum(x => x.Strength); int agility = this.Sockets .Where(x => x != null) .Sum(x => x.Agility); int vitality = this.Sockets .Where(x => x != null) .Sum(x => x.Vitality); StringBuilder builder = new StringBuilder(); builder .Append($"{this.Name}: ") .Append($"{this.MinDamage}-{this.MaxDamage} Damage,") .Append($" +{strenght} Strength,") .Append($" +{agility} Agility,") .Append($" +{vitality} Vitality"); return builder.ToString(); } } }
using System; using System.Collections.Generic; using System.Text; namespace NextGenSoftware.Holochain.HoloNET.Client.Core { public abstract class ZomeParam { public string ParamName { get; set; } //public object ParamValue { get; set; } public bool IsStruct { get; set; } } }
namespace CqrsMediatREFDapper.Domain.CourseContext.Commands { public sealed class RegisterCourseCommand : CourseCommand { public static RegisterCourseCommand Create(string name, string description, decimal price, byte[] video) => new RegisterCourseCommand { Name = name, Description = description, Price = price, Video = video }; } }
using System; using Xamarin.Forms; namespace ResponsiveLayout { public class GridPageCode : ContentPage { private double width = 0; private double height = 0; Grid innerGrid; Grid controlsGrid; public GridPageCode () { Title = "Grid - C#"; var outerGrid = new Grid (); innerGrid = new Grid { Padding = new Thickness(10)}; controlsGrid = new Grid (); outerGrid.RowDefinitions.Add (new RowDefinition{ Height = new GridLength (1, GridUnitType.Star) }); outerGrid.RowDefinitions.Add (new RowDefinition{ Height = new GridLength (60) }); innerGrid.RowDefinitions.Add (new RowDefinition{ Height = new GridLength (1, GridUnitType.Star) }); innerGrid.ColumnDefinitions.Add (new ColumnDefinition { Width = new GridLength (1, GridUnitType.Star) }); innerGrid.ColumnDefinitions.Add (new ColumnDefinition { Width = new GridLength (1, GridUnitType.Star) }); innerGrid.Children.Add (new Image { Source = "deer.jpg", HeightRequest = 300, WidthRequest = 300 }, 0, 0); outerGrid.Children.Add (innerGrid, 0, 0); controlsGrid.RowDefinitions.Add (new RowDefinition{ Height = new GridLength (1, GridUnitType.Auto) }); controlsGrid.RowDefinitions.Add (new RowDefinition{ Height = new GridLength (1, GridUnitType.Auto) }); controlsGrid.RowDefinitions.Add (new RowDefinition{ Height = new GridLength (1, GridUnitType.Auto) }); controlsGrid.ColumnDefinitions.Add (new ColumnDefinition { Width = new GridLength (1, GridUnitType.Auto) }); controlsGrid.ColumnDefinitions.Add (new ColumnDefinition { Width = new GridLength (1, GridUnitType.Star) }); controlsGrid.Children.Add (new Label { Text = "Name:" }, 0, 0); controlsGrid.Children.Add (new Label { Text = "Date:" }, 0, 1); controlsGrid.Children.Add (new Label { Text = "Tags:" }, 0, 2); controlsGrid.Children.Add (new Entry (), 1, 0); controlsGrid.Children.Add (new Entry (), 1, 1); controlsGrid.Children.Add (new Entry (), 1, 2); var buttonsGrid = new Grid (); outerGrid.Children.Add (buttonsGrid, 0, 1); buttonsGrid.ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); buttonsGrid.ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); buttonsGrid.ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); buttonsGrid.Children.Add (new Button { Text = "Previous" }, 0, 0); buttonsGrid.Children.Add (new Button { Text = "Save" }, 1, 0); buttonsGrid.Children.Add (new Button { Text = "Next" }, 2, 0); Content = outerGrid; } protected override void OnSizeAllocated (double width, double height){ base.OnSizeAllocated (width, height); if (width != this.width || height != this.height) { this.width = width; this.height = height; if (width > height) { innerGrid.RowDefinitions.Clear(); innerGrid.ColumnDefinitions.Clear (); innerGrid.RowDefinitions.Add (new RowDefinition{ Height = new GridLength (1, GridUnitType.Star) }); innerGrid.ColumnDefinitions.Add (new ColumnDefinition { Width = new GridLength (1, GridUnitType.Star) }); innerGrid.ColumnDefinitions.Add (new ColumnDefinition { Width = new GridLength (1, GridUnitType.Star) }); innerGrid.Children.Remove (controlsGrid); innerGrid.Children.Add (controlsGrid, 1, 0); } else { innerGrid.ColumnDefinitions.Clear (); innerGrid.ColumnDefinitions.Add (new ColumnDefinition{ Width = new GridLength (1, GridUnitType.Star) }); innerGrid.RowDefinitions.Add (new RowDefinition { Height = new GridLength (1, GridUnitType.Auto) }); innerGrid.RowDefinitions.Add (new RowDefinition { Height = new GridLength (1, GridUnitType.Star) }); innerGrid.Children.Remove (controlsGrid); innerGrid.Children.Add (controlsGrid, 0, 1); } } } } }
/* * Copyright (c) 2021 Snowflake Computing Inc. All rights reserved. */ using Azure.Storage.Blobs; using Snowflake.Data.Log; using System; using System.Collections.Generic; using System.IO; using Azure; using Azure.Storage.Blobs.Models; using Newtonsoft.Json; namespace Snowflake.Data.Core.FileTransfer.StorageClient { /// <summary> /// The azure client used to transfer files to the remote Azure storage. /// </summary> class SFSnowflakeAzureClient : ISFRemoteStorageClient { private const string EXPIRED_TOKEN = "ExpiredToken"; private const string NO_SUCH_KEY = "NoSuchKey"; /// <summary> /// The attribute in the credential map containing the shared access signature token. /// </summary> private static readonly string AZURE_SAS_TOKEN = "AZURE_SAS_TOKEN"; /// <summary> /// The logger. /// </summary> private static readonly SFLogger Logger = SFLoggerFactory.GetLogger<SFSnowflakeAzureClient>(); /// <summary> /// The cloud blob client to use to upload and download data on Azure. /// </summary> private BlobServiceClient blobServiceClient; /// <summary> /// Azure client without client-side encryption. /// </summary> /// <param name="stageInfo">The command stage info.</param> public SFSnowflakeAzureClient(PutGetStageInfo stageInfo) { Logger.Debug("Setting up a new Azure client "); // Get the Azure SAS token and create the client if (stageInfo.stageCredentials.TryGetValue(AZURE_SAS_TOKEN, out string sasToken)) { string blobEndpoint = string.Format("https://{0}.blob.core.windows.net", stageInfo.storageAccount); blobServiceClient = new BlobServiceClient(new Uri(blobEndpoint), new AzureSasCredential(sasToken)); } } /// <summary> /// Extract the bucket name and path from the stage location. /// </summary> /// <param name="stageLocation">The command stage location.</param> /// <returns>The remote location of the Azure file.</returns> public RemoteLocation ExtractBucketNameAndPath(string stageLocation) { string blobName = stageLocation; string azurePath = null; // Split stage location as bucket name and path if (stageLocation.Contains("/")) { blobName = stageLocation.Substring(0, stageLocation.IndexOf('/')); azurePath = stageLocation.Substring(stageLocation.IndexOf('/') + 1, stageLocation.Length - stageLocation.IndexOf('/') - 1); if (azurePath != "" && !azurePath.EndsWith("/")) { azurePath += "/"; } } return new RemoteLocation() { bucket = blobName, key = azurePath }; } /// <summary> /// Get the file header. /// </summary> /// <param name="fileMetadata">The Azure file metadata.</param> /// <returns>The file header of the Azure file.</returns> public FileHeader GetFileHeader(SFFileMetadata fileMetadata) { PutGetStageInfo stageInfo = fileMetadata.stageInfo; RemoteLocation location = ExtractBucketNameAndPath(stageInfo.location); // Get the Azure client BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(location.bucket); BlobClient blobClient = containerClient.GetBlobClient(location.key + fileMetadata.destFileName); BlobProperties response; try { // Issue the GET request response = blobClient.GetProperties(); } catch (Exception ex) { if (ex.Message.Contains(EXPIRED_TOKEN) || ex.Message.Contains("Status: 400")) { fileMetadata.resultStatus = ResultStatus.RENEW_TOKEN.ToString(); } else if (ex.Message.Contains(NO_SUCH_KEY) || ex.Message.Contains("Status: 404")) { fileMetadata.resultStatus = ResultStatus.NOT_FOUND_FILE.ToString(); } else { fileMetadata.resultStatus = ResultStatus.ERROR.ToString(); } return null; } fileMetadata.resultStatus = ResultStatus.UPLOADED.ToString(); dynamic encryptionData = JsonConvert.DeserializeObject(response.Metadata["encryptiondata"]); SFEncryptionMetadata encryptionMetadata = new SFEncryptionMetadata { iv = encryptionData.WrappedContentKey["EncryptedKey"], key = encryptionData["ContentEncryptionIV"], matDesc = response.Metadata["matdesc"] }; return new FileHeader { digest = response.Metadata["sfcdigest"], contentLength = response.ContentLength, encryptionMetadata = encryptionMetadata }; } /// <summary> /// Upload the file to the Azure location. /// </summary> /// <param name="fileMetadata">The Azure file metadata.</param> /// <param name="fileBytes">The file bytes to upload.</param> /// <param name="encryptionMetadata">The encryption metadata for the header.</param> public void UploadFile(SFFileMetadata fileMetadata, byte[] fileBytes, SFEncryptionMetadata encryptionMetadata) { // Create the JSON for the encryption data header string encryptionData = JsonConvert.SerializeObject(new EncryptionData { EncryptionMode = "FullBlob", WrappedContentKey = new WrappedContentInfo { KeyId = "symmKey1", EncryptedKey = encryptionMetadata.key, Algorithm = "AES_CBC_256" }, EncryptionAgent = new EncryptionAgentInfo { Protocol = "1.0", EncryptionAlgorithm = "AES_CBC_256" }, ContentEncryptionIV = encryptionMetadata.iv, KeyWrappingMetadata = new KeyWrappingMetadataInfo { EncryptionLibrary = "Java 5.3.0" } }); // Create the metadata to use for the header IDictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add("encryptiondata", encryptionData); metadata.Add("matdesc", encryptionMetadata.matDesc); metadata.Add("sfcdigest", fileMetadata.SHA256_DIGEST); PutGetStageInfo stageInfo = fileMetadata.stageInfo; RemoteLocation location = ExtractBucketNameAndPath(stageInfo.location); // Get the Azure client BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(location.bucket); BlobClient blobClient = containerClient.GetBlobClient(location.key + fileMetadata.destFileName); try { // Issue the POST/PUT request blobClient.Upload(new MemoryStream(fileBytes)); blobClient.SetMetadata(metadata); } catch (Exception ex) { if (ex.Message.Contains("Status: 400")) { fileMetadata.resultStatus = ResultStatus.RENEW_PRESIGNED_URL.ToString(); } else if (ex.Message.Contains("Status: 401")) { fileMetadata.resultStatus = ResultStatus.RENEW_TOKEN.ToString(); } else if (ex.Message.Contains("Status: 403") || ex.Message.Contains("Status: 500") || ex.Message.Contains("Status: 503")) { fileMetadata.resultStatus = ResultStatus.NEED_RETRY.ToString(); } return; } fileMetadata.destFileSize = fileMetadata.uploadSize; fileMetadata.resultStatus = ResultStatus.UPLOADED.ToString(); } } }
/************************************************************************* * Author: DCoreyDuke ************************************************************************/ using _43LimeMobileApp.Models.Entities; namespace _43LimeMobileApp.Admin.API.Services { /// <summary> /// LatLng Data Service - gets Latitude and Longitude information for the application /// Queries Google Maps Services for certain data ops /// </summary> internal sealed class LatLngService : IDataService { #region Properties /// <summary> /// Gets or sets the lat LNG. /// </summary> /// <value> /// The lat LNG. /// </value> public LatLng LatLng { get; set; } /// <summary> /// Gets or sets the latitude. /// </summary> /// <value> /// The latitude. /// </value> public string Latitude { get; set; } /// <summary> /// Gets or sets the longitude. /// </summary> /// <value> /// The longitude. /// </value> public string Longitude { get; set; } #endregion private LatLngService() { } /// <summary> /// Initializes a new instance of the <see cref="LatLngService"/> class. /// </summary> /// <param name="latitude">The latitude.</param> /// <param name="longitude">The longitude.</param> public LatLngService(string latitude, string longitude) : this() { this.Latitude = latitude; this.Longitude = longitude; this.LatLng = new LatLng(latitude, longitude); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AudioSyncMSNUI { class DialogForm { public static string ShowDialog(string text, string caption, string example) { Form form = new() { Width = 500, Height = 250, FormBorderStyle = FormBorderStyle.FixedDialog, Text = caption, StartPosition = FormStartPosition.CenterScreen }; Label txtLabel = new() { Left = 50, Top = 10, Text = text, MaximumSize = new System.Drawing.Size(400, 0), AutoSize = true }; TextBox txtBox = new() { Left = 50, Top = 90, Width = 400, SelectedText = example }; Button confirmBtn = new() { Text = "Ok", Left = 350, Width = 100, Top = 170, Height = 30, DialogResult = DialogResult.OK }; confirmBtn.Click += (sender, e) => { form.Close(); }; form.Controls.Add(txtLabel); form.Controls.Add(txtBox); form.Controls.Add(confirmBtn); form.AcceptButton = confirmBtn; return form.ShowDialog() == DialogResult.OK ? txtBox.Text : ""; } } }
using System.Threading.Tasks; using TMDB.Core.Api.V3.Models.Find; namespace TMDB.NET.Api.V3.ClientProxies { public class FindProxy : ApiProxy { public FindProxy(TMDbClient client) : base(client) { } public virtual Task<FindByIdResponse> GetAsync(FindByIdRequest request) => Client.SendAsync<FindByIdResponse>(request); } }
using Guard; using Picturebot.src.Helper; using Picturebot.src.Logger; using Picturebot.src.POCO; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Picturebot { public class Shoot { private Config _config { get; set; } private static readonly log4net.ILog _log = LogHelper.GetLogger(); /// <summary> /// Shoot constructor /// The workspace class handles everything related to the shoot operations /// </summary> public Shoot(Config config) { _config = config; } /// <summary> /// Add a new shoot within the workspace directory /// Example: "<location> <dd-MM-YYYY>" -> "London 20-02-2020" /// </summary> /// <param name="name">shoot name</param> /// <returns>True when a shoot doesn't exists yet</returns> public bool Add(string name) { string shootRoot = Path.Combine(_config.Workspace, name); // Create a new shoot when it doesn't exists yet if (!Guard.Filesystem.IsPath(shootRoot)) { try { // Create a new shoot Directory.CreateDirectory(shootRoot); _log.Info($"Shoot: created \"{shootRoot}\" shoot"); // Create all the flows within the shoot InitialiseShoot(shootRoot); return true; } catch (DirectoryNotFoundException e) { _log.Info($"Shoot: unable to create a new shoot \"{shootRoot}\"", e); return false; } } _log.Info($"Shoot: already \"{shootRoot}\" exists"); MessageBox.Show($"Shoot: already \"{shootRoot}\" exists"); return false; } /// <summary> /// Remove a specified shoot within the workspace directory /// </summary> /// <param name="path">Path the shoot</param> public void Remove(string path) { if(Guard.Filesystem.IsPath(path)) { Directory.Delete(path, true); _log.Info($"Shoot: deleted \"{path}\""); } else { _log.Info($"Shoot: unable to delete \"{path}\""); MessageBox.Show($"Shoot: unable to delete \"{path}\""); } } /// <summary> /// Rename a shoot name and recursively rename all pictures within every flow accordingly to the new shoot name /// </summary> /// <param name="name">New shoot name</param> public void Rename(string oldShootInfo, string shootName, string shootDate, bool isHash, int amountOfFiles) { string newShoot = $"{shootName} {shootDate}"; Flow flow = new Flow(_config); // Only rename files recursively when other flows contain pictures as well if (amountOfFiles != 0) { flow.Rename(oldShootInfo, false, isHash, newShoot); } string source = Path.Combine(_config.Workspace, oldShootInfo); string destination = Path.Combine(_config.Workspace, newShoot); try { Directory.Move(source, destination); _log.Info($"InitialiseShoot: moved \"{source}\" to \"{destination}\""); } catch (DirectoryNotFoundException e) { _log.Error($"InitialiseShoot: unable to move \"{source}\" to \"{destination}\"", e); MessageBox.Show(e.Message); } catch (IOException e) { _log.Error($"Shoot rename: access to \"{source}\" or \"{destination}\" is denied", e); MessageBox.Show(e.Message); } } /// <summary> /// Create all flows configured in the configuration file /// </summary> /// <param name="root">Root directory of the newly created shoot</param> private void InitialiseShoot(string root) { // Loop-over every flow defined in the workspace array object within the config file foreach (var flow in _config.Workflows) { // Create an absolute root path to the flow that is about to get created within the shoot string flowRoot = Path.Combine(root, flow); try { Directory.CreateDirectory(flowRoot); _log.Info($"Shoot: created \"{flowRoot}\" flow"); } catch (DirectoryNotFoundException e) { _log.Error($"Shoot: unable to \"{flowRoot}\" flow", e); MessageBox.Show(e.Message); } } } } }
using Microsoft.EntityFrameworkCore; namespace RestApiCRUD.Models { public class EmployeeContext : DbContext { public EmployeeContext(DbContextOptions<EmployeeContext> options) : base(options) { } public DbSet<Employee> Employees { get; set; } } }
using System; namespace SF_FoodTrucks.Models { public class FoodTrucks { public class Rootobject { public string Type { get; set; } public Feature[] Features { get; set; } public Crs Crs { get; set; } } public class Crs { public string Type { get; set; } public Properties Properties { get; set; } } public class Properties { public string Name { get; set; } } public class Feature { public string Type { get; set; } public Geometry Geometry { get; set; } public Properties1 Properties { get; set; } } public class Geometry { public string Type { get; set; } public float[] Coordinates { get; set; } } public class Properties1 { public string X { get; set; } public object Location_2_state { get; set; } public string Applicant { get; set; } public string Location { get; set; } public string Latitude { get; set; } public string Y { get; set; } public string Computed_region_yftq_j783 { get; set; } public object Location_2_zip { get; set; } public string Locationid { get; set; } public string Dayofweekstr { get; set; } public string Coldtruck { get; set; } public DateTime Addr_date_create { get; set; } public string Start24 { get; set; } public string Cnn { get; set; } public string Longitude { get; set; } public string Optionaltext { get; set; } public string Computed_region_rxqg_mtj9 { get; set; } public string Dayorder { get; set; } public string Computed_region_ajp5_b2md { get; set; } public string Block { get; set; } public object Location_2_city { get; set; } public string Endtime { get; set; } public object Scheduleid { get; set; } public string Permit { get; set; } public DateTime? Addr_date_modified { get; set; } public string Locationdesc { get; set; } public string Computed_region_bh8s_q3mv { get; set; } public string Starttime { get; set; } public string Lot { get; set; } public string Computed_region_jx4q_fizf { get; set; } public object Location_2_address { get; set; } public string End24 { get; set; } } } }
using Recore; using FileSync.Common.ApiModels; namespace FileSync.Client { sealed class Conflict { public FileSyncFile ClientFile { get; } public FileSyncFile ServiceFile { get; } public ChosenVersion ChosenVersion { get; } public Conflict(FileSyncFile clientFile, FileSyncFile serviceFile) { ClientFile = clientFile; ServiceFile = serviceFile; ChosenVersion = Func.Invoke(() => { bool serviceVersionIsNewer = serviceFile.LastWriteTimeUtc > clientFile.LastWriteTimeUtc; if (serviceVersionIsNewer) { return ChosenVersion.Service; } else { return ChosenVersion.Client; } }); } } enum ChosenVersion { Client, Service } }
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\strmif.h(22353,1) namespace DirectN { public enum tagDVD_SUBPICTURE_CODING { DVD_SPCoding_RunLength = 0, DVD_SPCoding_Extended = 1, DVD_SPCoding_Other = 2, } }
using System; using System.Collections.Generic; using System.Text; namespace SyZero.Feign { public interface IFeignProxyBuilder { Object Build(Type interfaceType, params object[] constructor); T Build<T>(params object[] constructor); } }
using System; namespace TheNeoGeoArchive.Persistence.Domain { public sealed class Release { public DateTime? Mvs { set; get; } public DateTime? Aes { set; get; } public DateTime? Cd { set; get; } } }
namespace CondinGame.Contests.SpringChallenge2021 { internal interface IActionStrategy { Action SelectAction(Game game); } }
using Autodesk.Revit.DB; using Autodesk.Revit.UI; namespace RevitLookupWpf.InstanceTree { public class WorksetIdInstanceNode : InstanceNode<WorksetId> { private WorksetId elementId; public WorksetIdInstanceNode(WorksetId rvtObject) : base(rvtObject) { elementId = rvtObject; if (rvtObject != null) { Name += $"({rvtObject.IntegerValue})"; } } public InstanceNode ToWorksetInstanceNode() { InstanceNode node; Document doc = SnoopingContext.Instance.CommandData.Application.ActiveUIDocument.Document; WorksetTable worksetTable = doc.GetWorksetTable(); Workset workset = worksetTable.GetWorkset(elementId); node = new WorksetInstanceNode(workset); return node; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using MongoDB.Driver; using Xunit; using YS.Knife.Hosting; namespace YS.Knife.Mongo.UnitTest { public class MongoContextAttributeTest : KnifeHost { [InjectConfiguration("connectionStrings:book_db")] private readonly string book_conn = TestEnvironment.MongoConnectionString; [InjectConfiguration("connectionStrings:user_db")] private readonly string user_conn = TestEnvironment.MongoConnectionString; [Theory] [InlineData(typeof(UserContext))] [InlineData(typeof(BookContext))] public void ShouldGetContextType(Type contextType) { var context = ((IServiceProvider)this).GetService(contextType); IEnumerable baseContexts = this.GetService<IEnumerable<MongoContext>>(); context.Should().NotBeNull(); baseContexts.Should().NotBeNull(); baseContexts.Should().Contain(context); } [Fact] public void ShouldGetUserStoreWhenRegisteEntityStore() { var userStore = this.GetService<IEntityStore<User>>(); userStore.Should().NotBeNull(); } [Fact] public void ShouldGetBookStoreWhenRegisteEntityStore() { var userStore = this.GetService<IEntityStore<User>>(); userStore.Should().NotBeNull(); } [Fact] public void ShouldNotGetNewBookStoreWhenNotRegisteEntityStore() { var bookStore = this.GetService<IEntityStore<NewBook>>(); bookStore.Should().BeNull(); } #region UserContext public class User { public string Id { get; set; } public int Age { get; set; } } [MongoContext("user_db")] public class UserContext : MongoContext { public UserContext(IMongoDatabase database) : base(database) { } public IMongoCollection<User> Users { get; set; } } #endregion #region BookContext public class Book { public string Id { get; set; } public int Name { get; set; } } public class NewBook { public string Id { get; set; } public int Name { get; set; } } [MongoContext("book_db", RegisterEntityStore = false)] public class BookContext : MongoContext { public BookContext(IMongoDatabase database) : base(database) { } public IMongoCollection<Book> Books { get; set; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; namespace PathonDB.DatabaseClient.Models.Column { public class Column : IColumn { public Properties Properties { get; private set; } private List<Row> _rows { get; } public Column(Properties properties) { this.Properties = properties; this._rows = new List<Row>(); } public void InsertRow(Row row) { this._rows.Add(row); } public Row GetRowById(string id) { return this._rows.First(x => x.Id == id); } public Row[] GetRows(string[] idList = null) { Func<Row, bool> validateRow = (Row x) => idList == null ? true : idList.Contains(x.Id); return this._rows.Where(validateRow).ToArray(); } public string[] GetFilteredIdList(object value) { return this._rows.Where(x => x.Value.Equals(value)).Select(x => x.Id).ToArray(); } } }
using System; using System.Collections; using DCL.Configuration; using DCL.Controllers; using DCL.Helpers; using DCL.Models; using UnityEngine; namespace DCL.Components { internal class AvatarAttachHandler : IDisposable { private const float BOUNDARIES_CHECK_INTERVAL = 5; public AvatarAttachComponent.Model model { internal set; get; } = new AvatarAttachComponent.Model(); public IParcelScene scene { private set; get; } public IDCLEntity entity { private set; get; } private AvatarAttachComponent.Model prevModel = null; private IAvatarAnchorPoints anchorPoints; private AvatarAnchorPointIds anchorPointId; private Coroutine componentUpdate = null; private readonly GetAnchorPointsHandler getAnchorPointsHandler = new GetAnchorPointsHandler(); private ISceneBoundsChecker sceneBoundsChecker => Environment.i?.world?.sceneBoundsChecker; private Vector2Int? currentCoords = null; private bool isInsideScene = true; private float lastBoundariesCheckTime = 0; public void Initialize(IParcelScene scene, IDCLEntity entity) { this.scene = scene; this.entity = entity; getAnchorPointsHandler.OnAvatarRemoved += Detach; } public void OnModelUpdated(string json) { OnModelUpdated(model.GetDataFromJSON(json) as AvatarAttachComponent.Model); } public void OnModelUpdated(AvatarAttachComponent.Model newModel) { prevModel = model; model = newModel; if (model == null) { return; } if (prevModel.avatarId != model.avatarId) { Detach(); if (!string.IsNullOrEmpty(model.avatarId)) { Attach(model.avatarId, (AvatarAnchorPointIds)model.anchorPointId); } } } public void Dispose() { Detach(); getAnchorPointsHandler.OnAvatarRemoved -= Detach; getAnchorPointsHandler.Dispose(); } internal virtual void Detach() { if (componentUpdate != null) { CoroutineStarter.Stop(componentUpdate); componentUpdate = null; } if (entity != null) { entity.gameObject.transform.localPosition = EnvironmentSettings.MORDOR; } getAnchorPointsHandler.CancelCurrentSearch(); } internal virtual void Attach(string avatarId, AvatarAnchorPointIds anchorPointId) { getAnchorPointsHandler.SearchAnchorPoints(avatarId, anchorPoints => { Attach(anchorPoints, anchorPointId); }); } internal virtual void Attach(IAvatarAnchorPoints anchorPoints, AvatarAnchorPointIds anchorPointId) { this.anchorPoints = anchorPoints; this.anchorPointId = anchorPointId; if (componentUpdate == null) { componentUpdate = CoroutineStarter.Start(ComponentUpdate()); } } IEnumerator ComponentUpdate() { currentCoords = null; while (true) { if (entity == null || scene == null) { componentUpdate = null; yield break; } var anchorPoint = anchorPoints.GetTransform(anchorPointId); if (IsInsideScene(CommonScriptableObjects.worldOffset + anchorPoint.position)) { entity.gameObject.transform.position = anchorPoint.position; entity.gameObject.transform.rotation = anchorPoint.rotation; if (Time.unscaledTime - lastBoundariesCheckTime > BOUNDARIES_CHECK_INTERVAL) { CheckSceneBoundaries(entity); } } else { entity.gameObject.transform.localPosition = EnvironmentSettings.MORDOR; } yield return null; } } internal virtual bool IsInsideScene(Vector3 position) { bool result = isInsideScene; Vector2Int coords = Utils.WorldToGridPosition(position); if (currentCoords == null || currentCoords != coords) { result = scene.IsInsideSceneBoundaries(coords, position.y); } currentCoords = coords; isInsideScene = result; return result; } private void CheckSceneBoundaries(IDCLEntity entity) { sceneBoundsChecker?.AddEntityToBeChecked(entity); lastBoundariesCheckTime = Time.unscaledTime; } } }
using Nancy; namespace Napack.Server { /// <summary> /// Manages the Napack Framwork Server visible interface. /// </summary> public class IndexModule : NancyModule { public IndexModule() { Get["/"] = parameters => { return View["Index", new IndexModel(Global.SystemConfig.AdministratorEmail)]; }; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class DelayedLoadScene : MonoBehaviour { public string levelToLoad; public Color loadToColor = Color.black; public float timeToStart = 3.0f; // Use this for initialization void Start () { Invoke ("LoadScene1", timeToStart); } void LoadScene1 (){ Initiate.Fade (levelToLoad, loadToColor, 5.0f); } }
namespace PromotionSales.Api.Application.PromotionApplication.Commands.UpdatePromotion; using MediatR; using PromotionSales.Api.Application.Common.EntitiesDto; public class UpdatePromotionCommand : IRequest<PromotionDto> { public Guid Id { get; set; } public IList<string> MediosDePago { get; set; } public IList<string> Bancos { get; set; } public IList<string> CategoriasProductos { get; set; } public int? MaximaCantidadDeCuotas { get; set; } public decimal? ValorInteresCuotas { get; set; } public decimal? PorcentajeDeDescuento { get; set; } public DateTime? FechaInicio { get; set; } public DateTime? FechaFin { get; set; } public bool Active { get; set; } public DateTime FechaCreacion { get; set; } public DateTime? FechaModificacion { get; set; } }
using System; using System.Collections.Generic; namespace XMonitor.Core { /// <summary> /// 定义监控服务选项接口 /// </summary> public interface IMonitorOptions { /// <summary> /// 获取或设置日志工具 /// </summary> ILogger Logger { get; set; } /// <summary> /// 获取通知通道列表 /// </summary> List<INotifyChannel> NotifyChannels { get; } /// <summary> /// 获取或设置检测的时间间隔 /// </summary> TimeSpan Interval { get; set; } } }
using System; namespace Selenium.AutomatedTests { /// <summary> /// Represents failure in the execution of an automation scenario /// </summary> [Serializable] public class AutomationScenarioRunFailedException : Exception { internal AutomationScenarioRunFailedException(string automationTestReportSummary) : base(automationTestReportSummary) { } } }
#if ADV_INS_CHANGES && UNITY_EDITOR using System; using System.Linq; using com.tinylabproductions.TLPLib.Data; using com.tinylabproductions.TLPLib.Extensions; using com.tinylabproductions.TLPLib.Functional; using com.tinylabproductions.TLPLib.Logger; using com.tinylabproductions.TLPLib.Tween.fun_tween.serialization.manager; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; namespace com.tinylabproductions.TLPLib.Editor.VisualTweenTimeline { public class TweenPlaybackController { public enum AnimationPlaybackEvent : byte { GoToStart, PlayFromStart, PlayFromCurrentTime, Pause, PlayFromEnd, GoToEnd, Reverse, Exit } public TweenPlaybackController(FunTweenManager ftm, Ref<bool> visualizationMode) { manager = ftm; this.visualizationMode = visualizationMode; beforeCursorDataIsSaved = false; } readonly FunTweenManager manager; double lastSeconds; bool isAnimationPlaying, applicationPlaying, playingBackwards, beforeCursorDataIsSaved; readonly Ref<bool> visualizationMode; Option<EditorApplication.CallbackFunction> updateDelegateOpt; Option<Object[]> savedTargetDataOpt; static double currentRealSeconds() { var epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return (DateTime.UtcNow - epochStart).TotalSeconds; } void updateAnimation() { var currentSeconds = currentRealSeconds(); if (lastSeconds < 1) lastSeconds = currentSeconds; var timeDiff = (float)(currentSeconds - lastSeconds); lastSeconds = currentSeconds; foreach (var savedTargetData in savedTargetDataOpt) { foreach (var entry in savedTargetData) { EditorUtility.SetDirty(entry); } } manager.timeline.timeline.timePassed += timeDiff * (playingBackwards ? -1 : 1); } void startUpdatingTime() { if (!EditorApplication.isCompiling) { startVisualization(); lastSeconds = currentRealSeconds(); updateDelegateOpt.voidFold( () => { EditorApplication.CallbackFunction updateDelegate = updateAnimation; EditorApplication.update += updateDelegate; updateDelegateOpt = updateDelegate.some(); }, updateDelegate => EditorApplication.update += updateDelegate ); } } void stopTimeUpdate() => updateDelegateOpt.map(updateDelegate => EditorApplication.update -= updateDelegate); void startVisualization() { if (!visualizationMode.value && getTimelineTargets(manager).valueOut(out var data)) { manager.recreate(); Undo.RegisterCompleteObjectUndo(data, "Animating targets"); savedTargetDataOpt = data.some(); visualizationMode.value = true; } } public void stopVisualization() { if (visualizationMode.value) { stopTimeUpdate(); Undo.PerformUndo(); savedTargetDataOpt = F.none_; visualizationMode.value = false; } } static Option<Object[]> getTimelineTargets(FunTweenManager ftm) => ftm.timeline.elements.opt().map( elements => elements .map(elem => elem.element.getTargets()) .Aggregate((acc, curr) => acc.concat(curr)) ); public void evaluateCursor(float time) { if (getTimelineTargets(manager).valueOut(out var data) && data.All(target => target != null)) { if (!Application.isPlaying) { if (visualizationMode.value) { stopTimeUpdate(); } else if (!beforeCursorDataIsSaved) { manager.recreate(); beforeCursorDataIsSaved = true; Undo.RegisterCompleteObjectUndo(data, "targets saved"); savedTargetDataOpt = data.some(); } } else { manager.run(FunTweenManager.Action.Stop); } foreach (var entry in data) { EditorUtility.SetDirty(entry); } manager.timeline.timeline.timePassed = time; } else { Log.d.warn($"Set targets before evaluating!"); } } public void stopCursorEvaluation() { if (!visualizationMode.value && beforeCursorDataIsSaved && !Application.isPlaying) { Undo.RevertAllInCurrentGroup(); savedTargetDataOpt = F.none_; beforeCursorDataIsSaved = false; } } public void manageAnimation(AnimationPlaybackEvent playbackEvent) { applicationPlaying = Application.isPlaying; switch (playbackEvent) { case AnimationPlaybackEvent.GoToStart: manager.timeline.timeline.timePassed = 0; if (!applicationPlaying) { stopTimeUpdate(); startVisualization(); } else { manager.run(FunTweenManager.Action.Stop); } isAnimationPlaying = false; break; case AnimationPlaybackEvent.PlayFromStart: if (!applicationPlaying) { if (!isAnimationPlaying) { startUpdatingTime(); } manager.timeline.timeline.timePassed = 0; if (!visualizationMode.value) { startVisualization(); } playingBackwards = false; } else { manager.run(FunTweenManager.Action.PlayForwards); } isAnimationPlaying = true; break; case AnimationPlaybackEvent.PlayFromCurrentTime: if (isAnimationPlaying) { if (!applicationPlaying) { stopTimeUpdate(); playingBackwards = false; } else { manager.run(FunTweenManager.Action.Stop); } isAnimationPlaying = false; } else { if (!applicationPlaying) { if (!visualizationMode.value) { startVisualization(); } startUpdatingTime(); playingBackwards = false; } else { manager.run(FunTweenManager.Action.Resume); } isAnimationPlaying = true; } break; case AnimationPlaybackEvent.Pause: if (!applicationPlaying){ stopTimeUpdate(); } else { manager.run(FunTweenManager.Action.Stop); } isAnimationPlaying = false; break; case AnimationPlaybackEvent.PlayFromEnd: if (!applicationPlaying) { if (!visualizationMode.value) { startVisualization(); } manager.timeline.timeline.timePassed = manager.timeline.timeline.duration; if (!isAnimationPlaying) { startUpdatingTime(); } playingBackwards = true; } else { manager.run(FunTweenManager.Action.PlayBackwards); } isAnimationPlaying = true; break; case AnimationPlaybackEvent.GoToEnd: if (!applicationPlaying) { if (!visualizationMode.value) { startVisualization(); } manager.timeline.timeline.timePassed = manager.timeline.timeline.duration; stopTimeUpdate(); } else { manager.timeline.timeline.timePassed = manager.timeline.timeline.duration; manager.run(FunTweenManager.Action.Stop); } isAnimationPlaying = false; break; case AnimationPlaybackEvent.Reverse: if (!applicationPlaying) { playingBackwards = !playingBackwards; } else { manager.run(FunTweenManager.Action.Reverse); } break; case AnimationPlaybackEvent.Exit: stopVisualization(); isAnimationPlaying = false; break; } } } } #endif
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChargePowerUp : MonoBehaviour, IPowerUp { public int effect; public int PowerUp() { return effect; } }
using AspNetScaffolding; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using WebApi.Models.Exceptions; namespace AspNetScaffolding.Extensions.GracefullShutdown { public static class GracefullShutdownExtensions { public static void ValidationShutdown(this ControllerBase controller) { if (Api.ShutdownSettings?.Enabled == false) { if (Api.ShutdownSettings.GracefullShutdownState.StopRequested && Api.ShutdownSettings.Redirect) { throw new PermanentRedirectException(null); } else if (Api.ShutdownSettings.GracefullShutdownState.StopRequested) { throw new ServiceUnavailableException("Service is unavailable for temporary maintenance"); } } } public static IApplicationBuilder UseGracefullShutdown(this IApplicationBuilder builder) { if (Api.ShutdownSettings?.Enabled != true) { return builder; } return builder.UseMiddleware<GracefullShutdownMiddleware>(); } public static IServiceCollection AddGracefullShutdown(this IServiceCollection services) { services.AddSingleton(Api.ShutdownSettings.GracefullShutdownState); services.AddSingleton<IRequestsCountProvider>(Api.ShutdownSettings.GracefullShutdownState); return services; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; public class WinningTicket { public static void Main() // 100/100 { StringBuilder result = new StringBuilder(); List<string> tickets = Console.ReadLine().Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToList(); string pattern = @"(\@{6,}|\${6,}|\^{6,}|\#{6,})"; Regex reg = new Regex(pattern); foreach (string ticket in tickets) { if (ticket.Length != 20) { result.Append($"invalid ticket{Environment.NewLine}"); } else { Match leftMatch = reg.Match(ticket.Substring(0, 10)); Match rightMatch = reg.Match(ticket.Substring(10)); int minLen = Math.Min(leftMatch.Length, rightMatch.Length); if (!leftMatch.Success || !rightMatch.Success) { result.Append($"ticket \"{ ticket}\" - no match{Environment.NewLine}"); } else { string leftPart = leftMatch.Value.Substring(0, minLen); string rightPart = rightMatch.Value.Substring(0, minLen); if (leftPart.Equals(rightPart)) { if (leftPart.Length == 10) { result.Append($"ticket \"{ ticket}\" - {minLen}{leftPart.Substring(0, 1)} Jackpot!{Environment.NewLine}"); } else { result.Append($"ticket \"{ ticket}\" - {minLen}{leftPart.Substring(0, 1)}{Environment.NewLine}"); } } else { result.Append($"ticket \"{ ticket}\" - no match{Environment.NewLine}"); } } } } Console.Write(result.ToString()); } }
namespace DeemZ.Models.ViewModels.ChatMessages { using System; using System.ComponentModel.DataAnnotations; public class ChatMessageViewModel { [Required] public string Content { get; set; } public string ApplicationUserId { get; set; } public string ApplicationUserUsername { get; set; } public string ApplicationUserImgUrl { get; set; } public string CourseName { get; set; } public string CourseId { get; set; } public DateTime SentOn { get; set; } = DateTime.UtcNow; } }
using UnityEngine; using System.Collections; using UnityEngine.EventSystems; namespace QFramework { /// <summary> /// 返回空类型的回调定义 /// </summary> public class QVoidDelegate{ public delegate void WithVoid(); public delegate void WithGo(GameObject go); public delegate void WithParams(params object[] paramList); public delegate void WithEvent(BaseEventData data); public delegate void WithObj(Object obj); public delegate void WithBool(bool value); } public delegate void DTableOnParse(byte[] data); public delegate void Run(); public delegate void Run<T>(T v); public delegate void Run<T, K>(T v1, K v2); }
using Cirrious.Conference.Core.ViewModels; using Cirrious.MvvmCross.Views; namespace Cirrious.Conference.UI.Touch.Views { public class SponsorsView : BaseSponsorsView<SponsorsViewModel> { public SponsorsView(MvxShowViewModelRequest request) : base(request) { } } }
using System; using System.Collections.Generic; using System.Text; using HotChocolate; using HotChocolate.AspNetCore.Extensions; using HotChocolate.AspNetCore.Serialization; using HotChocolate.Execution.Configuration; using HotChocolate.PreProcessingExtensions; using HotChocolate.PreProcessingExtensions.Tests.GraphQL; using HotChocolate.Resolvers; using HotChocolate.Types.Pagination; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; namespace HotChocolate.PreProcessingExtensions.Tests { public class GraphQLStarWarsTestServer : GraphQLTestServerBase { public GraphQLStarWarsTestServer(GraphQLTestServerFactory serverFactory) { this.Server = CreateTestServer( serverFactory, servicesConfigure: services => { //BBernard //Configure the test server and Load PreProcessedResults Custom Middleware! var graphQLBuilder = services .AddGraphQLServer() .AddQueryType(d => d.Name("Query")) .AddType<HelloWorldResolver>() .AddType<StarWarsCharacterResolver>() .AddType<StarWarsHuman>() .AddType<StarWarsDroid>() .SetPagingOptions(new PagingOptions() { DefaultPageSize = 5, IncludeTotalCount = true, MaxPageSize = 10 }) .AddPreProcessedResultsExtensions(); return graphQLBuilder; } ); } } }
 namespace CommonCore.State { //base class for Intents //Intents are created by one scene and executed on the next or on the loading screen public abstract class Intent { public virtual void LoadingExecute() { } public virtual void PreloadExecute() { } public virtual void PostloadExecute() { } } }
using System.ComponentModel.DataAnnotations; using MediatR; #pragma warning disable 8618 // ReSharper disable AutoPropertyCanBeMadeGetOnly.Global namespace Playlister.CQRS.Commands { /// <summary> /// Request to Update the Playlist data stored in the database /// </summary> // ReSharper disable once UnusedType.Global public record UpdatePlaylistCommand : IRequest<Unit> { public UpdatePlaylistCommand(string accessToken, string playlistId) { AccessToken = accessToken; PlaylistId = playlistId; } // ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once UnusedAutoPropertyAccessor.Global public string AccessToken { get; } // ReSharper disable once UnassignedGetOnlyAutoProperty public string PlaylistId { get; } /// <summary> /// The index of the first track to return. /// Default: <c>0</c> (the first object). Maximum offset: <c>100.000</c>. /// Use with limit to get the next set of playlists. /// </summary> [Range(0, 100_000)] public int Offset { get; init; } = 0; /// <summary> /// The maximum number of tracks to return. /// Default: <c>50</c>. Minimum: <c>1</c>. Maximum: <c>50</c>. /// Note: the Default on Spotify API is 50. /// </summary> [Range(0, 50)] public int Limit { get; init; } = 50; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DAO.Access; using VO.Entities; using VO.ExceptionHandler; using VO.Interfaces.BLL; namespace Bll { /// <summary> /// clase de negocio para clientes /// </summary> [PrintException(typeof(Exception))] public class Client : IClients { public DAOContainer DAO { get; set; } public List<ClientUser> List(string word) { throw new NotImplementedException(); } /// <summary> /// crea un nuevo cliente /// </summary> /// <param name="entity"></param> /// <returns></returns> public ClientUser Create(ClientUser entity) { VO.Entities.ClientUser data = null; data = DAO.Resolve<ClientsDAO>().Create(entity); return data; } /// <summary> /// actualiza un cliente /// </summary> /// <param name="entity"></param> /// <returns></returns> public ClientUser Update(ClientUser entity) { VO.Entities.ClientUser data = null; data = DAO.Resolve<ClientsDAO>().Update(entity); return data; } /// <summary> /// elimina un cliente /// </summary> /// <param name="id"></param> /// <returns></returns> public ClientUser Delete(int id) { VO.Entities.ClientUser data = DAO.Resolve<ClientsDAO>().Get(id); DAO.Resolve<ClientsDAO>().Delete(data); return data; } /// <summary> /// obtiene un cliente por su id de usuario /// </summary> /// <param name="userId"></param> /// <returns></returns> public ClientUser Get(int userId) { return DAO.Resolve<ClientsDAO>().Get(userId); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AAAI_veto_core { class Program { public static Random RandomGenerator = new Random(); static void Main(string[] args) { // Values of n,m to check var agentNumbers = new int[] { 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var candidateNumbers = new int[] { 2, 3, 4, 5 }; Simulations.AverageNumberOfWinners( agentNumbers, candidateNumbers, 100, // Number of repetitions. prof => VotingFunctions.FindVetoCore(prof), // FindVetoByConsumptionWinners for veto by consumption. (agents, candidates) => Profile.GenerateICProfile(agents, candidates)); Console.ReadLine(); } } }
using HtmlAgilityPack; namespace VeilleConcurrentielle.Scraper.ConsoleApp { public class HtmlDocumentLoader : IHtmlDocumentLoader { public HtmlDocument GetHtmlDocument(string url) { HtmlWeb web = new HtmlWeb(); var htmlDoc = web.Load(url); return htmlDoc; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Data; using VersionManager.BO; using System.Globalization; using VersionManager.ViewModel; using ViewModelBasic; namespace VersionManager { internal class SoftSelectCustomerConvertor : IValueConverter, IRefresh { private CustomerListVM _customervm; private CustomerListVM Customervm { get { if (_customervm == null) { _customervm = new CustomerListVM(); } return _customervm; } } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var allcustomers = Customervm.Entities; //重置选择项 foreach (var item in allcustomers) { item.IsHold = false; } SoftToUpdateBO soft = (SoftToUpdateBO)value; foreach (var customer in soft.Customers) { var item = allcustomers.FirstOrDefault(o => o.ID == customer.ID); if (item != null) { item.IsHold = true; } } return allcustomers; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } public void Refresh() { Customervm.Refresh(); } } }
// // This sample shows how to create data dynamically based on the // responses from a remote server. // // It uses the BindingContext API for the login screen (we might // as well) and the Element tree API for the actual tweet contents // using System; using System.Net; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using UIKit; using Foundation; using MonoTouch.Dialog; namespace Sample { public partial class AppDelegate { DialogViewController dynamic; BindingContext context; AccountInfo account; class AccountInfo { [Section ("Twitter credentials", "This sample loads various information\nsources dynamically from your twitter\naccount.")] [Entry ("Enter your login name")] public string Username; [Password ("Enter your password")] public string Password; [Section ("Tap to fetch the timeline")] [OnTap ("FetchTweets")] [Preserve] public string Login; } bool Busy { get { #if __TVOS__ return false; #else return UIApplication.SharedApplication.NetworkActivityIndicatorVisible; #endif // __TVOS__ } set { #if !__TVOS__ UIApplication.SharedApplication.NetworkActivityIndicatorVisible = value; #endif // !__TVOS__ } } public void FetchTweets () { if (Busy) return; Busy = true; // Fetch the edited values. context.Fetch (); var request = (HttpWebRequest)WebRequest.Create ("http://twitter.com/statuses/friends_timeline.xml"); request.Credentials = new NetworkCredential (account.Username, account.Password); request.BeginGetResponse (TimeLineLoaded, request); } // Creates the dynamic content from the twitter results RootElement CreateDynamicContent (XDocument doc) { var users = doc.XPathSelectElements ("./statuses/status/user").ToArray (); var texts = doc.XPathSelectElements ("./statuses/status/text").Select (x=>x.Value).ToArray (); var people = doc.XPathSelectElements ("./statuses/status/user/name").Select (x=>x.Value).ToArray (); var section = new Section (); var root = new RootElement ("Tweets") { section }; for (int i = 0; i < people.Length; i++){ var line = new RootElement (people [i]) { new Section ("Profile"){ new StringElement ("Screen name", users [i].XPathSelectElement ("./screen_name").Value), new StringElement ("Name", people [i]), new StringElement ("oFllowers:", users [i].XPathSelectElement ("./followers_count").Value) }, new Section ("Tweet"){ new StringElement (texts [i]) } }; section.Add (line); } return root; } void TimeLineLoaded (IAsyncResult result) { var request = result.AsyncState as HttpWebRequest; Busy = false; try { var response = request.EndGetResponse (result); var stream = response.GetResponseStream (); var root = CreateDynamicContent (XDocument.Load (new XmlTextReader (stream))); InvokeOnMainThread (delegate { var tweetVC = new DialogViewController (root, true); navigation.PushViewController (tweetVC, true); }); } catch (WebException e){ InvokeOnMainThread (delegate { var alertController = UIAlertController.Create ("Error", "Code: " + e.Status, UIAlertControllerStyle.Alert); alertController.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, (obj) => { })); window.RootViewController.PresentViewController (alertController, true, null); }); } } public void DemoDynamic () { account = new AccountInfo (); context = new BindingContext (this, account, "Settings"); if (dynamic != null) dynamic.Dispose (); dynamic = new DialogViewController (context.Root, true); navigation.PushViewController (dynamic, true); } } }
namespace FeatureSwitcher.Contexteer.Specs.Domain { public class FeatureConfiguration { public long Id { get; set; } public string FeatureName { get; set; } public long? ClientId { get; set; } public long? UseraccountId { get; set; } public UserRole Role { get; set; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; namespace Microsoft.DotNet.ProjectModel.Graph { public struct LibraryType : IEquatable<LibraryType> { public static readonly LibraryType Package = new LibraryType(nameof(Package)); public static readonly LibraryType Project = new LibraryType(nameof(Project)); public static readonly LibraryType ReferenceAssembly = new LibraryType(nameof(ReferenceAssembly)); public static readonly LibraryType MSBuildProject = new LibraryType(nameof(MSBuildProject)); // Default value public static readonly LibraryType Unspecified = new LibraryType(); public string Value { get; } private LibraryType(string value) { Value = value; } public static bool TryParse(string value, out LibraryType type) { // We only support values we know about if (string.Equals(Package.Value, value, StringComparison.OrdinalIgnoreCase)) { type = Package; return true; } else if (string.Equals(Project.Value, value, StringComparison.OrdinalIgnoreCase)) { type = Project; return true; } type = Unspecified; return false; } public override string ToString() { return Value ?? nameof(Unspecified); } public bool CanSatisfyConstraint(LibraryType constraint) { // Reference assemblies must be explicitly asked for if (Equals(ReferenceAssembly, constraint)) { return Equals(ReferenceAssembly, this); } else if (Equals(constraint, Unspecified)) { return true; } else { return string.Equals(constraint.Value, Value, StringComparison.OrdinalIgnoreCase); } } public bool Equals(LibraryType other) { return string.Equals(other.Value, Value, StringComparison.OrdinalIgnoreCase); } public override bool Equals(object obj) { return obj is LibraryType && Equals((LibraryType)obj); } public static bool operator ==(LibraryType left, LibraryType right) { return Equals(left, right); } public static bool operator !=(LibraryType left, LibraryType right) { return !Equals(left, right); } public override int GetHashCode() { if (string.IsNullOrEmpty(Value)) { return 0; } return StringComparer.OrdinalIgnoreCase.GetHashCode(Value); } } }
namespace Microshaoft { using System; using System.Reflection; public class InterceptorDispatchProxy<T> : DispatchProxy { public T Sender; public Func<T, MethodInfo, object[], bool> OnInvokingProcessFunc; public Action<T, MethodInfo, object[]> OnInvokedProcessAction; protected override object Invoke(MethodInfo targetMethod, object[] args) { if (OnInvokingProcessFunc != null) { var r = OnInvokingProcessFunc.Invoke(Sender, targetMethod, args); if ( r && //don't block intercept function targetMethod.ReturnType == typeof(void) ) { return null; } } try { return targetMethod.Invoke(Sender, args); } finally { OnInvokedProcessAction?.Invoke(Sender, targetMethod, args); } } } } namespace ConsoleApp71 { using Microshaoft; using System; using System.Reflection; class Program { static void Main(string[] args) { var proxy = DispatchProxy.Create<IProcessAble, InterceptorDispatchProxy<IProcessAble>>(); InterceptorDispatchProxy<IProcessAble> commonDispatchProxy = (InterceptorDispatchProxy<IProcessAble>)proxy; commonDispatchProxy.Sender = new Processor(); commonDispatchProxy.OnInvokingProcessFunc = (x, y, z) => { Console.WriteLine($"{nameof(commonDispatchProxy.OnInvokingProcessFunc)}:{y.Name}"); return false; }; commonDispatchProxy.OnInvokedProcessAction = (x, y, z) => { Console.WriteLine($"{nameof(commonDispatchProxy.OnInvokedProcessAction)}:{y.Name}"); }; proxy.Process(); proxy.Process("asdasdas"); proxy.Process2(); Console.WriteLine(); Console.ReadLine(); } } public class Processor : IProcessAble { public void Process() { Console.WriteLine("Process"); } public int Process(string x) { Console.WriteLine($"Process {x}"); return 1; } void IProcessAble.Process2() { Console.WriteLine("process2 in impl class"); } } interface IProcessAble { void Process(); int Process(string x); void Process2() { Console.WriteLine("process2 in interface"); } } }
namespace Tickr.Tests.Integration { using System.Net.Http; using Xunit; public class GetAllItemsTest : IClassFixture<TestFixture> { private readonly HttpClient _httpClient; public GetAllItemsTest(TestFixture testFixture) { _httpClient = testFixture.CreateClient(); } } }
namespace System.Windows.Forms { /// <summary> /// implement your windows hook here. /// </summary> internal static class MouseHook { public static event MouseEventHandler MouseDown; [Obsolete("not supported yet")] public static event MouseEventHandler MouseMove; public static event MouseEventHandler MouseUp; [Obsolete("not supported yet")] public static event MouseEventHandler MouseWheel; public static void RaiseMouseDown(object sender, MouseEventArgs args) { var handler = MouseDown; if (handler != null) handler(sender, args); } public static void RaiseMouseMove(object sender, MouseEventArgs args) { #pragma warning disable 618 var handler = MouseMove; #pragma warning restore 618 if (handler != null) handler(sender, args); } public static void RaiseMouseWheel(object sender, MouseEventArgs args) { #pragma warning disable 618 var handler = MouseWheel; #pragma warning restore 618 if (handler != null) handler(sender, args); } public static void RaiseMouseUp(object sender, MouseEventArgs args) { var handler = MouseUp; if (handler != null) handler(sender, args); } } }
using UnityEngine; using System.Collections; public class BeiBaoItem : MonoBehaviour { private ItemTypeInfo Info; private int m_num ; private BeiBaoWnd m_parent; public BeiBaoItem_h MyHead { get { return GetComponent<BeiBaoItem_h>(); } } public ItemTypeInfo GetInfo() { return Info; } public void BindEvents() { if (MyHead.BtnSelect) { MyHead.BtnSelect.OnClickEventHandler += BtnSelect_OnClickEventHandler; } } void BtnSelect_OnClickEventHandler(UIButton sender) { if (Info == null ) { NGUIUtil.DebugLog("BeiBaoItem.cs Info == null!!!"); return; } else { if(m_parent != null) m_parent.ItemClickCallBack(Info); } } public void BtnToggValueChange() { if(MyHead.TogSelect.value) { NGUIUtil.SetSprite(MyHead.SprSelect,"icon101"); } else { NGUIUtil.SetSprite(MyHead.SprSelect,""); } } public void SetData(ItemTypeInfo I ,int num ,BeiBaoWnd wnd) { Info= I ; m_num = num; m_parent = wnd; } // Use this for initialization void Start () { SetUI(); BindEvents (); } private void SetUI() { if (Info == null ) { NGUIUtil.DebugLog("BeiBaoItem.cs Info == null!!!"); return; } if(MyHead.SprType != null ) NGUIUtil.Set2DSprite(MyHead.SprType, "Textures/item/",Info.m_Icon.ToString()); //设置物品品阶 if(MyHead.SprQuality != null) NGUIUtil.SetSprite(MyHead.SprQuality, ConfigM.GetBigQuality(Info.m_Quality).ToString()); //设置物品数量 if(MyHead.LblCounts != null) NGUIUtil.SetLableText<int>(MyHead.LblCounts, m_num); } }
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Azure.Storage.Blob; namespace FileManager.Azure.Helpers { public static class BlobContainerHelpers { public static async Task<List<IListBlobItem>> ListBlobsAsync(this CloudBlobContainer container) { BlobContinuationToken continuationToken = null; List<IListBlobItem> results = new List<IListBlobItem>(); do { var response = await container.ListBlobsSegmentedAsync(continuationToken); continuationToken = response.ContinuationToken; results.AddRange(response.Results); } while (continuationToken != null); return results; } } }
using ImageWizard.Processing; using ImageWizard.Processing.Results; using OpenCvSharp; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace ImageWizard.OpenCvSharp.Filters { /// <summary> /// FilterContext /// </summary> public class OpenCvSharpFilterContext : FilterContext { public OpenCvSharpFilterContext(PipelineContext processingContext) : base(processingContext) { } public override void Dispose() { } public override async Task<DataResult> BuildResultAsync() { //using var haarCascade = new CascadeClassifier(TextPath.HaarCascade); //using Mat src = new Mat("lenna.png", ImreadModes.Unchanged); //Stream mem = ProcessingContext.StreamPool.GetStream(); //src.WriteToStream(mem); //mem.Seek(0, SeekOrigin.Begin); //return new DataResult(mem, MimeTypes.Png); throw new Exception(); } } }
namespace TPUM.Communication { public enum InterchangeStatus { Success, Fail } public class Interchange { public InterchangeStatus Status { get; set; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; using Moq; using Xunit; namespace NuGetGallery { public class DeploymentIdTelemetryEnricherFacts { private const string PropertyKey = "CloudDeploymentId"; public DeploymentIdTelemetryEnricherFacts() { Telemetry = new Mock<ITelemetry>(); Telemetry.Setup(x => x.Context).Returns(new TelemetryContext()); Target = new Mock<TestableDeploymentIdTelemetryEnricher>(); Target.Object.SetDeploymentId("TheDeploymentId"); } public Mock<ITelemetry> Telemetry { get; } public Mock<TestableDeploymentIdTelemetryEnricher> Target { get; } [Fact] public void DoesNothingWithNullTelemetry() { Target.Object.Initialize(telemetry: null); Target.Verify(x => x.DeploymentId, Times.Never); Assert.DoesNotContain(PropertyKey, Telemetry.Object.Context.Properties.Keys); } [Fact] public void DoesNothingWhenDeploymentIdIsNull() { Target.Object.SetDeploymentId(null); Target.Object.Initialize(Telemetry.Object); Target.Verify(x => x.DeploymentId, Times.Never); Assert.DoesNotContain(PropertyKey, Telemetry.Object.Context.Properties.Keys); } [Fact] public void DoesNothingWhenDeploymentIdIsAlreadySet() { Telemetry.Object.Context.Properties[PropertyKey] = "something else"; Target.Object.Initialize(Telemetry.Object); Target.Verify(x => x.DeploymentId, Times.Never); Assert.Equal(Telemetry.Object.Context.Properties[PropertyKey], "something else"); } [Fact] public void SetsDeploymentId() { Target.Object.Initialize(Telemetry.Object); Assert.Equal(Telemetry.Object.Context.Properties[PropertyKey], "TheDeploymentId"); } public class TestableDeploymentIdTelemetryEnricher : DeploymentIdTelemetryEnricher { private string _deploymentId; public void SetDeploymentId(string deploymentId) { _deploymentId = deploymentId; } internal override string DeploymentId => _deploymentId; } } }
using Cyclops.Xmpp.Data.Rooms; namespace Cyclops.Xmpp.Data; public interface IExtendedUserData { public IReadOnlyList<MucUserStatus?> Status { get; } public IRoomItem? RoomItem { get; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using PlayerState = SimplePhotonNetworkManager.PlayerState; public class UIPhotonWaitingPlayer : MonoBehaviour { public Text textPlayerName; public Text textPlayerState; public string playerStateReady = "Ready"; public string playerStateNotReady = "Not Ready"; public GameObject[] hostObjects; public GameObject[] owningObjects; public UIPhotonWaitingRoom Room { get; private set; } public PhotonPlayer Data { get; private set; } public void SetData(UIPhotonWaitingRoom room, PhotonPlayer data) { Room = room; Data = data; PlayerState state = PlayerState.NotReady; if (data.CustomProperties.ContainsKey(SimplePhotonNetworkManager.CUSTOM_PLAYER_STATE)) state = (PlayerState)(byte)data.CustomProperties[SimplePhotonNetworkManager.CUSTOM_PLAYER_STATE]; if (textPlayerName != null) textPlayerName.text = data.NickName; if (textPlayerState != null) { switch (state) { case PlayerState.Ready: textPlayerState.text = playerStateReady; break; case PlayerState.NotReady: textPlayerState.text = playerStateNotReady; break; } } foreach (var hostObject in hostObjects) { hostObject.SetActive(room.HostPlayerID.Equals(data.UserId)); } foreach (var owningObject in owningObjects) { owningObject.SetActive(PhotonNetwork.player.UserId.Equals(data.UserId)); } } }
using System; using System.Collections.Generic; using System.Linq; using EnvDTE; namespace NuGet.VisualStudio { /// <summary> /// Cache that stores project based on multiple names. i.e. Project can be retrieved by name (if non conflicting), unique name and custom unique name. /// </summary> internal class ProjectCache { // Mapping from project name structure to project instance private readonly Dictionary<ProjectName, Project> _projectCache = new Dictionary<ProjectName, Project>(); // Mapping from all names to a project name structure private readonly Dictionary<string, ProjectName> _projectNamesCache = new Dictionary<string, ProjectName>(StringComparer.OrdinalIgnoreCase); // We need another dictionary for short names since there may be more than project name per short name private readonly Dictionary<string, HashSet<ProjectName>> _shortNameCache = new Dictionary<string, HashSet<ProjectName>>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Finds a project by short name, unique name or custom unique name. /// </summary> /// <param name="name">name of the project to retrieve.</param> /// <param name="project">project instance</param> /// <returns>true if the project with the specified name is cached.</returns> public bool TryGetProject(string name, out Project project) { project = null; // First try to find the project name in one of the dictionaries. Then locate the project for that name. ProjectName projectName; return TryGetProjectName(name, out projectName) && _projectCache.TryGetValue(projectName, out project); } /// <summary> /// Finds a project name by short name, unique name or custom unique name. /// </summary> /// <param name="name">name of the project</param> /// <param name="projectName">project name instance</param> /// <returns>true if the project name with the specified name is found.</returns> public bool TryGetProjectName(string name, out ProjectName projectName) { return _projectNamesCache.TryGetValue(name, out projectName) || TryGetProjectNameByShortName(name, out projectName); } /// <summary> /// Removes a project and returns the project name instance of the removed project. /// </summary> /// <param name="name">name of the project to remove.</param> public void RemoveProject(string name) { ProjectName projectName; if (_projectNamesCache.TryGetValue(name, out projectName)) { // Remove from both caches RemoveProjectName(projectName); RemoveShortName(projectName); } } public bool Contains(string name) { if (name == null) { return false; } return _projectNamesCache.ContainsKey(name) || _shortNameCache.ContainsKey(name); } /// <summary> /// Returns all cached projects. /// </summary> public IEnumerable<Project> GetProjects() { return _projectCache.Values; } /// <summary> /// Determines if a short name is ambiguous /// </summary> /// <param name="shortName">short name of the project</param> /// <returns>true if there are multiple projects with the specified short name.</returns> public bool IsAmbiguous(string shortName) { HashSet<ProjectName> projectNames; if (_shortNameCache.TryGetValue(shortName, out projectNames)) { return projectNames.Count > 1; } return false; } /// <summary> /// Add a project to the cache. /// </summary> /// <param name="project">project to add to the cache.</param> /// <returns>The project name of the added project.</returns> public ProjectName AddProject(Project project) { // First create a project name from the project var projectName = new ProjectName(project); // Do nothing if we already have an entry if (_projectCache.ContainsKey(projectName)) { return projectName; } AddShortName(projectName); _projectNamesCache[projectName.CustomUniqueName] = projectName; _projectNamesCache[projectName.UniqueName] = projectName; _projectNamesCache[projectName.FullName] = projectName; // Add the entry mapping project name to the actual project _projectCache[projectName] = project; return projectName; } /// <summary> /// Tries to find a project by short name. Returns the project name if and only if it is non-ambiguous. /// </summary> public bool TryGetProjectNameByShortName(string name, out ProjectName projectName) { projectName = null; HashSet<ProjectName> projectNames; if (_shortNameCache.TryGetValue(name, out projectNames)) { // Get the item at the front of the queue projectName = projectNames.Count == 1 ? projectNames.Single() : null; // Only return true if the short name is unambiguous return projectName != null; } return false; } /// <summary> /// Adds an entry to the short name cache returning any conflicting project name. /// </summary> /// <returns>The first conflicting short name.</returns> private void AddShortName(ProjectName projectName) { HashSet<ProjectName> projectNames; if (!_shortNameCache.TryGetValue(projectName.ShortName, out projectNames)) { projectNames = new HashSet<ProjectName>(); _shortNameCache.Add(projectName.ShortName, projectNames); } projectNames.Add(projectName); } /// <summary> /// Removes a project from the short name cache. /// </summary> /// <param name="projectName">The short name of the project.</param> private void RemoveShortName(ProjectName projectName) { HashSet<ProjectName> projectNames; if (_shortNameCache.TryGetValue(projectName.ShortName, out projectNames)) { projectNames.Remove(projectName); // Remove the item from the dictionary if we've removed the last project if (projectNames.Count == 0) { _shortNameCache.Remove(projectName.ShortName); } } } /// <summary> /// Removes a project from the project name dictionary. /// </summary> private void RemoveProjectName(ProjectName projectName) { _projectNamesCache.Remove(projectName.CustomUniqueName); _projectNamesCache.Remove(projectName.UniqueName); _projectNamesCache.Remove(projectName.FullName); _projectCache.Remove(projectName); } } }
namespace UnityModule.AssetBundleManagement { public static class Constants { public const string AssetBundleExtension = ".unity3d"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Acuerdo.External.Shortener; using Inscribe.Configuration; namespace Inscribe.Plugin { public static class ShortenManager { private static List<IUrlShortener> shorteners = new List<IUrlShortener>(); private static List<IUriExtractor> extractors = new List<IUriExtractor>(); [Obsolete("Krile is no longer supported shortener services.")] public static IEnumerable<IUrlShortener> Shorteners { get { return shorteners; } } public static IEnumerable<IUriExtractor> Extractors { get { return extractors; } } [Obsolete("Krile is no longer supported shortener services.")] public static void RegisterShortener(IUrlShortener shortener) { shorteners.Add(shortener); } public static void RegisterExtractor(IUriExtractor extractor) { extractors.Add(extractor); } public static void RegisterAllShortenersInAsm(Assembly asm) { foreach (var type in asm.GetTypes()) { var ifs = type.GetInterfaces(); if (ifs.Contains(typeof(IUrlShortener))) { RegisterShortener(Activator.CreateInstance(type) as IUrlShortener); } else if (ifs.Contains(typeof(IUriExtractor))) { RegisterExtractor(Activator.CreateInstance(type) as IUriExtractor); } } } private static CommonExtractor commonExtractor = new CommonExtractor(); /// <summary> /// URLの解決を試みます。<para /> /// 何も無い場合は、そのままのURLを返します。 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string Extract(string url) { string extd; foreach (var ext in extractors) { if (!ext.TryDecompress(url, out extd)) { return extd; } } if (commonExtractor.TryDecompress(url, out extd)) { return extd; } return url; } /// <summary> /// URLがすでに短縮されているか確認します。 /// </summary> /// <param name="url">確認するURL</param> /// <returns>短縮されていればtrue</returns> [Obsolete("Krile is no longer supported shortener services.")] public static bool IsShortedThis(string url) { foreach (var c in shorteners) { if (c.IsCompressed(url)) return true; } return false; } /// <summary> /// URLの短縮を行うインスタンスを取得します。 /// </summary> /// <returns>短縮サービスのインスタンス、指定がない場合はNULL</returns> [Obsolete("Krile is no longer supported shortener services.")] public static IUrlShortener GetSuggestedShortener() { throw new NotSupportedException(); /* string sn = Setting.Instance.ExternalServiceProperty.ShortenerService; if (String.IsNullOrEmpty(sn)) return null; foreach (var ss in shorteners) { if (ss.Name == sn) { return ss; } } return null; */ } } }
namespace BlazorShop.Web.Client.Infrastructure { using System.Net.Http; using System.Net.Http.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.Components.Authorization; using Web.Shared.Identity; public class AuthClient : IAuthClient { private readonly HttpClient httpClient; private readonly AuthenticationStateProvider authenticationProvider; public AuthClient( HttpClient httpClient, AuthenticationStateProvider authenticationProvider) { this.httpClient = httpClient; this.authenticationProvider = authenticationProvider; } public async Task<bool> LoginAsync(LoginRequestModel model) { var result = await this.httpClient.PostAsJsonAsync("api/identity/login", model); var response = await result.Content.ReadFromJsonAsync<LoginResponseModel>(); var token = response.Token; if (token != null) { await ((TokenAuthenticationStateProvider)this.authenticationProvider).SetTokenAsync(token); return true; } return false; } public async Task RegisterAsync(RegisterRequestModel model) => await this.httpClient.PostAsJsonAsync("api/identity/register", model); public async Task LogoutAsync() => await ((TokenAuthenticationStateProvider)this.authenticationProvider).SetTokenAsync(null); } }
using SLOBSharp.Client.Requests; using SLOBSharp.Client.Requests.Scenes; using Xunit; namespace SLOBSharp.Tests.Client.Requests { public class RequestObjectTests { [Fact] public void CanBuildASlobsGetActiveSceneRequest() { var mockedRequest = new SlobsRequest { Method = "activeScene" }; mockedRequest.Parameters.SetResource("ScenesService"); var slobsGetActiveSceneRequest = new SlobsGetActiveSceneRequest(); Assert.Equal(mockedRequest.Method, slobsGetActiveSceneRequest.Method); Assert.True(mockedRequest.Parameters.Equals(slobsGetActiveSceneRequest.Parameters)); } } }
namespace Byndyusoft.Dotnet.Core.Samples.Web.DataAccess.Values.Commands { using System; using Domain.CommandsContexts.Values; using Infrastructure.CQRS.Abstractions.Commands; using JetBrains.Annotations; using Repository; [UsedImplicitly] public class SetValueCommand : ICommand<SetValueCommandContext> { private readonly IValuesRepository _repository; public SetValueCommand(IValuesRepository repository) { if(repository == null) throw new ArgumentNullException(); _repository = repository; } public void Execute(SetValueCommandContext commandContext) { _repository.Set(commandContext.Id, commandContext.Value); } } }
using System; namespace SadRogue.Primitives.SerializedTypes { /// <summary> /// Serializable (pure-data) object representing a <see cref="Point"/>. /// </summary> [Serializable] public struct PointSerialized { /// <summary> /// X-coordinate of the point. /// </summary> public int X; /// <summary> /// Y-coordinate of the point. /// </summary> public int Y; /// <summary> /// Converts from <see cref="Point"/> to <see cref="PointSerialized"/>. /// </summary> /// <param name="point"/> /// <returns/> public static implicit operator PointSerialized(Point point) => new PointSerialized() { X = point.X, Y = point.Y }; /// <summary> /// Converts from <see cref="PointSerialized"/> to <see cref="Point"/>. /// </summary> /// <param name="serialized"/> /// <returns/> public static implicit operator Point(PointSerialized serialized) => new Point(serialized.X, serialized.Y); } }
using System; namespace JsonApiDotNetCore.Models { public class ResourceAttribute : Attribute { public ResourceAttribute(string resourceName) { ResourceName = resourceName; } public string ResourceName { get; set; } } }
using System; namespace NodeDialog.Graph { /// <summary> /// Attribute for describing the assets to use when creating a node. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] public class BaseNodeVisualAttribute : Attribute { public const string DEFAULT_NORMAL_IMAGE = "node0 hex"; public const string DEFAULT_SELECTED_IMAGE = "node0 hex on"; /// <summary> /// The filename of the "normal" image for this node. /// </summary> public string normalImage { get; private set; } /// <summary> /// The filename of the "selected" image for this node. /// </summary> public string selectedImage { get; private set; } /// <summary> /// Attribute for describing the assets to use when creating a node. /// </summary> /// <param name="normalImage">The filename of the "normal" image for this node.</param> /// <param name="selectedImage">The filename of the "selected" image for this node.</param> public BaseNodeVisualAttribute(string normalImage, string selectedImage) { this.normalImage = normalImage; this.selectedImage = selectedImage; } } }
using System; using NumeralDash.Entities; using System.Collections.Generic; using SadRogue.Primitives; namespace NumeralDash.Rules { class RuleBase { static Type[] rules = { typeof(UpAndDownOrder), typeof(ReverseOrder), typeof(SequentialOrder), typeof(RandomOrder), }; public static IRule GetRandomRule(int numberCount) { var index = Program.GetRandomIndex(rules.Length); object? o = Activator.CreateInstance(rules[index], numberCount); if (o is IRule r) return r; else throw new InvalidOperationException("Could not create a new rule."); } #region Storage /// <summary> /// A list of remaing numbers to be collected. /// </summary> protected List<Number> RemainingNumbers { get; init; } /// <summary> /// Amount of numbers to be generated. /// </summary> protected int NumberCount { get; set; } /// <summary> /// Next number to be collected. /// </summary> public Number NextNumber { get; protected set; } = Number.Empty; /// <summary> /// Initial list of all numbers to collect from the map. /// </summary> public Number[] Numbers { get; init; } /// <summary> /// Foreground color. /// </summary> public Color Color { get; protected set; } #endregion public RuleBase(int count) { if (count < 1) { throw new ArgumentException("Minimum amount of numbers to generate is 1."); } NumberCount = count; RemainingNumbers = new(); Numbers = new Number[NumberCount]; } public virtual void SetNextNumber() { if (RemainingNumbers.Count >= 1) { SetNextAndRemove(0); OnNextNumberChanged(RemainingNumbers.Count + 1); } else { NextNumber = Number.Finished; OnNextNumberChanged(0); } } protected void SetNextAndRemove(int index) { NextNumber = RemainingNumbers[index]; RemainingNumbers.RemoveAt(index); } #region Events protected void OnNextNumberChanged(int numbersRemaining) { NextNumberChanged?.Invoke(NextNumber, numbersRemaining); } public event Action<Number, int>? NextNumberChanged; #endregion } }
using Abp.Application.Services.Dto; using SPA.DocumentManager.Enums.Extensions; using SPA.DocumentManager.PlanProjectTypes; using SPA.DocumentManager.PlanProjectTypes.Dtos; using SPA.DocumentManager.Plans; using SPA.DocumentManager.Plans.Dtos; namespace SPA.DocumentManager.PlanProjects.Dtos { public class PlanProjectListDto { public int PlanProjectTypeId { get; set; } public string PlanProjectTypeName { get; set; } public int Id { get; set; } public string SubProjectName { get; set; } public double PlannedWorkLoad { get; set; } public double PlannedCost { get; set; } public string Description { get; set; } public int PlanId { get; set; } public string PlanName { get; set; } public UnitType Unit { get; set; } public string UnitTypeDescription => Unit.ToDescription(); //public PlanProjectTypeListDto PlanProjectType { get; set; } //public PlanListDto Plan { get; set; } } }
using Microsoft.AspNetCore.Razor.TagHelpers; using System; using System.Collections.Generic; using System.Threading.Tasks; using Xunit; namespace Spid.Cie.OIDC.AspNetCore.Tests; public class CieButtonTests { [Fact] public async Task CieButtonTagHelper() { var context = new TagHelperContext( new TagHelperAttributeList(new List<TagHelperAttribute>() { new TagHelperAttribute("spid") }), new Dictionary<object, object>(), Guid.NewGuid().ToString("N")); var tagHelperOutput = new TagHelperOutput("markdown", new TagHelperAttributeList(new List<TagHelperAttribute>() { new TagHelperAttribute("spid") }), (result, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetHtmlContent(string.Empty); return Task.FromResult<TagHelperContent>(tagHelperContent); }); var tagHelper = new Mvc.CieButtonTagHelper(new Mocks.MockIdentityProvidersHandler(false)); tagHelper.ChallengeUrl = "http://127.0.0.1:8002/"; await tagHelper.ProcessAsync(context, tagHelperOutput); } [Fact] public async Task CieButtonTagHelperEmptyCollection() { var context = new TagHelperContext( new TagHelperAttributeList(new List<TagHelperAttribute>() { new TagHelperAttribute("spid") }), new Dictionary<object, object>(), Guid.NewGuid().ToString("N")); var tagHelperOutput = new TagHelperOutput("markdown", new TagHelperAttributeList(new List<TagHelperAttribute>() { new TagHelperAttribute("spid") }), (result, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetHtmlContent(string.Empty); return Task.FromResult<TagHelperContent>(tagHelperContent); }); var tagHelper = new Mvc.CieButtonTagHelper(new Mocks.MockIdentityProvidersHandler(true)); tagHelper.ChallengeUrl = "http://127.0.0.1:8002/"; await tagHelper.ProcessAsync(context, tagHelperOutput); } }
using System; using System.Collections.Generic; namespace ToyLanguage_NET { public interface Repository { List<PrgState> PrgStates { get; set; } void serializePrgStatet (); void logPrgState (); void deserializePrgStatet (); } }
#if UNITY_EDITOR #endif namespace RPGCore.Tables { public class MultiAssetSelector<T, E> : AssetSelector<T, E> where E : GenericTableEntry<T> { public uint Rolls = 1; public T[] SelectMultiple () { T[] selected = new T[Rolls]; for (uint i = 0; i < Rolls; i++) { selected[i] = Select (); } return selected; } } }
using System; using System.Collections.Generic; using System.Text; namespace Playground { class NameReverser { public static void Run() { Console.WriteLine("Please enter your name (type \"exit\" to finish):"); var name = Console.ReadLine(); while (name.Length <= 0) { Console.WriteLine("You did not enter a name! Try again!"); name = Console.ReadLine(); } if (name.ToLower() == "exit") return; char[] array = new char[name.Length]; for (int i = 0; i < name.Length; i++) { array[i] = name[(name.Length - 1) - i]; } var reversedName = new string(array); Console.WriteLine(string.Format("The reversed name of {0} is {1}", name, reversedName)); } } }
using Castle.DynamicProxy; namespace LinFx.Extensions.DynamicProxy; /// <summary> /// 异步拦截器 /// </summary> /// <typeparam name="TInterceptor"></typeparam> public class AsyncDeterminationInterceptor<TInterceptor> : AsyncDeterminationInterceptor where TInterceptor : IInterceptor { public AsyncDeterminationInterceptor(TInterceptor anterceptor) : base(new CastleAsyncInterceptorAdapter<TInterceptor>(anterceptor)) { } }