content
stringlengths
23
1.05M
using System; using System.Collections.Generic; namespace Supercode.Core.ErrorDetails { public record ErrorDetails( string Name, FormattableString? PrincipalMessage, string? Code, string? Source) { public ICollection<ErrorMessage> SecondaryMessages { get; init; } = new List<ErrorMessage>(); public ICollection<ErrorDetails> InnerErrors { get; init; } = new List<ErrorDetails>(); } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NhInterMySQL; using NhInterMySQL.Model; using System; using System.Collections.Generic; using System.Linq; using NhInterMySQL.Manager; using TLJCommon; using TLJ_MySqlService.Utils; namespace TLJ_MySqlService.Handler { [Handler(Consts.Tag_BindTuiGuangCode)] class BindExtendCodeHandler : BaseHandler { public override string OnResponse(string data) { BindExtendCode bindExtendCode = null; try { bindExtendCode = JsonConvert.DeserializeObject<BindExtendCode>(data); } catch (Exception e) { MySqlService.log.Warn("传入的参数有误:" + e); return null; } string _tag = bindExtendCode.tag; int _connId = bindExtendCode.connId; string code = bindExtendCode.tuiguangcode; string uid = bindExtendCode.uid; if (string.IsNullOrWhiteSpace(_tag) || string.IsNullOrWhiteSpace(uid) || string.IsNullOrWhiteSpace(code)) { MySqlService.log.Warn("字段有空:" + data); return null; } //传给客户端的数据 JObject _responseData = new JObject(); _responseData.Add(MyCommon.TAG, _tag); _responseData.Add(MyCommon.CONNID, _connId); BindCode(uid, code, _responseData); return _responseData.ToString(); } private void BindCode(string uid, string code, JObject responseData) { UserInfo userInfo = MySqlManager<UserInfo>.Instance.GetUserInfoByCode(code); if (userInfo == null) { OperatorFail(responseData, "该推广码不存在"); } else { UserExtend userExtend = MySqlManager<UserExtend>.Instance.GetByUid(uid); if (userExtend != null) { OperatorFail(responseData, "您已绑定推广码"); } else { if (userInfo.Uid == uid) { OperatorFail(responseData, "不能绑定自己的推广码"); return; } userExtend = new UserExtend() { Uid = uid, extend_uid = userInfo.Uid, task1 = 1, task2 = 1 }; if (MySqlManager<UserExtend>.Instance.Add(userExtend)) { responseData.Add("reward", "121:1"); MySqlUtil.AddProp(uid, "121:1", "绑定推广码奖励"); OperatorSuccess(responseData, "绑定成功"); } else { OperatorFail(responseData, "添加数据失败"); } } } } private void OperatorSuccess(JObject responseData,string msg) { responseData.Add(MyCommon.CODE, (int)Consts.Code.Code_OK); responseData.Add("msg", msg); } //数据库操作失败 private void OperatorFail(JObject responseData,string msg) { responseData.Add(MyCommon.CODE, (int) Consts.Code.Code_CommonFail); responseData.Add("msg", msg); } } }
using System; using System.Collections.Generic; using System.Text; namespace Gov.Entity { /// <summary> /// 产品目录 /// </summary> public class ProductCatalog : Catalog { public List<Product> Products { get; set; } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.SCIM { using System.Collections.Generic; using System.Runtime.Serialization; [DataContract] public sealed class ExtensionAttributeWindowsAzureActiveDirectoryGroup { [DataMember(Name = AttributeNames.ElectronicMailAddresses)] public IEnumerable<ElectronicMailAddress> ElectronicMailAddresses { get; set; } [DataMember(Name = AttributeNames.ExternalIdentifier)] public string ExternalIdentifier { get; set; } [DataMember(Name = AttributeNames.MailEnabled, IsRequired = false)] public bool MailEnabled { get; set; } [DataMember(Name = AttributeNames.SecurityEnabled, IsRequired = false)] public bool SecurityEnabled { get; set; } } }
using System; using UnityEngine; namespace LDtkUnity { public class LDtkParsedBool : ILDtkValueParser { bool ILDtkValueParser.TypeName(FieldInstance instance) => instance.IsBool; public object ImportString(object input) { //bool can never be null but just in case if (input == null) { Debug.LogWarning("LDtk: Bool field was unexpectedly null"); return false; } return Convert.ToBoolean(input); } } }
using System; public class StartUp { public static void Main() { var pizzaName = Console.ReadLine().Split(); try { MakePizza(pizzaName); } catch (Exception ex) { Console.WriteLine(ex.Message); } } public static void MakePizza(string[] tokens) { int numberOfToppings = 0; var pizza = new Pizza(tokens[1]); tokens = Console.ReadLine().Split(); while (tokens[0] != "END") { if (tokens[0] == "Dough") { var dough = new Dough(tokens[1], tokens[2], double.Parse(tokens[3])); pizza.Dough = dough; } else { var topping = new Topping(tokens[1], double.Parse(tokens[2])); pizza.AddTopping(topping); numberOfToppings++; } tokens = Console.ReadLine().Split(); } pizza.NumberOfToppings = numberOfToppings; Console.WriteLine($"{pizza.Name} - {pizza.GetCalories():f2} Calories."); } }
using Microsoft.Extensions.DependencyInjection; using Quartz; using Quartz.Spi; using System; using System.Threading.Tasks; namespace QuartzHostedServices { public class ScopedJobFactory : IJobFactory { private readonly IServiceProvider _rootServiceProvider; public ScopedJobFactory(IServiceProvider rootServiceProvider) { _rootServiceProvider = rootServiceProvider ?? throw new ArgumentNullException(nameof(rootServiceProvider)); } public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) { var jobType = bundle.JobDetail.JobType; // MA - Generate a scope for the job, this allows the job to be registered // using .AddScoped<T>() which means we can use scoped dependencies // e.g. database contexts var scope = _rootServiceProvider.CreateScope(); var job = (IJob)scope.ServiceProvider.GetRequiredService(jobType); return new ScopedJob(scope, job); } public void ReturnJob(IJob job) { (job as IDisposable)?.Dispose(); } private class ScopedJob : IJob, IDisposable { private readonly IServiceScope _scope; private readonly IJob _innerJob; public ScopedJob(IServiceScope scope, IJob innerJob) { _scope = scope; _innerJob = innerJob; } public Task Execute(IJobExecutionContext context) => _innerJob.Execute(context); public void Dispose() { (_innerJob as IDisposable)?.Dispose(); _scope.Dispose(); } } } }
using System.Diagnostics; using System.Text.Json; namespace Cloud_ShareSync.Core.CloudProvider.BackBlaze { internal partial class B2 { // All Paths are relative to the bucket root. private string CleanUploadPath( string uploadFilePath, bool json ) { using Activity? activity = _source.StartActivity( "CleanUploadPath" )?.Start( ); string uploadpath = uploadFilePath .Replace( "\\", "/" ) .TrimStart( '/' ); string cleanUri = ""; if (json) { cleanUri = JsonSerializer .Serialize( uploadpath, new JsonSerializerOptions( ) ) .Replace( "\\u0022", null ) .Replace( "\"", null ) .Replace( "\u0022", null ); } else { List<char> dontEscape = new( ); dontEscape.AddRange( "._-/~!$'()*;=:@ ".ToCharArray( ) ); dontEscape.AddRange( "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray( ) ); dontEscape.AddRange( "abcdefghijklmnopqrstuvwxyz".ToCharArray( ) ); dontEscape.AddRange( "0123456789".ToCharArray( ) ); foreach (char c in uploadpath.ToCharArray( )) { cleanUri += dontEscape.Contains( c ) ? c : Uri.HexEscape( c ); } cleanUri = cleanUri.Replace( ' ', '+' ); } cleanUri = cleanUri.TrimEnd( '/' ); activity?.Stop( ); return cleanUri; } } }
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Running; using FastBFF.HTTP.Client; using FastBFF.HTTP.Server; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.Threading.Tasks; namespace FastBFF.Benchmarks { [MemoryDiagnoser] public class FastBFFBenchmarks { private readonly FastBFFClient _client; private IHost _host; public FastBFFBenchmarks() { _client = new FastBFFClient("http://localhost:5000", 3); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureLogging(config => { config.ClearProviders(); }); webBuilder.UseStartup<Startup>(); }); [Benchmark(Baseline = true, OperationsPerInvoke = FastBFFClient.OperationsPerInvoke)] public Task GetJsonNetClass() => _client.GetJsonNetClass(); [Benchmark(OperationsPerInvoke = FastBFFClient.OperationsPerInvoke)] public Task GetSystemTextJsonClass() => _client.GetSystemTextJsonClass(); [Benchmark(OperationsPerInvoke = FastBFFClient.OperationsPerInvoke)] public Task GetJsonNetStruct() => _client.GetJsonNetStruct(); [Benchmark(OperationsPerInvoke = FastBFFClient.OperationsPerInvoke)] public Task WriteToResponseBody() => _client.WriteToResponseBody(); [Benchmark(OperationsPerInvoke = FastBFFClient.OperationsPerInvoke)] public Task WriteToBodyWriter() => _client.WriteToBodyWriter(); [Benchmark(OperationsPerInvoke = FastBFFClient.OperationsPerInvoke)] public Task RawGetJsonNetClass() => _client.RawGetJsonNetClass(); [Benchmark(OperationsPerInvoke = FastBFFClient.OperationsPerInvoke)] public Task RawGetSystemTextJsonClass() => _client.RawGetSystemTextJsonClass(); [Benchmark(OperationsPerInvoke = FastBFFClient.OperationsPerInvoke)] public Task RawGetJsonNetStruct() => _client.RawGetJsonNetStruct(); [Benchmark(OperationsPerInvoke = FastBFFClient.OperationsPerInvoke)] public Task RawWriteToResponseBody() => _client.RawWriteToResponseBody(); [Benchmark(OperationsPerInvoke = FastBFFClient.OperationsPerInvoke)] public Task RawWriteToBodyWriter() => _client.RawWriteToBodyWriter(); [GlobalSetup] public void IterationSetup() { _host = CreateHostBuilder(new string[0]).Build(); Task.Run(async () => await _host.StartAsync()).Wait(); } [GlobalCleanup] public void IterationCleanup() { Task.Run(async () => await _host.StopAsync()).Wait(); _host.Dispose(); } } public class Program { public static async Task Main(string[] args) { await Task.Delay(1); #if DEBUG //Debug Only var bench = new FastBFFBenchmarks(); bench.IterationSetup(); await bench.GetJsonNetClass(); await bench.GetJsonNetStruct(); await bench.GetSystemTextJsonClass(); await bench.WriteToResponseBody(); await bench.WriteToBodyWriter(); bench.IterationCleanup(); #else BenchmarkSwitcher.FromAssemblies(new[] { typeof(Program).Assembly }).Run(args); #endif } } }
using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.DurableTask; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using System; using System.Net.Http; using System.Threading.Tasks; namespace ADPControl { public static class HttpSurface { public class ExportRequest { public Guid SubscriptionId { get; set; } public string ResourceGroupName { get; set; } public string SourceSqlServerResourceGroupName { get; set; } public string SourceSqlServerName { get; set; } public string BatchAccountUrl { get; set; } public string StorageAccountName { get; set; } public string AccessToken { get; set; } public string VNetSubnetId { get; set; } } public class ImportRequest { public Guid SubscriptionId { get; set; } public string ResourceGroupName { get; set; } public string TargetSqlServerResourceGroupName { get; set; } public string TargetSqlServerName { get; set; } public string TargetAccessToken { get; set; } public string BatchAccountUrl { get; set; } public string StorageAccountName { get; set; } public string ContainerName { get; set; } public string SqlAdminPassword { get; set; } public string VNetSubnetId { get; set; } } [FunctionName("Export")] public static async Task<HttpResponseMessage> PostExport( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Export")] HttpRequestMessage req, [DurableClient] IDurableOrchestrationClient starter, ILogger log, Guid subscriptionId, string resourceGroupName) { log.LogInformation("C# HTTP trigger function processed an Export request."); ExportRequest request = await req.Content.ReadAsAsync<ExportRequest>(); request.SubscriptionId = subscriptionId; request.ResourceGroupName = resourceGroupName; if (request.SourceSqlServerResourceGroupName == null) request.SourceSqlServerResourceGroupName = resourceGroupName; string instanceId = await starter.StartNewAsync(nameof(Orchestrator.RunExportOrchestrator), request); log.LogInformation($"Started orchestration with ID = '{instanceId}'."); return starter.CreateCheckStatusResponse(req, instanceId); } [FunctionName("Import")] public static async Task<HttpResponseMessage> PostImport( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Import")] HttpRequestMessage req, [DurableClient] IDurableOrchestrationClient starter, ILogger log, Guid subscriptionId, string resourceGroupName) { log.LogInformation("C# HTTP trigger function processed an Import request."); ImportRequest request = await req.Content.ReadAsAsync<ImportRequest>(); request.SubscriptionId = subscriptionId; request.ResourceGroupName = resourceGroupName; if (request.TargetSqlServerResourceGroupName == null) request.TargetSqlServerResourceGroupName = resourceGroupName; string instanceId = await starter.StartNewAsync(nameof(Orchestrator.RunImportOrchestrator), request); log.LogInformation($"Started orchestration with ID = '{instanceId}'."); return starter.CreateCheckStatusResponse(req, instanceId); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using Installer; namespace UnitTests.Installer { [TestFixture] public class ShellExtensionLoaderTests { [Test] public void CanLoad() { var unloaded_server = new MyShellExtension(); Assert.That(unloaded_server.AssemblyVersion, Is.Null); Assert.That(unloaded_server.AssemblyFullName, Is.Null); Assert.That(unloaded_server.RuntimeVersion, Is.Null); Assert.That(unloaded_server.CodeBaseValue, Is.Null); var server = ShellExtensionLoader.LoadServer<MyShellExtension>(@"LxfHandler.dll"); Assert.That(server.AssemblyVersion, Is.Not.Null); Assert.That(server.AssemblyFullName, Is.Not.Null); Assert.That(server.RuntimeVersion, Is.Not.Null); Assert.That(server.CodeBaseValue, Is.Not.Null); } } }
// 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.Dnx.Runtime.Common.CommandLine; namespace Microsoft.Dnx.Tooling { internal static class ClearCacheConsoleCommand { public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory) { cmdApp.Command("clear-http-cache", c => { c.Description = "Clears the package cache."; c.HelpOption("-?|-h|--help"); c.OnExecute(() => { var command = new ClearCacheCommand( reportsFactory.CreateReports(quiet: false), DnuEnvironment.GetFolderPath(DnuFolderPath.HttpCacheDirectory)); return command.Execute(); }); }); } } }
using System; using System.Diagnostics; using System.Windows.Forms; namespace ProjectsTM.UI.Main { public partial class RsExportSelectForm : Form { public bool allPeriod => radioAll.Checked; public string selectGetsudo => textSelectGetsudo.Text; public RsExportSelectForm() { InitializeComponent(); } private void OK_Click(object sender, EventArgs e) { if (!CheckRadio()) return; DialogResult = DialogResult.OK; Close(); } private bool CheckRadio() { if (radioAll.Checked == true) { return true; } else if (radioSelect.Checked == true) { var from = textSelectGetsudo.Text; if (string.IsNullOrEmpty(from)) return false; return true; } else { Debug.Assert(false); return false; } } private void Cancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } } }
using ComputerFunda.ProgrammingProblem.Array; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputerFunda.DataStructure.Test.ArrayList { [TestCategory("Array")] [TestClass] public class ArrayRotationV1Test { [TestMethod] public void TestLeftRotation_RotationLessThanSize() { int[] intput = new int[] { 1, 2, 3, 4, 5 }; int operations = 2; int[] expected = new int[] { 3, 4, 5, 1, 2 }; int[] actual = ArrayRotationV1.LeftRotation(intput, operations); CollectionAssert.AreEqual(expected, actual); } [TestMethod] public void TestLeftRotation_SizeLessThanRotation() { int[] intput = new int[] { 1, 2, 3, 4, 5 }; int operations = 6; int[] expected = new int[] { 2, 3, 4, 5, 1 }; int[] actual = ArrayRotationV1.LeftRotation(intput, operations); CollectionAssert.AreEqual(expected, actual); } [TestMethod] public void TestMinimumBribes_CorrectSwaps() { int[] intput = new int[] { 1, 2, 5, 3, 7, 8, 6, 4 }; string expected = "7"; string actual = ArrayRotationV1.MinimumBribes(intput); Assert.AreEqual(expected, actual); } [TestMethod] public void TestMinimumBribes_WrongSwaps() { int[] intput = new int[] { 2, 5, 1, 3, 4 }; string expected = "Too chaotic"; string actual = ArrayRotationV1.MinimumBribes(intput); Assert.AreEqual(expected, actual); } } }
using System; using System.Collections.Generic; namespace MsdnDataIntegrationPatterns.DataIntegration.Entities { public class OrderEntity : Entity { public string OrderNumber { get; set; } public Guid CustomerId { get; set; } public DateTime CreatedOn { get; set; } public decimal TotalAmount { get; set; } public ICollection<OrderItemEntity> Items { get; set; } } }
namespace Stravaig.FamilyTreeGenerator.Requests { public class InitFileSystem : Request { } }
using Insight.Shared; namespace Insight { public interface IProject { string Cache { get; } IFilter DisplayFilter { get; set; } string SourceControlDirectory { get; set; } bool IsDefault { get; } bool IsValid(); void Load(string path); ISourceControlProvider CreateProvider(); } }
namespace Dynamic.Data { using MongoDB.Driver; public class Context { private string connectionString; private string databaseName; private string defaultCollectionName; private readonly IMongoClient client; private readonly IMongoDatabase database; public IMongoClient Client { get { return client; } } public IMongoDatabase Database { get { return database; } } public string DefaultCollectionName { get { return defaultCollectionName; } } public Context(string connectionString, string databaseName, string defaultCollectionName) { this.connectionString = connectionString; this.databaseName = databaseName; this.defaultCollectionName = defaultCollectionName; client = new MongoClient(connectionString); database = client.GetDatabase(databaseName); } } }
// Copyright (c) Daniel Crenna & Contributors. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Reflection; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; using TypeKitchen.Benchmarks.ObjectExecution; using TypeKitchen.Tests.Fakes; namespace TypeKitchen.Benchmarks.Scenarios { [SimpleJob(RuntimeMoniker.NetCoreApp31)] [MemoryDiagnoser] [DisassemblyDiagnoser(exportDiff: true)] [CsvMeasurementsExporter] [RPlotExporter] public class CallAccessorBenchmarks { private IMethodCallAccessor _accessor; private IMethodCallAccessor _direct; private ObjectMethodExecutor _executor; private Func<object, object[], object> _lateBound; private object[] _noArgs; private ClassWithTwoMethodsAndProperty _target; [GlobalSetup] public void GlobalSetup() { var method = typeof(ClassWithTwoMethodsAndProperty).GetMethod(nameof(ClassWithTwoMethodsAndProperty.Foo)); _target = new ClassWithTwoMethodsAndProperty(); _executor = ObjectMethodExecutor.Create ( method, typeof(ClassWithTwoMethodsAndProperty).GetTypeInfo() ); _direct = new DirectCallAccessor(); _noArgs = new object[] { }; _accessor = CallAccessor.Create(method); _lateBound = LateBinding.DynamicMethodBindCall(method); } [Benchmark(Baseline = false)] public void ObjectMethodExecutor_Void_NoArgs() { _executor.Execute(_target, _noArgs); } [Benchmark(Baseline = false)] public void CallAccessor_Void_NoArgs() { _accessor.Call(_target); } [Benchmark(Baseline = false)] public void LateBound_Void_NoArgs() { _lateBound(_target, null); } [Benchmark(Baseline = true)] public void Direct_Void_NoArgs() { _direct.Call(_target); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using GeneXus.Application; using GeneXus.Notifications.ProgressIndicator; namespace GeneXus.Notifications { public class GXWebProgressIndicator { private static string ID = "GX_PROGRESS_BAR"; private GXWebNotification notification; private GXWebProgressIndicatorInfo info; private bool running; public GXWebProgressIndicator(IGxContext gxContext) { notification = new GXWebNotification(gxContext); info = new GXWebProgressIndicatorInfo(); } public void Show() { running = true; info.Action = "0"; UpdateProgress(); } private void UpdateProgress() { if (running) { GXWebNotificationInfo notif = new GXWebNotificationInfo(); notif.Id = GXWebProgressIndicator.ID; notif.GroupName = GXWebProgressIndicator.ID; notif.Message = info; notification.Notify(notif); } } public void ShowWithTitle(string title) { running = true; Title = title; info.Action = "1"; UpdateProgress(); } public void ShowWithTitleAndDescription(string title, string desc) { running = true; Title = title; Description = desc; info.Action = "2"; UpdateProgress(); } public void Hide() { info.Action = "3"; UpdateProgress(); running = false; } public string Class { get { return info.Class; } set { info.Class = value; UpdateProgress(); } } public string Title { get { return info.Title; } set { info.Title = value; UpdateProgress(); } } public string Description { get { return info.Description; } set { info.Description = value; UpdateProgress(); } } public short Type { get { return info.Type; } set { info.Type = value; } } public int Value { get { return info.Value; } set { info.Value = value; UpdateProgress(); } } public int MaxValue { get { return info.MaxValue; } set { info.MaxValue = value; } } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class QuestUI : MonoBehaviour { private InputManager playerInput; public static QuestUI questUI; public GameObject questPanel; public List<Quest> activeQuests = new List<Quest>(); private List<GameObject> qButtons=new List<GameObject>(); public GameObject qButton; public Transform qButtonSpacer; //quest info public Text questTitle; public Text questDescription; /*protected virtual void OnValidate() { GetComponentsInChildren<QuestButton>(includeInactive: true, result: qButtons); }*/ protected void RenewButton() { for(int i = 0; i < qButtons.Count; i++) { //qButtons[i] } } void Awake() { if (questUI == null) { questUI = this; }else if (questUI != this) { Destroy(gameObject); } } void Start () { playerInput = GameManager.Instance.InputManager; activeQuests = QuestManager.questManager.currentQuestList; } void Update () { if (playerInput.questPanelShow && playerInput.OpenQuestPanel) { ShowQuestPanel(); }else if (!playerInput.questPanelShow && playerInput.OpenQuestPanel) { HideQuestPanel(); } } public void ShowQuestPanel() { FillQuestButton(); questPanel.SetActive(true); } public void HideQuestPanel() { questTitle.text = ""; questDescription.text = ""; questPanel.SetActive(false); //activeQuests.Clear(); /*for (int i = 0; i < qButtons.Count; i++) { Destroy(qButtons[i]); }*/ if(qButtonSpacer.childCount > 0) { foreach (Transform t in qButtonSpacer) { Destroy(t.gameObject); } } qButtons.Clear(); } void FillQuestButton() { foreach(Quest activeQuest in activeQuests) { GameObject qusetButton = Instantiate(qButton); QuestButton qButtonScript = qusetButton.GetComponent<QuestButton>(); qButtonScript.questID = activeQuest.id; qButtonScript.questTitle.text = activeQuest.title; qusetButton.transform.SetParent(qButtonSpacer, false); qButtons.Add(qusetButton); } } public void ShowSelectedQuest(int questID) { for(int i=0; i < activeQuests.Count; i++) { if (activeQuests[i].id == questID && activeQuests[i].progress == Quest.QuestProgress.accepted) { //questTitle.text = activeQuests[i].title; questDescription.text = activeQuests[i].description; } } } }
namespace AdminLteMvc.Migrations { using System; using System.Data.Entity.Migrations; public partial class TransactionDetails23 : DbMigration { public override void Up() { AddColumn("dbo.TransactionDetails", "consignee6", c => c.String()); AddColumn("dbo.TransactionDetails", "consignee7", c => c.String()); AddColumn("dbo.TransactionDetails", "consignee8", c => c.String()); AddColumn("dbo.TransactionDetails", "consignee9", c => c.String()); AddColumn("dbo.TransactionDetails", "consignee10", c => c.String()); AddColumn("dbo.TransactionDetails", "consigneeAdd6", c => c.String()); AddColumn("dbo.TransactionDetails", "consigneeAdd7", c => c.String()); AddColumn("dbo.TransactionDetails", "consigneeAdd8", c => c.String()); AddColumn("dbo.TransactionDetails", "consigneeAdd9", c => c.String()); AddColumn("dbo.TransactionDetails", "consigneeAdd10", c => c.String()); AddColumn("dbo.TransactionDetails", "consigneetelno6", c => c.String()); AddColumn("dbo.TransactionDetails", "consigneetelno7", c => c.String()); AddColumn("dbo.TransactionDetails", "consigneetelno8", c => c.String()); AddColumn("dbo.TransactionDetails", "consigneetelno9", c => c.String()); AddColumn("dbo.TransactionDetails", "consigneetelno10", c => c.String()); } public override void Down() { DropColumn("dbo.TransactionDetails", "consigneetelno10"); DropColumn("dbo.TransactionDetails", "consigneetelno9"); DropColumn("dbo.TransactionDetails", "consigneetelno8"); DropColumn("dbo.TransactionDetails", "consigneetelno7"); DropColumn("dbo.TransactionDetails", "consigneetelno6"); DropColumn("dbo.TransactionDetails", "consigneeAdd10"); DropColumn("dbo.TransactionDetails", "consigneeAdd9"); DropColumn("dbo.TransactionDetails", "consigneeAdd8"); DropColumn("dbo.TransactionDetails", "consigneeAdd7"); DropColumn("dbo.TransactionDetails", "consigneeAdd6"); DropColumn("dbo.TransactionDetails", "consignee10"); DropColumn("dbo.TransactionDetails", "consignee9"); DropColumn("dbo.TransactionDetails", "consignee8"); DropColumn("dbo.TransactionDetails", "consignee7"); DropColumn("dbo.TransactionDetails", "consignee6"); } } }
using System.Numerics; using System.Runtime.Intrinsics.X86; namespace IntrinsicsPlayground { public static unsafe partial class MatrixIntrinsics { public static Matrix4x4 Negate_Avx(Matrix4x4 matrix) { float* matrixPtr = &matrix.M11; var row12 = Avx.LoadVector256(matrixPtr + 0); var row34 = Avx.LoadVector256(matrixPtr + 8); var zeroVec = Avx.SetZeroVector256<float>(); Avx.Store(matrixPtr + 0, Avx.Subtract(zeroVec, row12)); // or _mm_xor_ps -0.0 ? Avx.Store(matrixPtr + 8, Avx.Subtract(zeroVec, row34)); return matrix; } } }
using Microsoft.Owin; using Microsoft.Owin.Host.SystemWeb; using Microsoft.Owin.Security.OpenIdConnect; using Owin; [assembly: OwinStartup(typeof(OwinApp.Startup))] namespace OwinApp { #region snippet public class Startup { public void Configuration(IAppBuilder app) { app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { // … Your preexisting options … CookieManager = new SameSiteCookieManager( new SystemWebCookieManager()) }); // Remaining code removed for brevity. #endregion app.Run(context => { context.Response.ContentType = "text/plain"; return context.Response.WriteAsync("Hello, world."); }); } } } // Install-Package Microsoft.Owin.Security.OpenIdConnect -Version 4.1.0
using LinqToLdap.Mapping; using LinqToLdap.QueryCommands; using LinqToLdap.QueryCommands.Options; namespace LinqToLdap.Tests.TestSupport { public class MockQueryCommandFactory : IQueryCommandFactory { public QueryCommandType Type { get; set; } public IQueryCommandOptions Options { get; set; } public IObjectMapping Mapping { get; set; } public IQueryCommand QueryCommandToReturn { get; set; } public IQueryCommand GetCommand(QueryCommandType type, IQueryCommandOptions options, IObjectMapping mapping) { Type = type; Options = options; Mapping = mapping; return QueryCommandToReturn; } public string Filter { get { return Options != null ? Options.Filter : null; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using Telerik.Core; using Telerik.Data.Core; using Telerik.Data.Core.Layouts; using Telerik.UI.Xaml.Controls.Grid; namespace Telerik.UI.Xaml.Controls.Grid { internal class DecorationsController { private Dictionary<int, LineDecorationModel> displayedRowDecorationsMap; private Dictionary<int, LineDecorationModel> displayedColumnDecorationsMap; private DecorationPool<LineDecorationModel> rowLinesElementsPool; private DecorationPool<LineDecorationModel> columnLinesElementsPool; private IDecorationPresenter<LineDecorationModel> decorationPresenter; public DecorationsController(IDecorationPresenter<LineDecorationModel> decoratorPresenter) { this.decorationPresenter = decoratorPresenter; this.rowLinesElementsPool = new DecorationPool<LineDecorationModel>(decoratorPresenter); this.columnLinesElementsPool = new DecorationPool<LineDecorationModel>(decoratorPresenter); this.displayedRowDecorationsMap = new Dictionary<int, LineDecorationModel>(); this.displayedColumnDecorationsMap = new Dictionary<int, LineDecorationModel>(); } /// <summary> /// Gets displayed row decorations map. Exposed for testing purposes. /// </summary> internal Dictionary<int, LineDecorationModel> DisplayedRowDecorationsMap { get { return this.displayedRowDecorationsMap; } } /// <summary> /// Gets displayed column decorations map. Exposed for testing purposes. /// </summary> internal Dictionary<int, LineDecorationModel> DisplayedColumnDecorationsMap { get { return this.displayedColumnDecorationsMap; } } internal void Arrange(ArrangeDataForDecorations horizontalArrangement, ArrangeDataForDecorations verticalArrangement) { this.ArrangeRowDecorations(horizontalArrangement, verticalArrangement); this.ArrangeColumnDecorations(horizontalArrangement, verticalArrangement); this.rowLinesElementsPool.FullyRecycleElements(); this.columnLinesElementsPool.FullyRecycleElements(); } internal void Update(UpdateFlags flags) { if ((flags & UpdateFlags.AffectsDecorations) == UpdateFlags.AffectsDecorations) { this.RecycleAllDecorators(); } } internal void RecycleColumnDecorators(int slot) { RecycleDecorator(slot, this.columnLinesElementsPool, this.displayedColumnDecorationsMap); } internal void RecycleRowDecorators(int slot) { RecycleDecorator(slot, this.rowLinesElementsPool, this.displayedRowDecorationsMap); } internal void RecycleRowDecoratorBefore(int line) { foreach (var item in this.displayedRowDecorationsMap.ToList()) { if (item.Key < line) { this.RecycleRowDecorator(item.Key); } } } internal void RecycleRowDecoratorAfter(int line) { foreach (var item in this.displayedRowDecorationsMap.ToList()) { if (item.Key > line) { this.RecycleRowDecorator(item.Key); } } } internal void RecycleAllRowDecorators() { foreach (var item in this.displayedRowDecorationsMap.ToList()) { this.RecycleRowDecorator(item.Key); } } internal void RecycleColumnDecoratorBefore(int line) { foreach (var item in this.displayedColumnDecorationsMap.ToList()) { if (item.Key < line) { this.RecycleColumnDecorator(item.Key); } } } internal void RecycleColumnDecoratorAfter(int line) { foreach (var item in this.displayedColumnDecorationsMap.ToList()) { if (item.Key > line) { this.RecycleColumnDecorator(item.Key); } } } internal void RecycleColumnDecoratorBetween(int startLine, int endLine) { foreach (var item in this.displayedColumnDecorationsMap.ToList()) { if (startLine < item.Key && item.Key < endLine) { this.RecycleColumnDecorator(item.Key); } } } internal void RecycleAllColumnDecorators() { foreach (var item in this.displayedColumnDecorationsMap.ToList()) { this.RecycleColumnDecorator(item.Key); } } internal void GenerateRowDecorators(IEnumerable<ItemInfo> displayedRowInfos) { // Generate row decorators foreach (var itemInfo in displayedRowInfos) { this.GenerateRowDecorator(itemInfo); } } internal void GenerateColumnDecorators(IEnumerable<ItemInfo> displayedColumnInfos) { // Generate column decorators foreach (var itemInfos in displayedColumnInfos) { this.GenerateColumnDecorator(itemInfos); } } private static void RecycleDecorator(int id, DecorationPool<LineDecorationModel> displayData, Dictionary<int, LineDecorationModel> decorators) { LineDecorationModel decorator; if (decorators.TryGetValue(id, out decorator)) { displayData.Recycle(decorator); decorators.Remove(id); } } private static void GenerateDecorator(int id, ItemInfo itemInfo, DecorationType decoratorElementType, DecorationPool<LineDecorationModel> decorationPool, Dictionary<int, LineDecorationModel> decorators, IDecorationPresenter<LineDecorationModel> owner) { LineDecorationModel decorator = null; if (owner != null && !decorators.TryGetValue(id, out decorator)) { decorator = CreateDecorator(itemInfo, decoratorElementType, decorationPool, owner); decorators.Add(id, decorator); } else if (owner != null) { decorator.ItemInfo = itemInfo; owner.ApplyDecoratorProperties(decorator, decoratorElementType); } } private static LineDecorationModel CreateDecorator(ItemInfo itemInfo, DecorationType decoratorElementType, DecorationPool<LineDecorationModel> displayData, IDecorationPresenter<LineDecorationModel> owner) { if (owner == null) { return null; } var lineDecorator = displayData.GetRecycledElement(); if (lineDecorator == null) { lineDecorator = new LineDecorationModel(); lineDecorator.Container = owner.GenerateContainerForDecorator(); } lineDecorator.ItemInfo = itemInfo; owner.ApplyDecoratorProperties(lineDecorator, decoratorElementType); displayData.AddToDisplayedElements(lineDecorator); return lineDecorator; } private static DecorationType GetDecoratorType(bool isRow) { return isRow ? DecorationType.Row : DecorationType.Column; } private void RecycleRowDecorator(int line) { RecycleDecorator(line, this.rowLinesElementsPool, this.displayedRowDecorationsMap); } private void RecycleColumnDecorator(int line) { RecycleDecorator(line, this.columnLinesElementsPool, this.displayedColumnDecorationsMap); } private void ArrangeColumnDecorations(ArrangeDataForDecorations horizontalArrangement, ArrangeDataForDecorations verticalArrangement) { double top; double bottom; double left; double right; foreach (var columnDecoratorPair in this.displayedColumnDecorationsMap) { LineDecorationModel decorator = columnDecoratorPair.Value; LayoutInfo layoutInfo = decorator.ItemInfo.LayoutInfo; top = verticalArrangement.GetStartOfLevel(layoutInfo.Level); bottom = layoutInfo.SpansThroughCells ? verticalArrangement.SlotsEnd : verticalArrangement.GetEndOfLevel(layoutInfo.Level + layoutInfo.LevelSpan - 1); left = horizontalArrangement.GetStartOfSlot(layoutInfo.Line); right = horizontalArrangement.GetEndOfSlot(layoutInfo.Line + layoutInfo.LineSpan - 1); var thickness = this.decorationPresenter.ArrangeDecorator(decorator, new RadRect(left, top, right, bottom)); } } private void ArrangeRowDecorations(ArrangeDataForDecorations horizontalArrangement, ArrangeDataForDecorations verticalArrangement) { double top; double bottom; double left; double right; foreach (var rowDecoratorPair in this.displayedRowDecorationsMap) { LineDecorationModel decorator = rowDecoratorPair.Value; LayoutInfo layoutInfo = decorator.ItemInfo.LayoutInfo; top = verticalArrangement.GetStartOfSlot(layoutInfo.Line); bottom = verticalArrangement.GetEndOfSlot(layoutInfo.Line + layoutInfo.LineSpan - 1); left = horizontalArrangement.GetStartOfLevel(layoutInfo.Level); right = layoutInfo.SpansThroughCells ? horizontalArrangement.SlotsEnd : horizontalArrangement.GetEndOfLevel(layoutInfo.Level + layoutInfo.LevelSpan - 1); var thickness = this.decorationPresenter.ArrangeDecorator(decorator, new RadRect(left, top, right, bottom)); } } private void RecycleRowDecoratorForGroup(int line) { RecycleDecorator(line, this.rowLinesElementsPool, this.displayedRowDecorationsMap); } private void RecycleColumnDecoratorForGroup(int line) { RecycleDecorator(line, this.columnLinesElementsPool, this.displayedColumnDecorationsMap); } private void GenerateRowDecorator(ItemInfo itemInfo) { var decoratorElementType = GetDecoratorType(true); bool hasDecoration = this.decorationPresenter.HasDecorations(decoratorElementType, itemInfo); if (hasDecoration) { this.GenerateRowDecoratorForGroup(itemInfo, decoratorElementType); } else { this.RecycleRowDecoratorForGroup(itemInfo.Id); } } private void GenerateColumnDecorator(ItemInfo itemInfo) { var decoratorElementType = GetDecoratorType(false); bool hasDecoration = this.decorationPresenter.HasDecorations(decoratorElementType, itemInfo); if (hasDecoration) { this.GenerateColumnDecoratorForGroup(itemInfo, decoratorElementType); } else { this.RecycleColumnDecoratorForGroup(itemInfo.Id); } } private void GenerateRowDecoratorForGroup(ItemInfo itemInfo, DecorationType decoratorElementType) { GenerateDecorator(itemInfo.Id, itemInfo, decoratorElementType, this.rowLinesElementsPool, this.displayedRowDecorationsMap, this.decorationPresenter); } private void GenerateColumnDecoratorForGroup(ItemInfo itemInfo, DecorationType decoratorElementType) { GenerateDecorator(itemInfo.Id, itemInfo, decoratorElementType, this.columnLinesElementsPool, this.displayedColumnDecorationsMap, this.decorationPresenter); } private void RecycleAllDecorators() { this.rowLinesElementsPool.RecycleAll(); this.columnLinesElementsPool.RecycleAll(); this.displayedRowDecorationsMap.Clear(); this.displayedColumnDecorationsMap.Clear(); } } }
// Copyright (c) 2005-2020, Coveo Solutions Inc. using System; using System.Diagnostics; namespace sfdx4csharpClient.Core.Attributes { /// <summary> /// Attribute used to store the cli command associated with a command's class. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class CommandClassAttribute : Attribute { private readonly string m_Value; /// <summary> /// Constructor /// </summary> /// <param name="p_Value">SFDX CLI command's namespace.</param> /// <example>For the Auth commands, the namespace should be "force:auth".</example> public CommandClassAttribute(string p_Value) { Debug.Assert(!string.IsNullOrEmpty(p_Value)); m_Value = p_Value; } /// <summary> /// Gets the attribute value on the given type. /// </summary> /// <param name="p_Type">Type with a CommandClassAttribute to get.</param> /// <returns>The attribute value.</returns> public static string GetCommandClassValue(Type p_Type) { Debug.Assert(p_Type != null); var attribute = (CommandClassAttribute)GetCustomAttribute(p_Type, typeof(CommandClassAttribute)); return attribute?.m_Value; } } }
using System; namespace Duracion { class Duracion { private int horas; private int minutos; private int segundos; public Duracion(int h, int m, int s){ horas=h; minutos=m; segundos=s; } public void imprime(){ Console.WriteLine("Horas:{0} Minutos:{1} Segundos {2}",horas, minutos, segundos); } public void Conversiones(){ minutos=(horas*60)+minutos; segundos=(horas*3600)+(minutos*60)+segundos; Console.WriteLine("El tiempo en minutos es:"+minutos); Console.WriteLine("El tiempo en segundos es:"+segundos); } public void ConverSeg(){ int hor; int min; hor=segundos/3600; min=segundos/60; Console.WriteLine("La cantidad de segundos en horas es:"+hor); Console.WriteLine("La cantidad de segundos en minutos es:"+min); } public static Duracion operator +(Duracion a, Duracion b){ int horas = a.horas+b.horas; int minutos = a.minutos+b.minutos; int segundos = a.segundos+b.segundos; return new Duracion (horas, minutos, segundos); } } class program { static void Main(string[] args) { Duracion a= new Duracion(1,15,11); Duracion b= new Duracion(0,29,37); Duracion c= a+b; a.imprime(); a.Conversiones(); a.ConverSeg(); b.imprime(); c.imprime(); } } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Another_Morrowind_Utility.FileStructure.Records; namespace Another_Morrowind_Utility.FileStructure { class ESXParser { private const int HEADER_SIZE = 16; RecordFactory factory = new RecordFactory(); int bytesRead = 0; /// <summary> /// Reads all records in a file and returns a collection of them /// </summary> /// <param name="path">File path</param> /// <returns>New collection of records</returns> public ESXFile Parse(string path) { List<Record> records = new List<Record>(); Record record; //throw new NotImplementedException(); using (FileStream fs = File.OpenRead(path)) { while ((record = ReadRecord(fs)) != null) { records.Add(record); } } return new ESXFile(records); } /// <summary> /// Attempts to read a record from file, /// returns null upon reaching end of file /// </summary> /// <param name="fs">file stream to read from</param> /// <param name="offset">offset to begin from</param> /// <returns>A new record or null</returns> public Record ReadRecord(FileStream fs) { byte[] rawHeader = new byte[HEADER_SIZE]; int count = fs.Read(rawHeader, 0, HEADER_SIZE); if (count == 0) return null; else if (count < 16) throw new FormatException("Unexpected file size."); bytesRead += count; RecordHeader header = new RecordHeader(rawHeader); byte[] data = new byte[header.Size]; count = fs.Read(data, 0, header.Size); if (count < header.Size) throw new Exception("Unexpected file size."); bytesRead += count; return factory.ConstructRecord(header, data); } private List<Subrecord> ParseSubrecords(byte[] data) { List<Subrecord> subrecords = new List<Subrecord>(); string type; int size; int offset = 0; int count = data.Length; byte[] subrecordData; while (count > 0) { if (count < 8) throw new FormatException("Unexpected file size."); type = Encoding.ASCII.GetString(data, offset, 4); count -= 4; offset += 4; size = BitConverter.ToInt32(data, offset); count -= 4; offset += 4; subrecordData = new byte[size]; Array.Copy(data, offset, subrecordData, 0, size); count -= size; offset += size; subrecords.Add(new Subrecord(type, size, subrecordData)); } return subrecords; } /// <summary> /// Constructs a new RecordHeader from raw data /// </summary> /// <param name="rawHeader">16 bytes of header data</param> /// <returns>New RecordHeader</returns> /*private RecordHeader ConstructHeader(byte[] rawHeader) { string type = Encoding.ASCII.GetString(rawHeader, 0, 4); int size = BitConverter.ToInt32(rawHeader, 4); int unknown = BitConverter.ToInt32(rawHeader, 8); int flags = BitConverter.ToInt32(rawHeader, 12); return new RecordHeader(rawHeader, map.StringToRecType(type), size, unknown, flags); } */ } }
namespace GraphQL.AspNetCore3.WebSockets; /// <summary> /// Processes a stream of messages received from a WebSockets client. /// <see cref="IDisposable.Dispose"/> must be called when the connection terminates. /// Methods defined within this interface need not be thread-safe. /// </summary> public interface IOperationMessageProcessor : IDisposable { /// <summary> /// Starts the connection initialization timer, if configured. /// </summary> Task InitializeConnectionAsync(); /// <summary> /// Called when a message is received from the client. /// </summary> Task OnMessageReceivedAsync(OperationMessage message); }
@model List<Livro> @{ ViewData["Title"] = "Listagem de Livros"; } <div class="row"> <div class="col-md-12"> <form class="form-inline" method="POST"> <div class="form-group mb-2"> <select name="TipoFiltro" class="form-control"> <option value="Autor">Autor</option> <option value="Titulo">Título</option> </select> </div> <div class="form-group mb-2 mx-sm-3"> <input type="text" placeholder="Filtro" name="Filtro" class="form-control" /> </div> <button type="submit" class="btn btn-primary mb-2">Pesquisar</button> </form> </div> </div> <div class="row" mb-2> <div class="col-md-12"> @if (@Model.Count>0){ <table class="table table-striped"> <thead> <tr><th>Id</th> <th>Titulo</th> <th>Autor</th> <th>Ano</th> <th></th> </tr> </thead> <tbody> @foreach(Livro l in Model) { <tr> <td>@l.Id</td> <td>@l.Titulo</td> <td>@l.Autor</td> <td>@l.Ano</td> <td><a href="/Livro/Edicao/@l.Id">Editar</a></td> <td><a href="/Livro/excluirCadLivros/@l.Id">Excluir</a></td> </tr> } </tbody> </table> }else{ <p>Nenhum registro encontrado</p> } </div> </div> <nav aria-label="..."> <ul class="pagination justify-content-center"> <li class="page-item disabled"> <a class="page-link">Previous</a> </li> <li class="page-item"><a class="page-link" href="#">1</a></li> <li class="page-item active" aria-current="page"> <a class="page-link" href="#">2</a> </li> <li class="page-item"><a class="page-link" href="#">3</a></li> <li class="page-item"> <a class="page-link" href="#">Next</a> </li> </ul> </nav>
using Application.Common.Interfaces; using Application.Common.Models; using Domain.Entities; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Application.PontosRisco.Commands.UpdatePontoRisco { public class UpdatePontoRiscoCommand { public string Id { get; set; } public string Descricao { get; set; } public double Latitude { get; set; } public double Longitude { get; set; } public string Pais { get; set; } public string Estado { get; set; } public string Cidade { get; set; } public string Distrito { get; set; } } public class UpdatePontoRiscoCommandHandler : IUpdatePontoRiscoCommandHandler { private readonly IApplicationDbContext _context; public UpdatePontoRiscoCommandHandler(IApplicationDbContext context) { _context = context; } public async Task<Response<string>> Handle(UpdatePontoRiscoCommand request) { var entity = _context.PontoRisco .Where(x => x.Id == request.Id) .FirstOrDefault(); if (entity != null) { try { var entityDistrito = _context.Distrito .Where(x => EF.Functions.Like(x.Nome, "%" + request.Distrito + "%")) .Where(x => EF.Functions.Like(x.Cidade.Nome, "%" + request.Cidade + "%")) .Where(x => EF.Functions.Like(x.Cidade.Estado.Nome, "%" + request.Estado + "%")) .Where(x => EF.Functions.Like(x.Cidade.Estado.Pais.Nome, "%" + request.Pais + "%")) .Include(e => e.Cidade) .Include(e => e.Cidade.Estado) .Include(e => e.Cidade.Estado.Pais) .OrderByDescending(o => o.Nome) .ToList() .FirstOrDefault(); entity.Descricao = request.Descricao; entity.Ponto = new Ponto() { Latitude = request.Latitude, Longitude = request.Longitude }; entity.Distrito = entityDistrito; _context.SaveChanges(); return new Response<string>(data: entity.Id.ToString()); } catch { return new Response<string>(message: $"erro para atualizar: ${ entity.Id }"); } } else { return new Response<string>(message: $"nenhum ${ entity.Id } foi encontrado"); } } } }
using System.Collections.Generic; using Newtonsoft.Json; using Umbraco.Core.Models; using System; namespace FormEditor.Fields { public abstract class FieldWithValue : Field { private string _formSafeName; public virtual string Name { get; set; } [JsonIgnore] public string FormSafeName { get { // use a backing field, FormSafeName will be used intensively if (_formSafeName == null) { _formSafeName = GetFormSafeName(); } return _formSafeName; } internal set => _formSafeName = value; } [JsonIgnore] public virtual string SubmittedValue { get; protected set; } public virtual bool HasSubmittedValue => string.IsNullOrEmpty(SubmittedValue) == false; protected virtual string GetFormSafeName() { return FieldHelper.FormSafeName(Name); } protected internal override void CollectSubmittedValue(Dictionary<string, string> allSubmittedValues, IPublishedContent content) { SubmittedValue = FieldHelper.GetSubmittedValue(this, allSubmittedValues); } protected internal override bool ValidateSubmittedValue(IEnumerable<Field> allCollectedValues, IPublishedContent content) { return true; } protected internal virtual string FormatSubmittedValueForIndex(IPublishedContent content, Guid rowId) { return SubmittedValue; } protected internal virtual string FormatValueForDataView(string value, IContent content, Guid rowId) { return value; } protected internal virtual string FormatValueForCsvExport(string value, IContent content, Guid rowId) { return value; } protected internal virtual string FormatValueForFrontend(string value, IPublishedContent content, Guid rowId) { return value; } public virtual string SubmittedValueForEmail() { return SubmittedValue; } public virtual bool SupportsStripHtml => true; } }
// // Copyright 2019 Google LLC // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using Google.Solutions.Common.Locator; using Google.Solutions.IapDesktop.Extensions.Activity.Logs; using Newtonsoft.Json.Linq; using System; using System.Diagnostics; namespace Google.Solutions.IapDesktop.Extensions.Activity.Events.System { public class NotifyInstanceLocationEvent : SystemEventBase { public const string Method = "NotifyInstanceLocation"; public string ServerId => base.LogRecord.ProtoPayload.Metadata["serverId"].Value<string>(); public NodeTypeLocator NodeType { get { // The node type is unqualified, e.g. "n1-node-96-624". if (base.LogRecord.ProtoPayload.Metadata.ContainsKey("nodeType") && base.LogRecord.Resource.Labels.ContainsKey("project_id") && base.LogRecord.Resource.Labels.ContainsKey("zone")) { return new NodeTypeLocator( base.LogRecord.Resource.Labels["project_id"], base.LogRecord.Resource.Labels["zone"], base.LogRecord.ProtoPayload.Metadata["nodeType"].Value<string>()); } else { return null; } } } public DateTime SchedulingTimestamp => base.LogRecord.ProtoPayload.Metadata["timestamp"].Value<DateTime>(); public override string Message => "Instance scheduled to run on sole tenant node " + this.ServerId; internal NotifyInstanceLocationEvent(LogRecord logRecord) : base(logRecord) { Debug.Assert(IsInstanceScheduledEvent(logRecord)); } public static bool IsInstanceScheduledEvent(LogRecord record) { return record.IsSystemEvent && record.ProtoPayload.MethodName == Method; } } }
using System.IO; using System.Xml; using System.Xml.Serialization; using Newtonsoft.Json; namespace CiscoListener.Helpers { public static class Serializer { public static void SaveXml<T>(string path, T config) { var x = new XmlSerializer(typeof(T)); using (var w = XmlWriter.Create(path, new XmlWriterSettings {Indent = true})) { x.Serialize(w, config); } } public static void LoadXml<T>(string path, out T config) { var x = new XmlSerializer(typeof(T)); using (var r = XmlReader.Create(path)) { config = (T)x.Deserialize(r); } } public static void SaveJson<T>(string path, T config) { File.WriteAllText(path, JsonConvert.SerializeObject(config)); } public static void LoadJson<T>(string path, out T config) { config = JsonConvert.DeserializeObject<T>(File.ReadAllText(path)); } } }
using System; using System.Collections.Generic; namespace Strings { public class StringsTest { public const string test = "test"; public string string1 = string.Format("string format"); string string2 = $"string interpolation {test}"; string string3 = $"string \"interpolation\" {test}"; string string4 = $"string {{interpolation}} {test + "x"}"; string string5 = $"string interpolation {test + "\"x\""}"; string string6 = $"string interpolation {test + $"\"x\"{"y"}"}"; string string7 = $@"Test ""literal"" with at sign"; string string8 = $@"Test {"multi"} line"; string string9 = $"Test with {$"nested interpolated {"\"strings\""}"}"; public void Method1(string item) { string1 = string.Format("string format {0}", string1); string2 = $"string interpolation {string2}"; string2 = @"This is a test of double quote """""; } public void Method2() { Method1(string.Format("string format {0}", string1)); Method1($"string interpolation {string2}"); } public void Issue14() { string argumentName = "Test"; int argIndex = 1; string[] arguments = new string[10]; arguments[0] = "Test"; arguments[1] = "Test1"; Console.WriteLine($"{argumentName}[{argIndex}] = \"{arguments[argIndex]}\""); var test = $"{argumentName}[{argIndex}] = \"{arguments[argIndex]}\""; test = @"This is a test of double quote ""test"""""""""""" "" test"; test = @"This is a test of double quote ""test"" "" test"; test = @"This is a test of double quote """""""; Console.WriteLine(@"This is a test of double quote """""""); Console.WriteLine(@"This is a test of double quote ""test"" "" test"); Console.WriteLine(@"This is a test of double quote ""test"""""""""""" "" test"); var strippedStatement = Regex.Replace("input string", @"(?<S>(^|\W+)?)Mev\.(?<E>($|\W+)?)", @"${S}${E}"); } public void InterpolationWithLiteral() { string argumentName = "Test"; int argIndex = 1; string[] arguments = new string[10]; arguments[0] = "Test"; arguments[1] = "Test1"; Console.WriteLine($@"{argumentName}[{argIndex}] = ""{arguments[argIndex]}"""); var test = $@"{argumentName}[{argIndex}] = ""{arguments[argIndex]}"""; test = $@"This is a test of double quote ""test"""""""""""" "" test"; test = $@"This is a test of double quote ""test"" "" test"; test = $@"This is a test of double quote """""""; Console.WriteLine($@"This is a test of double quote """""""); Console.WriteLine($@"This is a test of double quote ""test"" "" test"); Console.WriteLine($@"This is a test of double quote ""test"""""""""""" "" test"); } } public class StringsConstTest { public const string test = "test"; private readonly string x = string.Format("string format {0}", test); private readonly string y = $"string interpolation {test}"; var message = $"ConnectionString missing: {ConfigurationManager.AppSettings["ConnectionStringName"]}"; } public class CSSAsString { public static string GetStyle() { return @"<style> body { padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0px; padding-top: 0px; font-family: arial, helvetica, sans-serif; background-color: #cccccc; } form { padding-right: 0px; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px; } </style>"; } public static string GetStyleWithDoubleQuotes() { return @"<style> body { padding-right: 0px; padding-left: 0px; font-size: 8pt; padding-bottom: 0px; margin: 0px; padding-top: 0px; font-family: arial, helvetica, sans-serif; background-color: #cccccc; ""this is another test"" } form { padding-right: 0px; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px; } </style>"; } } public class Issue88 { var foo1 = @"c:\foo\"; var foo2 = @"c:\foo"; var foo3 = $@"{foo2}\"; // Regression check: Non-verbatim interpolated string ending with backslash var foo4 = $"{foo2}\\"; var issue192 = $"123 {@"c:\temp\"}"; } }
using Microsoft.EntityFrameworkCore.Metadata.Builders; using Newtonsoft.Json; namespace Disunity.Management.Extensions { public static class PropertyBuilderExtensions { public static PropertyBuilder<T> HasJsonConversion<T>(this PropertyBuilder<T> builder) { return builder.HasConversion( d => JsonConvert.SerializeObject(d, Formatting.None), s => JsonConvert.DeserializeObject<T>(s)); } } }
using FluentAssertions; using Xunit; using static System.Text.Json.JsonSerializer; namespace Golden.Common.Tests { public class JsonUtilsTests { [Fact] void ToJson_serializes_an_object_to_string_with_json_format() { var obj = new Fake { Id = 10, Name = "Test" }; var result = obj.ToJson(); var expectedObj = Deserialize<Fake>(result); expectedObj.Should().BeEquivalentTo(obj); } [Fact] void JsonTo_deserializes_a_json_string_to_specified_type() { var json = @"{""Id"":10,""Name"":""Sample""}"; var expectedObj = new Fake { Id = 10, Name = "Sample" }; var result = json.JsonTo<Fake>(); result.Should().BeEquivalentTo(expectedObj); } [Fact] void JsonTo_deserializes_a_specified_property_of_json_string() { var json = @"{""Id"":10,""Name"":""Sample""}"; var propertyName = "Name"; var expectedValue = "Sample"; var result = json.JsonTo<string>(propertyName); result.Should().Be(expectedValue); } [Fact] void JsonTo_deserializes_a_specified_nested_property_of_json_string() { var json = @"{""Nested"":{""Name"":""Sample""}}"; var propertyName = "Nested.Name"; var expectedValue = "Sample"; var result = json.JsonTo<string>(propertyName); result.Should().Be(expectedValue); } class Fake { public int Id { get; set; } public string Name { get; set; } public Fake Nested { get; set; } } } }
using Builder.Astralis; using Builder.Astralis.Descriptors; using Builder.Astralis.Execution; using System.IO; namespace Builder { public static class RepositoryResolver { static void ResolveRepo(Descriptor desc) { if (desc.Repositories == null) return; foreach (var repo in desc.Repositories) { switch (repo.Type.ToLower()) { case "git": Git git = new Git { Address = repo.Address, Output = Catalog.ParsePath(repo.Output) }; if (!Directory.Exists(git.Output)) git.Clone(); else if (Program.Config.Upgrade) git.Pull(); break; } } } public static void ResolveForProject(Project project) { ResolveRepo(project); ResolveRepo(project.Framework); ResolveRepo(project.Board); ResolveRepo(project.Board.Processor); ResolveRepo(project.Toolset); foreach (var drv in project.Drivers) ResolveRepo(drv.Source); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleSimPrt.PrtModel { /// <summary> /// 程序模拟初始化 /// </summary> public class PrtInit { public static EventHandlerPool eventhandlerpool = new EventHandlerPool(); public static ResourcePool PrtResourcePool = new ResourcePool(eventhandlerpool); public static Client client = new Client(PrtResourcePool); public static PrtManager prtManager = new PrtManager(PrtResourcePool, eventhandlerpool); public static void Init() { StringBuilder strbDexc = new StringBuilder(); strbDexc.AppendLine("打印机模拟程序-by JinLiwei 2016-12-31"); strbDexc.AppendLine("O------0 0------0 0--------0 0------0"); strbDexc.AppendLine("|客户端|-》|资源池|-》|打印队列|-》|打印机|"); strbDexc.AppendLine("0------0 0------0 0--------0 0------0"); Console.WriteLine(strbDexc.ToString()); Action actSacn = new Action(prtManager.Scan); Task.Run(actSacn); Action actHandle = new Action(prtManager.Handle); Task.Run(actHandle); while (true) { string str =Console.ReadLine(); Resource res = new Resource { Name = str }; client.Push(res); Console.WriteLine(PrtResourcePool); Thread.Sleep(10); } } } }
/* Copyright (C) 2004 - 2011 Versant Inc. http://www.db4o.com */ using Db4objects.Db4o.NativeQueries.Expr; using Db4objects.Db4o.NativeQueries.Expr.Cmp.Operand; namespace Db4objects.Db4o.NativeQueries.Expr { public class TraversingExpressionVisitor : IExpressionVisitor, IComparisonOperandVisitor { public virtual void Visit(AndExpression expression) { expression.Left().Accept(this); expression.Right().Accept(this); } public virtual void Visit(BoolConstExpression expression) { } public virtual void Visit(OrExpression expression) { expression.Left().Accept(this); expression.Right().Accept(this); } public virtual void Visit(ComparisonExpression expression) { expression.Left().Accept(this); expression.Right().Accept(this); } public virtual void Visit(NotExpression expression) { expression.Expr().Accept(this); } public virtual void Visit(ArithmeticExpression operand) { operand.Left().Accept(this); operand.Right().Accept(this); } public virtual void Visit(ConstValue operand) { } public virtual void Visit(FieldValue operand) { operand.Parent().Accept(this); } public virtual void Visit(CandidateFieldRoot root) { } public virtual void Visit(PredicateFieldRoot root) { } public virtual void Visit(StaticFieldRoot root) { } public virtual void Visit(ArrayAccessValue operand) { operand.Parent().Accept(this); operand.Index().Accept(this); } public virtual void Visit(MethodCallValue value) { value.Parent().Accept(this); VisitArgs(value); } protected virtual void VisitArgs(MethodCallValue value) { IComparisonOperand[] args = value.Args; for (int i = 0; i < args.Length; ++i) { args[i].Accept(this); } } } }
namespace Etch.OrchardCore.Leaflet.ViewModels { public class BuildDisplayViewModel { public dynamic DisplayShape { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net.Sockets; using System.Net.Http; using LiteNetLib; using System.Threading; using System.Net; using Newtonsoft.Json; namespace dreamscape { public partial class Hub : Form { EventBasedNetListener netListener; NetManager client; List<string> serverslist; public Hub() { netListener = new EventBasedNetListener(); client = new NetManager(netListener); InitializeComponent(); serverslist = new List<string>(); using(WebClient c = new WebClient()) { string servers = c.DownloadString("http://atari0.cf/engine/servers.php"); foreach (string i in servers.Split('|')) { ServerItem v = JsonConvert.DeserializeObject<ServerItem>(i); try { m_Games.Items.Add(v.name + " " + v.status); serverslist.Add(i); } catch (Exception) { } } } } private void M_Connect_Click(object sender, EventArgs e) { Game game = new Game(m_ipAddr.Text, 6698, m_Key.Text); game.Show(); this.Visible = false; game.FormClosing += (send, args) => { this.Visible = true; }; game.FormClosed += (send, args) => { game.Dispose(); }; } private void M_Games_SelectedValueChanged(object sender, EventArgs e) { string item = (string)m_Games.SelectedItem; foreach(string i in serverslist) { ServerItem v = JsonConvert.DeserializeObject<ServerItem>(i); if(item == v.name + " " + v.status) { m_ipAddr.Text = v.ip; } } } private void Hub_Load(object sender, EventArgs e) { } } public class ServerItem { public string name; public string ip; public string status; public ServerItem(string ip, string status, string name) { this.ip = ip; this.name = name; this.status = status; } } }
using InmobiliariaLogicLayer.Decimales; using InmobiliariaLogicLayer.Lotes; using InmobiliariaLogicLayer.Lotes.PrecioLoteDecorators; using InmobiliariaViewModels.Cuotas; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InmobiliariaLogicLayer.Cuotas { public class CuotaVenta { private PuntoDecimal punto; public CuotaVenta() { punto = new PuntoDecimal(); } public CuotaVentaViewModels CalcularDescuento(CuotaVentaViewModels datos) { var cuota = new CuotaVentaViewModels(); ILoteComponent lote = new PrecioLote(datos.cantidad); //cuota.cantidad = datos.cantidad; lote = new DescuentoLote(lote, datos.descuento, 0); cuota.descuento = lote.calcularMonto(); lote = new EngancheLote(lote, datos.enganche); cuota.enganche = lote.calcularMonto(); cuota.cantidad = lote.calcularSaldo(); lote = new InteresLote(lote, datos.interes, datos.tiempo); cuota.interes = punto.dosDecimales(lote.calcularMonto()); cuota.tiempo = datos.tiempo; cuota.cuota = (cuota.cantidad + cuota.interes)/ datos.tiempo; return cuota; } public CuotaVentaViewModels CalcularSinDescuento(CuotaVentaViewModels datos) { var cuota = new CuotaVentaViewModels(); ILoteComponent lote = new PrecioLote(datos.cantidad); //cuota.cantidad = lote.calcularMonto(); lote = new EngancheLote(lote, datos.enganche); cuota.enganche = lote.calcularMonto(); cuota.cantidad = lote.calcularSaldo(); lote = new InteresLote(lote, datos.interes, datos.tiempo); cuota.interes = punto.dosDecimales(lote.calcularMonto()); cuota.tiempo = datos.tiempo; cuota.cuota = (cuota.cantidad + cuota.interes) / datos.tiempo; return cuota; } } }
using System; using System.ComponentModel; namespace ServerGui.UserControls { /// <summary> /// Holds options for a DataGrid Column. /// </summary> [Serializable] public class ColumnOptions { public int DisplayIndex { get; set; } public double Width { get; set; } public ListSortDirection? SortDirection { get; set; } } }
using UnityEngine; using System.Collections; abstract public class BehaviourBase { public int m_id; public int m_percent; public BehaviourBase(int id, int percent) { m_id = id; m_percent = percent; } abstract public bool IsNeed(); abstract public bool IsAvailable(); } public class BehaviourGeneric : BehaviourBase { public BehaviourGeneric(int id, int percent) : base(id, percent) { } override public bool IsNeed() { return false;} override public bool IsAvailable() { return true;} } public class BehaviourPatten { Hashtable m_behaviours = new Hashtable(); float m_sleepTime; public void Set(BehaviourBase behaviour) { m_behaviours.Add (behaviour.m_id,behaviour); } public void Sleep(float sleepTime) { m_sleepTime = sleepTime; } public int NextBehaviour() { m_sleepTime -=Time.deltaTime; if(m_sleepTime >= 0) return 0; ArrayList array=new ArrayList(); int total_percent=0; int need=0; foreach( BehaviourBase b in m_behaviours.Values) { if( b.IsNeed ()) need= b.m_id; if(b.IsAvailable()) { total_percent += b.m_percent; array.Add(b); } } if(need !=0) { m_sleepTime =0; return need; } /* m_sleepTime -=Time.deltaTime; if(m_sleepTime >= 0) return 0; */ int random = Random.Range(0, total_percent); int next=0; foreach( BehaviourBase b in array) { next += b.m_percent; if ( random <= next) { return b.m_id; } } return 0; } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class GameOverUIManager : MonoBehaviour { public void OnNoClicked() { GameManager.LoadAfterLoadingScene("MainMenu"); } public void OnYesClicked() { GameManager.Player.Set(3, 0); GameManager.LoadAfterLoadingScene("M1"); } }
using UnityEngine; using UnityEngine.UI; using System.Collections; using UnityEngine.SceneManagement; public class MenuUi : MonoBehaviour { public Text code; public Text mission1; public Text mission2; public Text mission3; public Image star; void Update() { //显示任务 switch (Menu.level) { case 1: code.text = "代号:本能"; mission1.text = "任务1:坚持30秒\n(解锁新关卡)"; mission2.text = "任务2:击杀10个敌人\n(解锁2零件)"; mission3.text = "任务3:与敌人距离不小于1米\n(解锁4零件)"; break; case 2: code.text = "代号:启示"; mission1.text = "任务1:击杀30名敌人\n(暂无)"; mission2.text = "任务2:1分钟内完成\n(解锁2零件)"; mission3.text = "任务3:35秒内完成\n(解锁4零件)"; break; case 3: code.text = "代号:危机"; mission1.text = "任务1:坚持2分钟\n(暂无)"; mission2.text = "任务2:与敌人距离不小于1米\n(解锁2零件)"; mission3.text = "任务3:杀敌数不能达到40\n(解锁4零件)"; break; case 4: code.text = "代号:抉择"; mission1.text = "任务1:坚持1分钟\n(暂无)"; mission2.text = "任务2:杀敌数不能达到20\n(解锁3零件)"; mission3.text = "任务3:找到粉红毛绒熊\n(解锁4零件)"; break; case 5: code.text = "代号:风暴"; mission1.text = "任务1:击杀30个敌人\n(暂无)"; mission2.text = "任务2:找到粉红毛绒熊\n(解锁2零件)"; mission3.text = "任务3:30秒内完成\n(解锁3零件)"; break; } //显示评分 if (Menu.roomNum[1, Menu.level] ) { mission1.color = Color.yellow; } else { mission1.color = Color.black; } if (Menu.roomNum[2, Menu.level]) { mission2.color = Color.yellow; } else { mission2.color = Color.black; } if (Menu.roomNum[3, Menu.level]) { mission3.color = Color.yellow; } else { mission3.color = Color.black; } star.fillAmount = Menu.balabala[Menu.level]; } public void OnStartGame() { SceneManager.LoadScene("WeaponAssemblageWIP"); } public void OnEndGame() { Application.Quit(); } }
using System.Collections.Generic; namespace ArduinoAPI.Service { public interface IMemoryStorage { /// <summary> /// Adds an item to the dictionary /// </summary> /// <param name="key">The given key for the value</param> /// <param name="value">The given value</param> /// <returns></returns> public bool AddItem(string key, object value); /// <summary> /// Updates the given value /// </summary> /// <param name="key">The given key for the value</param> /// <param name="value">The value</param> public void UpdateItem(string key, object value); /// <summary> /// Delete's a given value using its key /// </summary> /// <param name="key">Key for the given value</param> /// <returns></returns> public bool DeleteItem(string key); /// <summary> /// Gets the given value casted as T /// </summary> /// <typeparam name="T">T can be anything but the value must be able to be casted to T</typeparam> /// <param name="key">Key for the given value</param> /// <returns>The value casted as T</returns> public T GetItem<T>(string key); /// <summary> /// Gets a list of values casted as T /// </summary> /// <typeparam name="T">T can be anything but the value must be able to be casted to T</typeparam> /// <returns>A List of values casted as T</returns> public List<T> GetAllItems<T>(); } }
using UnityEngine; public class MovementScript : MonoBehaviour { void Update () { transform.Translate(Input.GetAxis("Horizontal") * 0.5f, Input.GetAxis("Vertical") * 0.5f, 0f); } }
using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Xaml; using Microsoft.Maui.Dispatching; using System; using Telerik.Maui.Controls; using QSF.Services.Interfaces; namespace QSF.Examples.BadgeViewControl.FirstLookExample { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class FirstLookView : RadContentView, INavigationView { private IDispatcherTimer pollingTimer; public FirstLookView() { this.InitializeComponent(); this.InitializePollingTimer(); } private void InitializePollingTimer() { this.pollingTimer = this.Dispatcher.CreateTimer(); this.pollingTimer.Interval = TimeSpan.FromSeconds(2); this.pollingTimer.Tick += this.OnPollingTimerTick; this.pollingTimer.IsRepeating = true; } private void OnPollingTimerTick(object sender, EventArgs eventArgs) { var viewModel = (FirstLookViewModel)this.BindingContext; viewModel.UpdateUnreadMessages(); } public void OnAppearing() { this.pollingTimer.Start(); } public void OnDisappearing() { this.pollingTimer.Stop(); } } }
/* * Copyright 2017 Mikhail Shiryaev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * Product : Rapid SCADA * Module : ScadaData * Summary : SCADA-Server connection settings * * Author : Mikhail Shiryaev * Created : 2005 * Modified : 2017 */ using System; using System.IO; using System.Xml; using Utils; namespace Scada.Client { /// <summary> /// SCADA-Server connection settings /// <para>Настройки соединения со SCADA-Сервером</para> /// </summary> public class CommSettings : ISettings { /// <summary> /// Имя файла настроек по умолчанию /// </summary> public const string DefFileName = "CommSettings.xml"; /// <summary> /// Конструктор /// </summary> public CommSettings() { SetToDefault(); } /// <summary> /// Конструктор с установкой параметров связи /// </summary> public CommSettings(string serverHost, int serverPort, string serverUser, string serverPwd, int serverTimeout) { ServerHost = serverHost; ServerPort = serverPort; ServerUser = serverUser; ServerPwd = serverPwd; ServerTimeout = serverTimeout; } /// <summary> /// Получить или установить имя компьютера или IP-адрес SCADA-Сервера /// </summary> public string ServerHost { get; set; } /// <summary> /// Получить или установить номер TCP-порта SCADA-Сервера /// </summary> public int ServerPort { get; set; } /// <summary> /// Получить или установить имя пользователя для подключения к SCADA-Серверу /// </summary> public string ServerUser { get; set; } /// <summary> /// Получить или установить пароль пользователя для подключения к SCADA-Серверу /// </summary> public string ServerPwd { get; set; } /// <summary> /// Получить или установить таймаут ожидания ответа SCADA-Сервера, мс /// </summary> public int ServerTimeout { get; set; } /// <summary> /// Создать новый объект настроек /// </summary> public ISettings Create() { return new CommSettings(); } /// <summary> /// Определить, равны ли заданные настройки текущим настройкам /// </summary> public bool Equals(ISettings settings) { return Equals(settings as CommSettings); } /// <summary> /// Определить, равны ли заданные настройки текущим настройкам /// </summary> public bool Equals(CommSettings commSettings) { return commSettings == null ? false : commSettings == this ? true : ServerHost == commSettings.ServerHost && ServerPort == commSettings.ServerPort && ServerUser == commSettings.ServerUser && ServerPwd == commSettings.ServerPwd && ServerTimeout == commSettings.ServerTimeout; } /// <summary> /// Установить значения настроек по умолчанию /// </summary> public void SetToDefault() { ServerHost = "localhost"; ServerPort = 10000; ServerUser = ""; ServerPwd = "12345"; ServerTimeout = 10000; } /// <summary> /// Создать копию настроек /// </summary> public CommSettings Clone() { return new CommSettings(ServerHost, ServerPort, ServerUser, ServerPwd, ServerTimeout); } /// <summary> /// Загрузить настройки из заданного XML-узла /// </summary> public void LoadFromXml(XmlNode commSettingsNode) { if (commSettingsNode == null) throw new ArgumentNullException("commSettingsNode"); XmlNodeList xmlNodeList = commSettingsNode.SelectNodes("Param"); foreach (XmlElement xmlElement in xmlNodeList) { string name = xmlElement.GetAttribute("name").Trim(); string nameL = name.ToLowerInvariant(); string val = xmlElement.GetAttribute("value"); try { if (nameL == "serverhost") ServerHost = val; else if (nameL == "serverport") ServerPort = int.Parse(val); else if (nameL == "serveruser") ServerUser = val; else if (nameL == "serverpwd") ServerPwd = val; else if (nameL == "servertimeout") ServerTimeout = int.Parse(val); } catch { throw new ScadaException(string.Format(CommonPhrases.IncorrectXmlParamVal, name)); } } } /// <summary> /// Загрузить настройки из файла /// </summary> public bool LoadFromFile(string fileName, out string errMsg) { // установка значений по умолчанию SetToDefault(); // загрузка настроек соединения со SCADA-Сервером try { if (!File.Exists(fileName)) throw new FileNotFoundException(string.Format(CommonPhrases.NamedFileNotFound, fileName)); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(fileName); LoadFromXml(xmlDoc.DocumentElement); errMsg = ""; return true; } catch (Exception ex) { errMsg = CommonPhrases.LoadCommSettingsError + ": " + ex.Message; return false; } } /// <summary> /// Сохранить настройки в заданный XML-элемент /// </summary> public void SaveToXml(XmlElement commSettingsElem) { commSettingsElem.AppendParamElem("ServerHost", ServerHost, "Имя компьютера или IP-адрес SCADA-Сервера", "SCADA-Server host or IP address"); commSettingsElem.AppendParamElem("ServerPort", ServerPort, "Номер TCP-порта SCADA-Сервера", "SCADA-Server TCP port number"); commSettingsElem.AppendParamElem("ServerUser", ServerUser, "Имя пользователя для подключения", "User name for the connection"); commSettingsElem.AppendParamElem("ServerPwd", ServerPwd, "Пароль пользователя для подключения", "User password for the connection"); commSettingsElem.AppendParamElem("ServerTimeout", ServerTimeout, "Таймаут ожидания ответа, мс", "Response timeout, ms"); } /// <summary> /// Сохранить настройки в файле /// </summary> public bool SaveToFile(string fileName, out string errMsg) { try { XmlDocument xmlDoc = new XmlDocument(); XmlDeclaration xmlDecl = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); xmlDoc.AppendChild(xmlDecl); XmlElement rootElem = xmlDoc.CreateElement("CommSettings"); xmlDoc.AppendChild(rootElem); SaveToXml(rootElem); xmlDoc.Save(fileName); errMsg = ""; return true; } catch (Exception ex) { errMsg = CommonPhrases.SaveCommSettingsError + ":\n" + ex.Message; return false; } } } }
using FileHelpers; namespace truck_manifest { [DelimitedRecord("|")] public class A1TruckTimeData : BaseRecord { public string TruckID; public string TruckTime; } }
@{ Layout="shared/_Layout.cshtml"; } <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <div class="container"> <div class="jumbotron"> <h1>answer:</h1> </div> <h2>the word you selected appear's @Model times</h2> <h3><a href="/">Return Home</a></h3> </body> </div> </html>
using System; #if WINDOWS_UWP using Windows.UI.ViewManagement; #elif __MACOS__ using AppKit; #endif using Xam.Forms.Markdown; using Xamarin.Forms; namespace ConferenceKiosk { public partial class GuidePage : ContentPage { Color activeColor = Color.FromHex("#e3008c"); Color otherColor = Color.FromHex("9b9b9b"); Button[] progressBtns; public GuidePage() { InitializeComponent(); NavigationPage.SetHasNavigationBar(this, false); markdown.Theme = new MyMarkdownTheme(); markdown.Markdown = Markdown.GetNextPage(); progressBtns = new Button[] { BtnOne, BtnTwo, BtnThree, BtnFour, BtnFive, BtnSix }; UpdateProgressButtons(); } async void NextBtnClicked(object sender, EventArgs e) { if (Markdown.IsLastPage) { var nav = Navigation.PushAsync(new FinalPage()); #if WINDOWS_UWP var pref = ViewModePreferences.CreateDefault(ApplicationViewMode.Default); pref.CustomSize = new Windows.Foundation.Size(800, 600); await ApplicationView.GetForCurrentView().TryEnterViewModeAsync(ApplicationViewMode.Default, pref); #elif __MACOS__ NSApplication.SharedApplication.MainWindow.Level = NSWindowLevel.Normal; NSApplication.SharedApplication.MainWindow.ToggleFullScreen(NSApplication.SharedApplication.MainWindow); #endif await nav; } else { markdown.Markdown = Markdown.GetNextPage(); BackBtn.IsVisible = true; UpdateProgressButtons(); } } void PrevBtnClicked(object sender, EventArgs e) { if(Markdown.WillBeFirstPage) BackBtn.IsVisible = false; else BackBtn.IsVisible = true; markdown.Markdown = Markdown.GetPrevPage(); UpdateProgressButtons(); } void ProgressBtnClicked(object sender, EventArgs e) { var index = sender.GetType() == typeof(ProgressButton) ? (sender as ProgressButton).Index : (Markdown.PageCount - 1); if (index == Markdown.Index) return; if (index == 0) BackBtn.IsVisible = false; else BackBtn.IsVisible = true; markdown.Markdown = Markdown.GetPage(index); UpdateProgressButtons(); } void UpdateProgressButtons() { for (int i = 0; i < Markdown.PageCount - 1; i++) { if (i == Markdown.Index) progressBtns[i].BackgroundColor = activeColor; else progressBtns[i].BackgroundColor = otherColor; } if (Markdown.IsLastPage) { phoneIcon.Source = "phone_active.png"; NextLabel.Text = "DONE"; } else { phoneIcon.Source = "phone_progress.png"; NextLabel.Text = "NEXT"; } } } public class MyMarkdownTheme : DarkMarkdownTheme { public MyMarkdownTheme() { BackgroundColor = Color.Black; switch(Device.RuntimePlatform) { case Device.UWP: Paragraph.FontSize = 14; Code.FontSize = 14; break; } } } public class ProgressButton : Button { public static BindableProperty IndexProperty = BindableProperty.Create("Index", typeof(int), typeof(ProgressButton), -1); public static BindableProperty IsActiveProperty = BindableProperty.Create("IsActive", typeof(bool), typeof(ProgressButton), false); public int Index { get { return (int)GetValue(IndexProperty); } set { SetValue(IndexProperty, value); } } public bool IsActive { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _04.Logistics { class Logistics { static void Main(string[] args) { int loads = int.Parse(Console.ReadLine()); double microbusPrice = 200d; double truckPrice = 175d; double trainPrice = 120d; int microbus = 0; int truck = 0; int train = 0; double totalTons = 0.0d; for (int i = 0; i < loads; i++) { int singleLoad = int.Parse(Console.ReadLine()); if (singleLoad > 0 && singleLoad <= 3) { microbus += singleLoad; } else if (singleLoad > 3 && singleLoad <= 11) { truck += singleLoad; } else if (singleLoad > 11) { train += singleLoad; } totalTons += singleLoad; } double average = (microbus * microbusPrice + truck * truckPrice + train * trainPrice) / totalTons; double microbusPercentage = microbus / totalTons * 100; double truckPercentage = truck / totalTons * 100; double trainPercentage = train / totalTons * 100; Console.WriteLine($"{average:f2}\n{microbusPercentage:f2}%\n{truckPercentage:f2}%\n{trainPercentage:f2}%"); } } }
#nullable enable namespace BizHawk.Client.Common { public readonly struct KeyEvent { public readonly DistinctKey Key; public readonly bool Pressed; public KeyEvent(DistinctKey key, bool pressed) { Key = key; Pressed = pressed; } } }
using MVCCaching; using Generic.Repositories.Interfaces; using Generic.Models; using CMS.DataEngine; using Generic.Repositories.Helpers.Interfaces; namespace Generic.Repositories.Implementations { public class KenticoSiteSettingsRepository : ISiteSettingsRepository { private IKenticoSiteSettingsRepositoryHelper _Helper; public KenticoSiteSettingsRepository(IKenticoSiteSettingsRepositoryHelper Helper) { _Helper = Helper; } [DoNotCache] public PasswordPolicySettings GetPasswordPolicy(string SiteName) { return new PasswordPolicySettings() { UsePasswordPolicy = _Helper.GetBoolSettingValue(SiteName, "CMSUsePasswordPolicy"), MinLength = _Helper.GetIntSettingValue(SiteName, "CMSPolicyMinimalLength"), NumNonAlphanumericChars = _Helper.GetIntSettingValue(SiteName, "CMSPolicyNumberOfNonAlphaNumChars"), Regex = _Helper.GetStringSettingValue(SiteName, "CMSPolicyRegularExpression"), ViolationMessage = _Helper.GetStringSettingValue(SiteName, "CMSPolicyViolationMessage") }; } } }
using System; using System.Collections.Generic; using System.Text; namespace EM.GIS.Symbology { /// <summary> /// 要素分类 /// </summary> public interface IFeatureCategory : ICategory { /// <summary> /// 过滤表达式 /// </summary> string FilterExpression { get; set; } /// <summary> /// 选择的符号 /// </summary> IFeatureSymbolizer SelectionSymbolizer { get; set; } /// <summary> /// 符号 /// </summary> IFeatureSymbolizer Symbolizer { get; set; } } }
using System.Collections.Generic; namespace UltimateTeam.Toolkit.Parameters { public class ClubInfoType : SearchParameterBase<string> { public const string Kit = "kit"; public const string Badge = "badge"; private ClubInfoType(string descripton, string value) { Description = descripton; Value = value; } public static IEnumerable<ClubInfoType> GetAll() { yield return new ClubInfoType("kit", Kit); yield return new ClubInfoType("badge", Badge); } } }
using System; using Microsoft.Maui.Controls.Compatibility.ControlGallery.Issues; namespace Microsoft.Maui.Controls.Compatibility.ControlGallery { public class FlyoutPageTabletPage : ContentPage { public FlyoutPageTabletPage() { Title = "FlyoutPage FlyoutLayoutBehavior Gallery"; var btn = new Button { Text = "Default (old behavior)" }; btn.Clicked += async (sender, e) => await Navigation.PushModalAsync(new Issue1461Page(FlyoutLayoutBehavior.Default, null)); var btn1 = new Button { Text = "Default (old behavior) but always hide toolbar button" }; btn1.Clicked += async (sender, e) => await Navigation.PushModalAsync(new Issue1461Page(FlyoutLayoutBehavior.Default, false)); var btn2 = new Button { Text = "Popover - (always show it as a popover) but hide toolbar button" }; btn2.Clicked += async (sender, e) => await Navigation.PushModalAsync(new Issue1461Page(FlyoutLayoutBehavior.Popover, false)); //there's never a time when to real hide the master i think, use a normal page for that.. //what the user wants is out of the screen, maybe we need a better namming var btn3 = new Button { Text = "Popover - (always show it as a popover)" }; btn3.Clicked += async (sender, e) => await Navigation.PushModalAsync(new Issue1461Page(FlyoutLayoutBehavior.Popover, null)); //we throw an exception here if you try to toggle it var btn4 = new Button { Text = "Split - (always show it as splitview , toggle master always visible, throws exception)" }; btn4.Clicked += async (sender, e) => await Navigation.PushModalAsync(new Issue1461Page(FlyoutLayoutBehavior.Split, null)); var btn5 = new Button { Text = "SplitOnPortrait Portrait - (always show it as splitview in Portrait, throws exception)" }; btn5.Clicked += async (sender, e) => await Navigation.PushModalAsync(new Issue1461Page(FlyoutLayoutBehavior.SplitOnPortrait, null)); var btn6 = new Button { Text = "SplitOnLandscape Landscape - (always show it as splitview in Landscape, throws exception))" }; btn6.Clicked += async (sender, e) => await Navigation.PushModalAsync(new Issue1461Page(FlyoutLayoutBehavior.SplitOnLandscape, null)); Content = new StackLayout { Padding = new Thickness(0, 20, 0, 0), Children = { btn, btn1, btn2, btn6, btn3, btn4, btn5 }, Spacing = 20 }; } } }
namespace NHSD.GPIT.BuyingCatalogue.UI.Components.Views.Shared.TagHelpers.TaskList { public sealed class TaskListContext { public TaskListContext() { SectionNumberCount = 1; } public int SectionNumberCount { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using OwinFramework.Pages.Core.Collections; using OwinFramework.Pages.Core.Debug; using OwinFramework.Pages.Core.Extensions; using OwinFramework.Pages.Core.Interfaces.Collections; using OwinFramework.Pages.Core.Interfaces.DataModel; using OwinFramework.Pages.Core.Interfaces.Managers; using OwinFramework.Pages.Core.Interfaces.Runtime; namespace OwinFramework.Pages.Framework.DataModel { internal class DataContext: ReusableObject, IDataContext, IDebuggable { public IDataContextBuilder DataContextBuilder { get; set; } private readonly DataContextFactory _dataContextFactory; private readonly IDataDependencyFactory _dataDependencyFactory; #if DEBUG private readonly int _id; #endif private IRenderContext _renderContext; private IDataContext _parent; public DataContext( IDictionaryFactory dictionaryFactory, DataContextFactory dataContextFactory, IDataDependencyFactory dataDependencyFactory, IIdManager idManager) { _dataContextFactory = dataContextFactory; _dataDependencyFactory = dataDependencyFactory; _properties = new LinkedList<PropertyEntry>(); #if DEBUG _id = idManager.GetUniqueId(); #endif } public DataContext Initialize( Action<IReusable> disposeAction, IRenderContext renderContext, IDataContextBuilder dataContextBuilder, DataContext parent) { if (dataContextBuilder == null) throw new ArgumentNullException("dataContextBuilder"); if (renderContext == null) throw new ArgumentNullException("renderContext"); Initialize(disposeAction); _properties.Clear(); _renderContext = renderContext; _parent = parent; DataContextBuilder = dataContextBuilder; return this; } #if DEBUG /// <summary> /// This exists so that you can inspect it in the debugger. It serves no other purpose /// </summary> private string _debugProperties { get { var result = new StringBuilder(); Action<DataContext> addProperties = dc => { if (dc.DataContextBuilder != null) { result.AppendLine("Data context builder #" + dc.DataContextBuilder.Id); var debuggable = dc.DataContextBuilder as IDebuggable; if (debuggable != null) { var rules = debuggable.GetDebugInfo<DebugDataScopeRules>(); if (rules != null && rules.Scopes != null) { foreach (var scope in rules.Scopes) result.AppendLine(" " + scope); } } } foreach(var property in dc._properties) { result.AppendFormat("{0} = {1}\n", property.ToString(), property.Value); } }; result.AppendLine("Properties in data context #" + _id); addProperties(this); var parent = _parent as DataContext; while (parent != null) { result.AppendLine(); result.AppendLine("Properties in parent data context #" + parent._id); addProperties(parent); parent = parent._parent as DataContext; } return result.ToString(); } } #endif T IDebuggable.GetDebugInfo<T>(int parentDepth, int childDepth) { return new DebugDataContext { Instance = this, DataContextBuilder = DataContextBuilder, Properties = _properties.Select(p => p.Type).ToList(), Parent = _parent == null || parentDepth == 0 ? null : _parent.GetDebugInfo(parentDepth - 1, 0) } as T; } public override string ToString() { return DataContextBuilder == null ? "data context with " + _properties.Count + " properties" : "data context #" + DataContextBuilder.Id + " with " + _properties.Count + " properties"; } IDataContext IDataContext.CreateChild(IDataContextBuilder dataContextBuilder) { return _dataContextFactory.Create(_renderContext, dataContextBuilder, this); } public void Set<T>(T value, string scopeName, int level) { if (string.IsNullOrEmpty(scopeName)) SetUnscoped(typeof(T), value, level); else SetScoped(typeof(T), value, scopeName); } void IDataContext.Set(Type type, object value, string scopeName, int level) { if (string.IsNullOrEmpty(scopeName)) SetUnscoped(type, value, level); else SetScoped(type, value, scopeName); } T IDataContext.Get<T>(string scopeName, bool isRequired) { if (string.IsNullOrEmpty(scopeName)) return (T)GetUnscoped(typeof(T), isRequired); return (T)GetScoped(typeof(T), scopeName, isRequired); } object IDataContext.Get(Type type, string scopeName, bool isRequired) { if (string.IsNullOrEmpty(scopeName)) return GetUnscoped(type, isRequired); return GetScoped(type, scopeName, isRequired); } private void SetScoped(Type type, object value, string scopeName) { var dependency = _dataDependencyFactory.Create(type, scopeName); var isInScope = DataContextBuilder.IsInScope(dependency); if (isInScope || _parent == null) SetProperty(type, scopeName, value); else _parent.Set(type, value, scopeName); } private void SetUnscoped(Type type, object value, int level) { if (level == 0 || _parent == null) SetProperty(type, value); else { _parent.Set(type, value, null, level - 1); DeleteProperty(type); } } private object GetScoped(Type type, string scopeName, bool isRequired) { var retry = false; while (true) { object result; if (TryGetProperty(type, scopeName, out result)) return result; var dependency = _dataDependencyFactory.Create(type, scopeName); var isInScope = DataContextBuilder.IsInScope(dependency); if (!isInScope) { if (_parent == null) { if (!isRequired) return null; throw ScopeSearchFailedException(type, scopeName); } return _parent.Get(type, scopeName, isRequired); } if (!isRequired) return null; if (retry) throw RetryFailedException(type); DataContextBuilder.AddMissingData(_renderContext, dependency); retry = true; } } private object GetUnscoped(Type type, bool isRequired) { var retry = false; while (true) { object result; if (TryGetProperty(type, out result)) return result; if (_parent != null) return _parent.Get(type, null, isRequired); if (!isRequired) return null; if (retry) throw RetryFailedException(type); DataContextBuilder.AddMissingData(_renderContext, _dataDependencyFactory.Create(type)); retry = true; } } private Exception RetryFailedException(Type type) { return new Exception("This data context does not know how to find missing" + " data of type " + type.DisplayName() + " because after adding it to the scope provider" + " the dependency could still not be resolved"); } private Exception ScopeSearchFailedException(Type type, string scopeName) { return new Exception("This data context does not know how to find missing" + " data of type " + type.DisplayName() + " in '" + scopeName + "' scope because this type is" + " not in scope for any data conetxt in the ancestor path"); } #region Properties private readonly LinkedList<PropertyEntry> _properties; private bool TryGetProperty(Type type, out object value) { PropertyEntry match = null; foreach(var property in _properties.Where(p => p.Type == type)) { if (match == null) match = property; else { if (!string.IsNullOrEmpty(match.ScopeName)) match = property; } } if (match == null) { value = null; return false; } value = match.Value; return true; } private bool TryGetProperty(Type type, string scopeName, out object value) { if (string.IsNullOrEmpty(scopeName)) return TryGetProperty(type, out value); var match = _properties.FirstOrDefault( p => p.Type == type && string.Equals(scopeName, p.ScopeName, StringComparison.OrdinalIgnoreCase)); if (match == null) { value = null; return false; } value = match.Value; return true; } private void SetProperty(Type type, string scopeName, object value) { if (string.IsNullOrEmpty(scopeName)) { SetProperty(type, value); return; } var existing = _properties.FirstOrDefault( p => p.Type == type && string.Equals(scopeName, p.ScopeName, StringComparison.OrdinalIgnoreCase)); if (existing == null) _properties.AddFirst(new PropertyEntry { Type = type, ScopeName = scopeName, Value = value }); else existing.Value = value; } private void SetProperty(Type type, object value) { var existing = _properties.FirstOrDefault( p => p.Type == type && string.IsNullOrEmpty(p.ScopeName)); if (existing == null) _properties.AddFirst(new PropertyEntry { Type = type, Value = value }); else existing.Value = value; } private void DeleteProperty(Type type, string scopeName) { if (string.IsNullOrEmpty(scopeName)) DeleteProperty(type); else { // TODO: No efficient way to remove list elements using the .Net LinkedList class } } private void DeleteProperty(Type type) { // TODO: No efficient way to remove list elements using the .Net LinkedList class } private class PropertyEntry { public Type Type; public string ScopeName; public object Value; public override string ToString() { var result = Type.DisplayName(TypeExtensions.NamespaceOption.None); if (string.IsNullOrEmpty(ScopeName)) return result; return result + " in '" + ScopeName + "' scope"; } } #endregion } }
using Roguelike.Attributes; using Roguelike.Tiles.Looting; using System; using System.Collections.Generic; using System.Linq; namespace Roguelike.Abilities { public class AbilitiesSet { List<PassiveAbility> passiveAbilities = new List<PassiveAbility>(); List<ActiveAbility> activeAbilities = new List<ActiveAbility>(); //List<Ability> allItems = new List<Ability>(); public AbilitiesSet() { EnsureItems(); } public void EnsureItems() { { var kinds = Enum.GetValues(typeof(AbilityKind)).Cast<AbilityKind>().ToList(); foreach (var kind in kinds) { if (passiveAbilities.Any(i => i.Kind == kind) || kind == AbilityKind.Unset) continue; Ability ab = null; if (kind == AbilityKind.ExplosiveMastering || kind == AbilityKind.ThrowingStoneMastering || kind == AbilityKind.ThrowingKnifeMastering || kind == AbilityKind.HunterTrapMastering) { ab = new ActiveAbility() { Kind = kind }; activeAbilities.Add(ab as ActiveAbility); } else { if (kind == AbilityKind.LootingMastering) ab = new LootAbility(true) { Kind = AbilityKind.LootingMastering }; else ab = new PassiveAbility() { Kind = kind }; passiveAbilities.Add(ab as PassiveAbility); } //allItems.Add(ab); } } } public Ability GetByEntityStatKind(EntityStatKind esk, bool primary) { if (primary) return PassiveItems.Where(i => i.PrimaryStat.Kind == esk).FirstOrDefault(); return PassiveItems.Where(i => i.AuxStat.Kind == esk).FirstOrDefault(); } //public List<Ability> AllItems //{ // get // { // //can not called it here - deserialization doubles items! // //if (!abilities.Any()) // return allItems; // } //} public Ability GetAbility(AbilityKind kind) { Ability ab = passiveAbilities.Where(i => i.Kind == kind).FirstOrDefault(); if(ab == null) ab = activeAbilities.Where(i => i.Kind == kind).FirstOrDefault(); return ab; } public List<PassiveAbility> PassiveItems { get { //can not called it here - deserialization doubles items! //if (!abilities.Any()) // EnsureAbilities(); return passiveAbilities; } set { passiveAbilities = value;//for serialization } } public List<ActiveAbility> ActiveItems { get { return activeAbilities; } set { activeAbilities = value;//for serialization } } } }
using CloudinaryDotNet; using Picturra.Models.Image; namespace Picturra.Presenter.Adapters { public interface ICloudinaryAdapter { Account Credentials { get; set; } Image UploadImage(ImageUpload imageUpload); void DeleteImage(string token); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using TimsWpfControls.Converter; using TimsWpfControls.Model; namespace DataGridCellStyleExample { public class Person : BaseClass { public Person(string firstName, string lastName, int age) { Name = lastName; FirstName = firstName; Age = age; } private string _Name; public string Name { get { return _Name; } set { _Name = value; RaisePropertyChanged(nameof(Name)); } } private string _FirstName; public string FirstName { get { return _FirstName; } set { _FirstName = value; RaisePropertyChanged(nameof(FirstName)); } } private int _Age; public int Age { get { return _Age; } set { _Age = value; RaisePropertyChanged(nameof(Age)); } } } public class ViewModel : BaseClass { public ObservableCollection<Person> People { get; } = new ObservableCollection<Person>() { new Person("Tim", "U.", 32), new Person("Tom", "Tommy", 45), new Person("Tick", "Tack", 10), new Person("Trick", "Track", 20) }; } }
using System; namespace STak.WinTak { public interface IModelHighlighter { bool IsHighlighted { get; } void Highlight(bool highlight); } }
using System; using System.Data; using SavepointHandlers; namespace SavepointHandlers.SqlServer { public class SqlServerSavepointAdapter : ISavepointAdapter { public string SetSavepoint(IDbCommand command) { var savePointName = Guid.NewGuid().ToString("N"); command.CommandText = "SAVE TRANSACTION @SavePointName"; var parameter = command.CreateParameter(); parameter.ParameterName = "@SavePointName"; parameter.Value = savePointName; command.Parameters.Add(parameter); command.ExecuteNonQuery(); return savePointName; } public void RollbackToSavepoint(IDbCommand command, string savePointName) { command.CommandText = "ROLLBACK TRANSACTION @SavePointName SAVE TRANSACTION @SavePointName"; var parameter = command.CreateParameter(); parameter.ParameterName = "@SavePointName"; parameter.Value = savePointName; command.Parameters.Add(parameter); command.ExecuteNonQuery(); } } }
using System; using CMS.UIControls; public partial class CMSInstall_Controls_LayoutPanels_Warning : CMSUserControl { /// <summary> /// Gets client ID of warning label control. /// </summary> public string WarningLabelClientID { get { return lblWarning.ClientID; } } }
namespace BinaryPuzzleDotComScraper { public enum PuzzleDifficulty { Easy = 1, Medium, Hard, VeryHard } }
using DotGather.Interfaces; namespace DotGather.GatherContent.Objects { /// <summary> /// This class maps to a GatherContent DueDate Object. /// </summary> /// <seealso cref="IDueDate"/> /// <seealso cref="Page"/> public class DueDate : IDueDate { /// <summary>The unique ID used to identify a DueDate</summary> public int StatusId { get; set; } /// <summary>Specifies if the Date has passed</summary> public bool Overdue { get; set; } /// <summary>This property represents a Date and Time</summary> /// <seealso cref="GatherContentDate"/> public IDate Date { get; set; } } }
using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace CronJobs.Infrastructure.Extensions { public static class ApplicationBuilderJobExtensions { public static void UseJobServer(this IApplicationBuilder builder) { var options = builder.ApplicationServices.GetService<JobBuilderOptions>(); var jobServer = new JobManager(options, builder); jobServer.Start(); } } }
using System; using System.Net; using System.Threading; using System.Threading.Tasks; using Righthand.ViceMonitor.Bridge.Commands; using Righthand.ViceMonitor.Bridge.Services.Implementation; namespace Righthand.ViceMonitor.Bridge.Services.Abstract { /// <summary> /// Interface to access <see cref="ViceBridge"/> /// </summary> public interface IViceBridge: IAsyncDisposable, IDisposable { /// <summary> /// Task where loop is running. /// </summary> Task? RunnerTask { get; } /// <summary> /// Gets running status. Running is set once the connection to VICE is established. /// </summary> bool IsRunning { get; } /// <summary> /// Gets started status. Started is set as soon as bridge starts. /// </summary> bool IsStarted { get; } /// <summary> /// Gets connection to VICE status. /// </summary> bool IsConnected { get; } /// <summary> /// Starts the bridge. /// </summary> /// <param name="port">Port of the binary monitor. 6502 by default.</param> void Start(int port = 6502); /// <summary> /// Stops the bridge. /// </summary> /// <returns></returns> Task StopAsync(); /// <summary> /// Enqueues command for sending /// </summary> /// <typeparam name="T">Command type</typeparam> /// <param name="command">An instance of <see cref="ViceCommand{TResponse}"/> subtype to enqueue.</param> /// <returns>An instance of passed in command.</returns> T EnqueueCommand<T>(T command) where T : IViceCommand; /// <summary> /// Occurs when an unbound event arrived. /// </summary> /// <threadsafety>Can occur on any thread.</threadsafety> event EventHandler<ViceResponseEventArgs>? ViceResponse; /// <summary> /// Occurs when connection status to VICE changes. /// </summary> /// <threadsafety>Can occur on any thread.</threadsafety> event EventHandler<ConnectedChangedEventArgs>? ConnectedChanged; /// <summary> /// Waits for connection status change. /// </summary> /// <param name="ct"></param> /// <returns>New IsConnectedValue.</returns> Task<bool> WaitForConnectionStatusChangeAsync(CancellationToken ct = default); } }
using System.Collections.Generic; using Telerik.Charting; using Windows.Foundation; using Windows.UI.Composition; using Windows.UI.Xaml.Media; namespace Telerik.UI.Xaml.Controls.Chart { internal abstract class ChartSeriesRenderer { internal ChartSeriesModel model; internal IList<DataPoint> renderPoints; private const double PlotAreaVicinity = 5.0; public void Render(bool isDrawnWithComposition = false) { this.Reset(); this.renderPoints = this.GetRenderPoints(); if (this.renderPoints.Count == 0) { return; } if (!isDrawnWithComposition) { this.RenderCore(); } } public virtual void ApplyPalette() { } public virtual void ApplyContainerVisualPalette(ContainerVisual containerVisual, ContainerVisualsFactory factory) { } protected internal static IEnumerable<DataPointSegment> GetDataSegments(IList<DataPoint> dataPoints) { DataPointSegment dataSegment = null; int pointIndex = 0; foreach (DataPoint point in dataPoints) { if (point.isEmpty || double.IsNaN(point.CenterX()) || double.IsNaN(point.CenterY())) { if (dataSegment != null) { dataSegment.EndIndex = pointIndex - 1; // segment is defined for at least two points if (dataSegment.StartIndex != dataSegment.EndIndex) { yield return dataSegment; } dataSegment = null; } } else { if (dataSegment == null) { dataSegment = new DataPointSegment(); dataSegment.StartIndex = pointIndex; } } pointIndex++; } if (dataSegment != null) { dataSegment.EndIndex = dataPoints.Count - 1; // segment is defined for at least two points if (dataSegment.StartIndex != dataSegment.EndIndex) { yield return dataSegment; } } } protected virtual IList<DataPoint> GetRenderPoints() { if (this.model.renderablePoints.Count > 0) { return this.GetRenderPoints(this.model.renderablePoints); } return this.GetRenderPoints(this.model.DataPointsInternal); } protected Brush GetPaletteBrush(PaletteVisualPart part) { ChartSeries series = this.model.presenter as ChartSeries; if (series == null) { return null; } return series.chart.GetPaletteBrush(series.ActualPaletteIndex, part, series.Family, series.IsSelected); } protected abstract void Reset(); protected abstract void RenderCore(); private List<DataPoint> GetRenderPoints(IList<DataPoint> dataPoints) { var clipRect = this.model.layoutSlot; var plotDirection = this.model.GetTypedValue<AxisPlotDirection>(AxisModel.PlotDirectionPropertyKey, AxisPlotDirection.Vertical); bool isVertical = plotDirection == AxisPlotDirection.Vertical; double start = isVertical ? clipRect.X - PlotAreaVicinity : clipRect.Y - PlotAreaVicinity; double end = isVertical ? clipRect.Right + PlotAreaVicinity : clipRect.Bottom + PlotAreaVicinity; bool addedPreviousPoint = false; Point? previousPoint = null; DataPoint previousDataPoint = null; bool isPreviousPointInView = false; var renderPoints = new List<DataPoint>(); for (int i = 0; i < dataPoints.Count; i++) { var dataPoint = dataPoints[i]; var point = dataPoint.Center(); if (dataPoints[i].isEmpty || double.IsNaN(point.X) || double.IsNaN(point.Y)) { // Point is empty addedPreviousPoint = false; previousPoint = null; previousDataPoint = null; isPreviousPointInView = false; continue; } double position = isVertical ? point.X : point.Y; if (start <= position && position <= end) { // Point is inside the viewport if (!addedPreviousPoint && previousPoint.HasValue) { renderPoints.Add(previousDataPoint); } renderPoints.Add(dataPoint); addedPreviousPoint = true; isPreviousPointInView = true; } else { if (isPreviousPointInView) { // Point is not inside the viewport, but the previous point is renderPoints.Add(dataPoint); addedPreviousPoint = true; } else { // Both the current point and the previous point are not in the viewport bool lineIntersectsClipRect = false; if (previousPoint.HasValue) { double prevPosition = isVertical ? previousPoint.Value.X : previousPoint.Value.Y; position = isVertical ? point.X : point.Y; lineIntersectsClipRect = (prevPosition <= start && end <= position) || (position <= start && end <= prevPosition); } if (!addedPreviousPoint && lineIntersectsClipRect) { renderPoints.Add(previousDataPoint); } if (lineIntersectsClipRect) { renderPoints.Add(dataPoint); addedPreviousPoint = true; } else { addedPreviousPoint = false; } } isPreviousPointInView = false; } previousPoint = point; previousDataPoint = dataPoint; } return renderPoints; } } }
using AutoMapper; using SolarDigest.Api.Data; using SolarDigest.Api.Logging; using SolarDigest.Shared.Utils; using System; using System.Threading; using System.Threading.Tasks; namespace SolarDigest.Api.Repository { internal sealed class SolarDigestExceptionTable : SolarDigestTableBase, ISolarDigestExceptionTable { public override string TableName => $"{Helpers.GetAppVersionName()}_{Shared.Constants.Table.Exception}"; public SolarDigestExceptionTable(IMapper mapper, ISolarDigestLogger logger) : base(mapper, logger) { } public Task AddExceptionAsync(Exception exception, CancellationToken cancellationToken) { var entity = new ExceptionEntity { Message = exception.Message, StackTrace = exception.StackTrace }; return TableImpl.PutItemAsync(entity, cancellationToken); } } }
using Domain; namespace DataAccess { public interface IStudentRepository { void Save(Student toSave); } }
@model Fap.AspNetCore.ViewModel.FormViewModel <fap-form id="@Model.FormId" form-model="Model"></fap-form> <script> function entry(offerUid) { var entryUid = $("#frm-profile #Fid").val(); $.post(basePath + "/Recruit/Api/Entry", { offerUid: offerUid, entryUid: entryUid }, function (rv) { if (rv.success) { $.msg(rv.msg); } else { bootbox.alert(rv.msg); } }) } </script>
using System.Text.Json.Serialization; namespace SyntSky.GoodGame.Api.V4.Dto.Comments; public class DonatDto { [JsonPropertyName("objId")] [JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)] public long ChannelId { get; set; } [JsonPropertyName("level")] [JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)] public int Level { get; set; } [JsonPropertyName("key")] public string ChannelName { get; set; } = null!; }
using System.Threading; using System.Threading.Tasks; using System.Windows; using Microsoft.Win32; namespace fos.Workarounds; internal class RenderLoopFix { public static void Initialize() { SystemEvents.SessionSwitch += SystemEvents_SessionSwitch; SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged; } private static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e) { ApplyFix(); } private static void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e) { ApplyFix(); } public static void ApplyFix() { var mainWindow = WindowManager.MainWindow; mainWindow?.Show(); Task.Run(() => { Thread.Sleep(500); Application.Current.Dispatcher.Invoke(() => { if (mainWindow != null && mainWindow.Visibility == Visibility.Visible) mainWindow?.Hide(); }); }); } ~RenderLoopFix() { SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch; SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged; } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Collections.Generic; using TheArtOfDev.HtmlRenderer.Adapters; namespace TheArtOfDev.HtmlRenderer.Core.Entities { /// <summary> /// Raised when the user clicks on a link in the html. /// </summary> public sealed class HtmlContextMenuEventArgs : EventArgs { /// <summary> /// the link href that was clicked /// </summary> private readonly RContextMenu _contextMenu; /// <summary> /// Init. /// </summary> /// <param name="link">the context menu</param> public HtmlContextMenuEventArgs(RContextMenu contextMenu) { _contextMenu = contextMenu; } /// <summary> /// the context menu /// </summary> public RContextMenu ContextMenu { get { return _contextMenu; } } public override string ToString() { return string.Format("Context Menu: {0}", ContextMenu); } } }
using Crabtopus.Models; namespace Crabtopus.Services { internal interface ICardsService { Card GetById(int id); Card Get(string setCode, string collectorNumber); } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Blazored.LocalStorage; using Syncfusion.Blazor; using Microsoft.Extensions.Hosting; using Common.Web; using Common.Application; using System.Net.Http; using System; using Blazored.SessionStorage; using System.Collections.Generic; namespace Demo.Server { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://localhost:5000/") }); services.AddSignalR(e => { e.MaximumReceiveMessageSize = 102400000; }); services.AddRazorPages(); services.AddServerSideBlazor(); services.AddHttpClient(); services.AddCommonServices(); services.AddScoped<LoginService>(); services.AddScoped<DataService>(); } public static void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/Host"); }); } } }
using ConWinTer.Model; using ConWinTer.Utils; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace ConWinTer.Export { public class CsvTableExporter : ITableExporter { public string Separator { get; set; } public CsvTableExporter(string separator = ",") { Separator = separator; } public void Export(Table table, string path) { if (!IsSupportedFile(path)) throw new ArgumentException($"File '{path}' is not supported."); var writer = new StreamWriter(File.OpenWrite(path)); foreach (var row in table.AsRowsArray) writer.WriteLine(string.Join(Separator, row)); writer.Flush(); writer.Close(); } public IEnumerable<string> GetSupportedExtensions() { return new List<string> { ".csv" }; } public bool IsSupportedFile(string path) { return PathUtils.HasExtension(path, GetSupportedExtensions()); } } }
using System; using System.IO; namespace Proj4Net.Core.Datum.Grids { public class DatGridTableLoader : GridTableLoader { public DatGridTableLoader(Uri location) : base(location) { } internal override bool ReadHeader(GridTable table) { using (var stream = OpenGridTableStream()) { var header = new byte[176]; if (stream.Read(header, 0, 176) != 176) return false; table.LowerLeft = new PhiLambda { Phi = GetBigEndianDouble(header, 24), Lambda = -GetBigEndianDouble(header, 72) }; table.UpperRight = new PhiLambda { Phi = GetBigEndianDouble(header, 40), Lambda = -GetBigEndianDouble(header, 56) }; table.SizeOfGridCell = new PhiLambda { Phi = GetBigEndianDouble(header, 88), Lambda = -GetBigEndianDouble(header, 104) }; var size = table.UpperRight - table.LowerLeft; table.NumLambdas = (int) (Math.Abs(size.Lambda)/table.SizeOfGridCell.Lambda + 0.5) + 1; table.NumPhis = (int)(Math.Abs(size.Phi) / table.SizeOfGridCell.Phi + 0.5) + 1; table.LowerLeft = PhiLambda.DegreesToRadians(table.LowerLeft); table.UpperRight = PhiLambda.DegreesToRadians(table.UpperRight); table.SizeOfGridCell = PhiLambda.DegreesToRadians(table.SizeOfGridCell); return true; } } internal override bool ReadData(GridTable table) { using (var br = new BinaryReader(OpenGridTableStream())) { br.BaseStream.Seek(176, SeekOrigin.Current); var coeffs = new PhiLambda[table.NumPhis][]; for (var row = 0; row < table.NumPhis; row++) { coeffs[row] = new PhiLambda[table.NumLambdas]; // NTV order is flipped compared with a normal CVS table for (var col = table.NumLambdas - 1; col >= 0; col--) { const double degToArcSec = (Math.PI/180)/3600; // shift values are given in "arc-seconds" and need to be converted to radians. coeffs[row][col].Phi = ReadBigEndianDouble(br)*degToArcSec; coeffs[row][col].Lambda = ReadBigEndianDouble(br)*degToArcSec; } } table.Coefficients = coeffs; return true; } } } }
using System; using FlaUI.Core; namespace FlaUInspect.Core { public static class AutomationPropertyExtensions { public static string ToDisplayText<T>(this IAutomationProperty<T> automationProperty) { try { var success = automationProperty.TryGetValue(out T value); return success ? (value == null ? String.Empty : value.ToString()) : "Not Supported"; } catch (Exception ex) { return $"Exception getting value ({ex.HResult})"; } } } }
using System.Collections.Generic; namespace FlexibleCalculator.Calculator { public interface IReversePolishNotationAlgo { Token[] OrderTokens(IEnumerable<string> tokens); } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using MTBLogger.Data; using MTBLogger.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MTBLogger.Controllers { public class ToRideController : Controller { private readonly ApplicationDbContext _db; public ToRideController(ApplicationDbContext db) { _db = db; } public IActionResult Index() { return View(); } // GET - Create public IActionResult Create() { return View(); } // POST - Create [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(ToRide obj) { if(ModelState.IsValid) { obj.UserId = HttpContext.Session.GetInt32("UserId"); _db.ToRide.Add(obj); _db.SaveChanges(); return RedirectToAction("Index", "Home"); } return View(obj); } // GET - Edit public IActionResult Edit(int? id) { if (id == null) { return NotFound(); } var obj = _db.ToRide.Find(id); if(obj == null) { return NotFound(); } return View(obj); } // POST - Edit [HttpPost] [ValidateAntiForgeryToken] public IActionResult Edit(ToRide obj) { if(ModelState.IsValid) { obj.UserId = HttpContext.Session.GetInt32("UserId"); _db.ToRide.Update(obj); _db.SaveChanges(); return RedirectToAction("Index", "Home"); } return View(obj); } // GET - Delete public IActionResult Delete(int? id) { if(id == null) { return NotFound(); } var obj = _db.ToRide.Find(id); if(obj == null) { return NotFound(); } return View(obj); } // POST - Delete public IActionResult DeletePost(ToRide obj) { if(obj == null) { return NotFound(); } _db.ToRide.Remove(obj); _db.SaveChanges(); return RedirectToAction("Index", "Home"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Tactics.Models { public class UI : MonoBehaviour { public Material playerGradientMaterial; public Material enemyGradientMaterial; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class QuickConsoleToggler : MonoBehaviour { [SerializeField] ConsoleGUI console; [SerializeField] KeyCode toggleKey = KeyCode.Quote; public KeyCode ToggleKey => toggleKey; private void Update() { if (Input.GetKeyDown(toggleKey)) console.ToggleConsole(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChameleonLib.Resources { public class Constants { public const string PERIODIC_TASK_NAME = "VelostepChameleonPeriodicAgent"; //string resourceIntensiveTaskName = "ResourceIntensiveAgent"; public const string CHAMELEON_INSTALL_DTTM = "ChameleonInstallDttm"; public const string MUTEX_DATA = "MutexData"; public const string FACEBOOK_SUPPORT = "http://www.facebook.com/chameleonapp"; public const string EMAIL_SUPPORT = "appsupport@velostep.com"; public const string WEATHER_MAIN_CITY = "WeatherMainCity"; public const string WEATHER_ACCESS_TOKEN = "WeatherBugAccessToken"; public const string WEATHER_UNIT_TYPE = "WeatherSettingsUnitType"; public const string WEATHER_ICON_TYPE = "WeatherSettingsIconType"; public const string WEATHER_LOCATION_CONSENT = "LocationConsent"; public const string WEATHER_USE_LOCATION_SERVICES = "WeatherUseLocationServices"; public const string WEATHER_LIVE_RESULT = "WeatherLiveResult"; public const string WEATHER_FORECAST_RESULT = "WeatherForecastResult"; public const string LOCKSCREEN_IMAGE_POSTFIX = "_wowstuff_lockscreen.jpg"; public const string LOCKSCREEN_IMAGE_THUMNAIL_POSTFIX = "_wowstuff_lockscreen.thumb"; public const string LOCKSCREEN_IMAGE_READY_POSTFIX = "_wowstuff_lockscreen.ready"; public const string LOCKSCREEN_IMAGE_A_POSTFIX = "_wowstuff_lockscreen_A.jpg"; public const string LOCKSCREEN_IMAGE_B_POSTFIX = "_wowstuff_lockscreen_B.jpg"; public const int LOCKSCREEN_MAX_COUNT = 20; public const double FRAME_RATIO = 0.8; public const string PREFIX_APP_RESOURCE_FOLDER = "ms-appx:///"; public const string PREFIX_APP_DATA_FOLDER = "ms-appdata:///Local/"; public const string LOCKSCREEN_BACKGROUND_USE_SEPARATION = "LockscreenBackgroundSeparation"; public const string LOCKSCREEN_BACKGROUND_TEMPLATE = "LockscreenBackgroundTemplate"; public const string LOCKSCREEN_BACKGROUND_COLOR = "LockscreenBackgroundColor"; public const string LOCKSCREEN_BACKGROUND_OPACITY = "LockscreenBackgroundOpacity"; public const int LOCKSCREEN_BACKGROUND_DEFAULT_OPACITY = 20; public const string LOCKSCREEN_FONT_WEIGHT = "LockscreenFontWeight"; public const string LOCKSCREEN_UPDATE_INTERVAL = "LockscreenUpdateInterval"; public const string LOCKSCREEN_USE_ROTATOR = "LockscreenUseRatator"; public const string CALENDAR_FIRST_DAY_OF_WEEK = "CalendarFirstDayOfWeek"; public const string CALENDAR_SHOW_APPOINTMENT = "CalendarShowAppointment"; public const string COMMON_FIRST_PAGE_ITEM = "CommonFirstPageItem"; public const string BING_LANGUAGE_MARKET = "BingLanugageMarketplace"; public const string BING_SEARCH_OPTIONS = "BingSearchOptions"; public const string BING_SEARCH_SIZE = "BingSearchSize"; public const string BING_SEARCH_SIZE_WIDTH = "BingSearchSizeWidth"; public const string BING_SEARCH_SIZE_HEIGHT = "BingSearchSizeHeight"; public const string BING_SEARCH_SIZE_MIN_HEIGHT = "480"; public const string BING_SEARCH_SIZE_MIN_WIDTH = "480"; public const string BING_SEARCH_ASPECT = "BingSearchAspect"; public const string BING_SEARCH_COLOR = "BingSearchColor"; public const string BING_SEARCH_STYLE = "BingSearchStyle"; public const string BING_SEARCH_FACE = "BingSearchFace"; public const string BING_SEARCH_COUNT = "BingSearchCount"; public const string BING_SEARCH_ADULT = "BingSearchAdult"; public const string CHANGED_SETTINGS = "ChangedSettings"; public const string DOMAIN_FILTER = "DomainFilter"; public const string CHAMELEON_SKIN_BACKGROUND_COLOR = "ChameleonSkinBackgroundColor"; public const string CHAMELEON_USE_PROTECTIVE_COLOR = "ChameleonUseProtectiveColor"; public const string CHAMELEON_USE_PROTECTIVE_IMAGE = "ChameleonUseProtectiveImage"; public const string LIVETILE_UPDATE_INTERVAL = "LivetilesUpdateInterval"; public const string LIVETILE_CALENDAR_BACKGROUND_COLOR = "LivetileCalendarBackgroundColor"; public const string LIVETILE_WEATHER_BACKGROUND_COLOR = "LivetileWeatherBackgroundColor"; public const string LIVETILE_WEATHER_FONT_SIZE = "LivetileWeatherFontSize"; public const string LIVETILE_FONT_WEIGHT = "LivetileFontWeight"; public const string LIVETILE_BATTERY_BACKGROUND_COLOR = "LivetileBatteryBackgroundColor"; public const string LIVETILE_RANDOM_BACKGROUND_COLOR = "LivetileRandomBackgroundColor"; public const string LIVETILE_BATTERY_FULL_INDICATION = "LivetileBatteryFullIndication"; public const string DOWNLOAD_IMAGE_LIST = "DownloadImageList"; public const string LAST_RUN_LOCKSCREEN = "LastRunForLockscreen"; public const string LAST_RUN_LIVETILE = "LastRunForLivetile"; public const string FLASHLIGHT_USE_TOGGLE_SWITCH = "FlashlightUseToggleSwitch"; } }
using System.Threading.Tasks; using WT.Ecommerce.Domain.Models; namespace WT.Ecommerce.Services.Products { public interface IProductService { Task<ProductQueryResult> GetPaged(int limit, int skip,string name,int? categoryId); Task<ProductResponse> Create(ProductRequest input); Task<ProductImage> AddImage(string name, string description,int productId); Task RemoveImage(string name); } }
using Newtonsoft.Json; using System; namespace Panosen.Serialization.ElasticSearch { public class Range { [JsonProperty("name")] public string Name { get; set;} [JsonProperty("gt")] public long? GreaterThan { get; set;} [JsonProperty("gte")] public long? GreateEqualThan { get; set;} [JsonProperty("lt")] public long? LessThan { get; set;} [JsonProperty("lte")] public long? LessEqualThan { get; set;} [JsonProperty("from")] public long? From { get; set;} [JsonProperty("to")] public long? To { get; set;} [JsonProperty("boost")] public int? Boost { get; set;} [JsonProperty("include_lower")] public bool? IncludeLower { get; set;} [JsonProperty("include_upper")] public bool? IncludeUpper { get; set;} } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MS-PL license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel; using System.Linq.Expressions; namespace MvvmCross.ViewModels { public interface IMvxNotifyPropertyChanged : INotifyPropertyChanged { // this ShouldAlwaysRaiseInpcOnUserInterfaceThread is not a Property so as to avoid Inpc pollution bool ShouldAlwaysRaiseInpcOnUserInterfaceThread(); void ShouldAlwaysRaiseInpcOnUserInterfaceThread(bool value); void RaisePropertyChanged<T>(Expression<Func<T>> property); void RaisePropertyChanged(string whichProperty); void RaisePropertyChanged(PropertyChangedEventArgs changedArgs); } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace PsiCorps.BlackOmega.IdentityMap.InMemory { public class InMemoryIdentityMapEngine<TEntity, TId> : IIdentityMapEngine<TEntity, TId> where TEntity : class { // TODO: Data races (?) private readonly IDictionary<TId, TEntity> _map = new Dictionary<TId, TEntity>(); public Task<TEntity> GetById(TId id, CancellationToken ct) => Task.FromResult(_map.TryGetValue(id, out var entity) ? entity : null); public Task Update(TId id, TEntity result, CancellationToken ct) { _map[id] = result; return Task.CompletedTask; } public Task Invalidate(TId id, CancellationToken ct) { _map.Remove(id); return Task.CompletedTask; } } }
using System; using System.Runtime.InteropServices; using HAL.Base; // ReSharper disable RedundantAssignment // ReSharper disable InconsistentNaming #pragma warning disable 1591 namespace HAL.SimulatorHAL { ///<inheritdoc cref="HAL"/> internal class HALSerialPort { internal static void Initialize(IntPtr library, ILibraryLoader loader) { Base.HALSerialPort.SerialInitializePort = serialInitializePort; Base.HALSerialPort.SerialSetBaudRate = serialSetBaudRate; Base.HALSerialPort.SerialSetDataBits = serialSetDataBits; Base.HALSerialPort.SerialSetParity = serialSetParity; Base.HALSerialPort.SerialSetStopBits = serialSetStopBits; Base.HALSerialPort.SerialSetWriteMode = serialSetWriteMode; Base.HALSerialPort.SerialSetFlowControl = serialSetFlowControl; Base.HALSerialPort.SerialSetTimeout = serialSetTimeout; Base.HALSerialPort.SerialEnableTermination = serialEnableTermination; Base.HALSerialPort.SerialDisableTermination = serialDisableTermination; Base.HALSerialPort.SerialSetReadBufferSize = serialSetReadBufferSize; Base.HALSerialPort.SerialSetWriteBufferSize = serialSetWriteBufferSize; Base.HALSerialPort.SerialGetBytesReceived = serialGetBytesReceived; Base.HALSerialPort.SerialRead = serialRead; Base.HALSerialPort.SerialWrite = serialWrite; Base.HALSerialPort.SerialFlush = serialFlush; Base.HALSerialPort.SerialClear = serialClear; Base.HALSerialPort.SerialClose = serialClose; } /// Return Type: void ///port: byte ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialInitializePort")] [CalledSimFunction] public static extern void serialInitializePort(byte port, ref int status); /// Return Type: void ///port: byte ///baud: unsigned int ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialSetBaudRate")] [CalledSimFunction] public static extern void serialSetBaudRate(byte port, uint baud, ref int status); /// Return Type: void ///port: byte ///bits: byte ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialSetDataBits")] [CalledSimFunction] public static extern void serialSetDataBits(byte port, byte bits, ref int status); /// Return Type: void ///port: byte ///parity: byte ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialSetParity")] [CalledSimFunction] public static extern void serialSetParity(byte port, byte parity, ref int status); /// Return Type: void ///port: byte ///stopBits: byte ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialSetStopBits")] [CalledSimFunction] public static extern void serialSetStopBits(byte port, byte stopBits, ref int status); /// Return Type: void ///port: byte ///mode: byte ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialSetWriteMode")] [CalledSimFunction] public static extern void serialSetWriteMode(byte port, byte mode, ref int status); /// Return Type: void ///port: byte ///flow: byte ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialSetFlowControl")] [CalledSimFunction] public static extern void serialSetFlowControl(byte port, byte flow, ref int status); /// Return Type: void ///port: byte ///timeout: float ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialSetTimeout")] [CalledSimFunction] public static extern void serialSetTimeout(byte port, float timeout, ref int status); /// Return Type: void ///port: byte ///terminator: char ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialEnableTermination")] [CalledSimFunction] public static extern void serialEnableTermination(byte port, byte terminator, ref int status); /// Return Type: void ///port: byte ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialDisableTermination")] [CalledSimFunction] public static extern void serialDisableTermination(byte port, ref int status); /// Return Type: void ///port: byte ///size: unsigned int ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialSetReadBufferSize")] [CalledSimFunction] public static extern void serialSetReadBufferSize(byte port, uint size, ref int status); /// Return Type: void ///port: byte ///size: unsigned int ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialSetWriteBufferSize")] [CalledSimFunction] public static extern void serialSetWriteBufferSize(byte port, uint size, ref int status); /// Return Type: int ///port: byte ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialGetBytesReceived")] [CalledSimFunction] public static extern int serialGetBytesReceived(byte port, ref int status); /// Return Type: unsigned int ///port: byte ///buffer: char* ///count: int ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialRead")] [CalledSimFunction] public static extern uint serialRead(byte port, byte[] buffer, int count, ref int status); /// Return Type: unsigned int ///port: byte ///buffer: char* ///count: int ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialWrite")] [CalledSimFunction] public static extern uint serialWrite(byte port, byte[] buffer, int count, ref int status); /// Return Type: void ///port: byte ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialFlush")] [CalledSimFunction] public static extern void serialFlush(byte port, ref int status); /// Return Type: void ///port: byte ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialClear")] [CalledSimFunction] public static extern void serialClear(byte port, ref int status); /// Return Type: void ///port: byte ///status: int* [DllImport("libHALAthena_shared.so", EntryPoint = "serialClose")] [CalledSimFunction] public static extern void serialClose(byte port, ref int status); } }
using Xunit; namespace WebApiTests.Base { public class BaseServiceTests { [Fact] public void TestCreate() { Assert.Equal(4, 4); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Jtext103.EntityModel; namespace Jtext103.OldHouse.Business.Models { /// <summary> /// holds the info of a house /// </summary> public class House:Entity { /// <summary> /// the user guid whom added by /// </summary> public Guid OwnerId { get; set; } /// <summary> /// need register /// </summary> private double _overallValue; public string Name { get; set; } public string LocationString { get; set; } public string Country { get; set; } public string Province { get; set; } public string City { get; set; } public string Abstarct { get; set; } public string Description { get; set; } public string Condition { get; set; } public DateTime BuiltYear { get; set; } public double HistoricValue{ get; set; } public double PhotoValue { get; set; } public List<string> Images { get; set; } public List<string> Tags { get; set; } public string Cover { get; set; } /// <summary> /// a unique code name for a house, unlike the ID its's human readable /// /// </summary> public string CodeName { get; set; } public double OverallValue { get { return _overallValue; } internal set { _overallValue = value; } } public GeoPoint Location { get; set; } public House():base() { this.EntityType = "House"; } } }
using System.Windows; namespace TestStack.White { public class HorizontalSpan : Span { public HorizontalSpan(Rect bounds) : base(bounds.Left, bounds.Right) {} public virtual bool IsOutside(Rect rect) { return DoesntContain(rect, rect.Left, rect.Right); } } }
using System; namespace EmergencySituationSimulator2014.Model { public abstract class Person : Entity { public double Pv { get; protected set; } public double GoodHealtPv { get; protected set; } public double Age { get; protected set; } public double HealtStatus { get { return Pv/GoodHealtPv; } } public enum SexEnum { Woman, Man, Other } public SexEnum Sex { get; protected set; } protected Person() { GoodHealtPv = 100.0; Pv = Math.Max(Oracle.CreateNumber(100.0, 42.0), 10.0); Name = Oracle.CreatePersonName(); // Maybe I should rename the isFortunate method :P Sex = Oracle.IsFortunate() ? SexEnum.Woman : SexEnum.Man; Age = Oracle.CreateAge(); } public void Hit() { Pv = Math.Max(Pv+Math.Min(Oracle.CreateNumber(-30.0, 30.0), 0), 0); } } }
using System; namespace Com.Game.Data { [Serializable] public class SysShopItemVo { public string unikey; public int id; public int type; public string itemID; public int itemNum; public string itemPrice; public int MaxNumberOfPurchases; public int dailyPurchaseTimes; public int PurchaseTimes; public int onlyOne; public int weight; public int tag; public int IsSelling; public string StartTime; public string EndTime; public string icon; } }