content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// ------------------------------------------------------------------------------ // Copyright (c) 2015 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.OneDrive.Sdk { using System.Collections.Generic; /// <summary> /// The type SharedCollectionRequestBuilder. /// </summary> public partial class SharedCollectionRequestBuilder : BaseRequestBuilder, ISharedCollectionRequestBuilder { /// <summary> /// Constructs a new SharedCollectionRequestBuilder. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="oneDriveClient">The <see cref="IOneDriveClient"/> for handling requests.</param> public SharedCollectionRequestBuilder( string requestUrl, IOneDriveClient oneDriveClient) : base(requestUrl, oneDriveClient) { } /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> public ISharedCollectionRequest Request() { return this.Request(null); } /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> public ISharedCollectionRequest Request(IList<Option> options) { return new SharedCollectionRequest(this.RequestUrl, this.OneDriveClient, options); } /// <summary> /// Gets an <see cref="IItemRequestBuilder"/> for the specified Shared. /// </summary> /// <param name="id">The ID for the Shared.</param> /// <returns>The <see cref="IItemRequestBuilder"/>.</returns> public IItemRequestBuilder this[string id] { get { return new ItemRequestBuilder(this.AppendSegmentToRequestUrl(id), this.OneDriveClient); } } } }
41.794872
109
0.62362
[ "MIT" ]
jbatonnet/SmartSync
SmartSync.OneDrive/OneDriveSdk/Requests/Generated/SharedCollectionRequestBuilder.cs
3,260
C#
using System; using System.Linq; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Integration; using Microsoft.Bot.Builder.Integration.AspNet.Core; using Microsoft.Bot.Configuration; using Microsoft.Bot.Connector.Authentication; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace BackMeUp { public class Startup { private ILoggerFactory _loggerFactory; private bool _isProduction = false; public Startup(IHostingEnvironment env) { _isProduction = env.IsProduction(); var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { var secretKey = Configuration.GetSection("botFileSecret")?.Value; var botFilePath = Configuration.GetSection("botFilePath")?.Value; // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection. var botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", secretKey); services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot config file could not be loaded. ({botConfig})")); // Retrieve current endpoint. var environment = _isProduction ? "production" : "development"; ICredentialProvider credentialProvider = null; foreach (var service in botConfig.Services) { switch (service.Type) { case ServiceTypes.Endpoint: if (service is EndpointService endpointService) { credentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); } break; } } services.AddBot<BackMeUp>(opt => ConfigureBot<BackMeUp>(opt, credentialProvider, _loggerFactory)); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; app.UseDefaultFiles() .UseStaticFiles() .UseBotFramework(); } private static void ConfigureBot<T>(BotFrameworkOptions options, ICredentialProvider credentialProvider, ILoggerFactory loggerFactory) { // Set the CredentialProvider for the bot. It uses this to authenticate with the QnA service in Azure options.CredentialProvider = credentialProvider ?? throw new InvalidOperationException("Missing endpoint information from bot configuraiton file."); // Creates a logger for the application to use. ILogger logger = loggerFactory.CreateLogger<T>(); // Catches any errors that occur during a conversation turn and logs them. options.OnTurnError = async (context, exception) => { logger.LogError($"Exception caught : {exception}"); await context.SendActivityAsync("Sorry, it looks like something went wrong."); }; // The Memory Storage used here is for local bot debugging only. When the bot // is restarted, everything stored in memory will be gone. IStorage dataStore = new MemoryStorage(); // Create Conversation State object. // The Conversation State object is where we persist anything at the conversation-scope. var conversationState = new ConversationState(dataStore); options.State.Add(conversationState); } } }
40.951923
150
0.642874
[ "MIT" ]
InsightDI/BackMeUpBIAD
labs/lab2/start-here/BackMeUp/Startup.cs
4,261
C#
/* * Copyright 2019 Capnode AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using QuantConnect; using QuantConnect.Statistics; using System; using System.Collections.Generic; using System.Linq; namespace Algoloop.Wpf.ViewModel { public class TrackSymbolViewModel { readonly List<Trade> _trades = new (); private readonly Symbol _symbol; public TrackSymbolViewModel(Symbol symbol) { _symbol = symbol; } /// <summary> /// The symbol of the traded instrument /// </summary> public string Symbol => _symbol.Value; /// <summary> /// The market of the traded instrument /// </summary> public string Market => _symbol.ID.Market; /// <summary> /// The security type of the traded instrument /// </summary> public SecurityType Security => _symbol.ID.SecurityType; /// <summary> /// The type of the traded instrument /// </summary> public string Type => _symbol.SecurityType.ToString(); public decimal Score { get; private set; } /// <summary> /// Total profit to max drawdown ratio /// </summary> public decimal RoMaD { get; private set; } /// <summary> /// The number of trades /// </summary> public int Trades => _trades.Count; /// <summary> /// The gross profit/loss of the trades (as account currency) /// </summary> public decimal NetProfit { get; private set; } /// <summary> /// The maximum drawdown of the trades (as account currency) /// </summary> public decimal Drawdown { get; private set; } /// <summary> /// Longest drawdown period /// </summary> public TimeSpan DrawdownPeriod { get; private set; } public void AddTrade(Trade trade) { _trades.Add(trade); } public void Calculate() { if (_trades == null || !_trades.Any()) { return; } decimal netProfit = _trades.Sum(m => m.ProfitLoss - m.TotalFees); NetProfit = netProfit.RoundToSignificantDigits(2); // Calculate Return over Max Drawdown Ratio decimal drawdown = TrackViewModel.MaxDrawdown(_trades, out TimeSpan period); Drawdown = drawdown.RoundToSignificantDigits(2); DrawdownPeriod = period; decimal roMaD = drawdown == 0 ? 0 : netProfit / -drawdown; RoMaD = roMaD.RoundToSignificantDigits(4); // Calculate score double score = TrackViewModel.CalculateScore(_trades); Score = ((decimal)score).RoundToSignificantDigits(4); } } }
30.75
88
0.596808
[ "Apache-2.0" ]
Capnode/Algoloop
Algoloop.Wpf/ViewModel/TrackSymbolViewModel.cs
3,321
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using FluentAssertions; using Microsoft.NET.TestFramework.Assertions; using Microsoft.TemplateEngine.TestHelper; using Xunit.Abstractions; namespace Dotnet_new3.IntegrationTests { internal static class Helpers { internal static void InstallNuGetTemplate(string packageName, ITestOutputHelper log, string homeDirectory, string? workingDirectory = null) { DotnetNewCommand command = new DotnetNewCommand(log, "-i", packageName) .WithCustomHive(homeDirectory); if (!string.IsNullOrWhiteSpace(workingDirectory)) { command.WithWorkingDirectory(workingDirectory); } command.Execute() .Should() .ExitWith(0) .And .NotHaveStdErr(); } internal static string InstallTestTemplate(string templateName, ITestOutputHelper log, string homeDirectory, string? workingDirectory = null) { string testTemplate = TestUtils.GetTestTemplateLocation(templateName); DotnetNewCommand command = new DotnetNewCommand(log, "-i", testTemplate) .WithCustomHive(homeDirectory); if (!string.IsNullOrWhiteSpace(workingDirectory)) { command.WithWorkingDirectory(workingDirectory); } command.Execute() .Should() .ExitWith(0) .And .NotHaveStdErr(); return Path.GetFullPath(testTemplate); } } }
34.3
149
0.614577
[ "MIT" ]
JanKrivanek/templating
test/dotnet-new3.UnitTests/Helpers.cs
1,715
C#
#region License /* Copyright 2011, 2013, 2018 James F. Bellinger <http://www.zer7.com/software/hidsharp> 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. */ #endregion using System; using System.Collections.Generic; using HidSharp.Reports.Encodings; namespace HidSharp.Reports { // TODO: Make this public if anyone finds value in doing so. For now let's not lock ourselves in. sealed class ReportDescriptorParseState { public ReportDescriptorParseState() { RootItem = new DescriptorCollectionItem(); GlobalItemStateStack = new List<IDictionary<GlobalItemTag, EncodedItem>>(); LocalItemState = new List<KeyValuePair<LocalItemTag, uint>>(); Reset(); } public void Reset() { CurrentCollectionItem = RootItem; RootItem.ChildItems.Clear(); RootItem.CollectionType = 0; GlobalItemStateStack.Clear(); GlobalItemStateStack.Add(new Dictionary<GlobalItemTag, EncodedItem>()); LocalItemState.Clear(); } public EncodedItem GetGlobalItem(GlobalItemTag tag) { EncodedItem value; GlobalItemState.TryGetValue(tag, out value); return value; } public uint GetGlobalItemValue(GlobalItemTag tag) { EncodedItem item = GetGlobalItem(tag); return item != null ? item.DataValue : 0; } public bool IsGlobalItemSet(GlobalItemTag tag) { return GlobalItemState.ContainsKey(tag); } public DescriptorCollectionItem CurrentCollectionItem { get; set; } public DescriptorCollectionItem RootItem { get; private set; } public IDictionary<GlobalItemTag, EncodedItem> GlobalItemState { get { return GlobalItemStateStack[GlobalItemStateStack.Count - 1]; } } public IList<IDictionary<GlobalItemTag, EncodedItem>> GlobalItemStateStack { get; private set; } public IList<KeyValuePair<LocalItemTag, uint>> LocalItemState { get; private set; } } }
30.56383
102
0.604595
[ "ECL-2.0", "Apache-2.0" ]
vinogradniy/HidSharp
HidSharp/Reports/ReportDescriptorParseState.cs
2,875
C#
//----------------------------------------------------------------------------- // FILE: ChildWorkflowFuture.cs // CONTRIBUTOR: Jeff Lill // COPYRIGHT: Copyright (c) 2005-2022 by neonFORGE LLC. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Neon.Cadence; using Neon.Cadence.Internal; using Neon.Common; using Neon.Tasks; namespace Neon.Cadence { /// <summary> /// Implements a child workflow future that returns <c>void</c>. /// </summary> public class ChildWorkflowFuture : IAsyncFuture { private bool completed = false; private Workflow parentWorkflow; private ChildExecution childExecution; /// <summary> /// Constructor. /// </summary> /// <param name="parentWorkflow">Identifies the parent workflow context.</param> /// <param name="childExecution">The child workflow execution.</param> internal ChildWorkflowFuture(Workflow parentWorkflow, ChildExecution childExecution) { this.parentWorkflow = parentWorkflow; this.childExecution = childExecution; } /// <summary> /// Returns the workflow execution. /// </summary> public WorkflowExecution Execution => childExecution.Execution; /// <inheritdoc/> public async Task GetAsync() { await SyncContext.Clear; if (completed) { throw new InvalidOperationException($"[{nameof(IAsyncFuture<object>)}.GetAsync()] may only be called once per future stub instance."); } completed = true; await parentWorkflow.Client.GetChildWorkflowResultAsync(parentWorkflow, childExecution); } } /// <summary> /// Implements a child workflow future that returns a value. /// </summary> /// <typeparam name="TResult">The workflow result type.</typeparam> public class ChildWorkflowFuture<TResult> : IAsyncFuture<TResult> { private bool completed = false; private Workflow parentWorkflow; private ChildExecution childExecution; /// <summary> /// Constructor. /// </summary> /// <param name="parentWorkflow">Identifies the parent workflow context.</param> /// <param name="childExecution">The child workflow execution.</param> internal ChildWorkflowFuture(Workflow parentWorkflow, ChildExecution childExecution) { this.parentWorkflow = parentWorkflow; this.childExecution = childExecution; } /// <summary> /// Returns the workflow execution. /// </summary> public WorkflowExecution Execution => childExecution.Execution; /// <inheritdoc/> public async Task<TResult> GetAsync() { await SyncContext.Clear; if (completed) { throw new InvalidOperationException($"[{nameof(IAsyncFuture<object>)}.GetAsync()] may only be called once per future stub instance."); } completed = true; var resultBytes = await parentWorkflow.Client.GetChildWorkflowResultAsync(parentWorkflow, childExecution); return parentWorkflow.Client.DataConverter.FromData<TResult>(resultBytes); } } }
34.403361
150
0.635076
[ "Apache-2.0" ]
jefflill/neonKUBE
Lib/Neon.Cadence/ChildWorkflowFuture.cs
4,096
C#
using System; using System.Drawing; using System.Windows.Forms; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Messaging; using QuantConnect.Packets; //using Gecko; //using Gecko.JQuery; namespace QuantConnect.Views.WinForms { public partial class LeanWinForm : Form { private readonly WebBrowser _monoBrowser; private readonly AlgorithmNodePacket _job; private readonly QueueLogHandler _logging; private readonly EventMessagingHandler _messaging; //private GeckoWebBrowser _geckoBrowser; /// <summary> /// Create the UX. /// </summary> /// <param name="notificationHandler">Messaging system</param> /// <param name="job">Job to use for URL generation</param> public LeanWinForm(IMessagingHandler notificationHandler, AlgorithmNodePacket job) { InitializeComponent(); //Form Setup: CenterToScreen(); WindowState = FormWindowState.Maximized; Text = "QuantConnect Lean Algorithmic Trading Engine: v" + Globals.Version; //Save off the messaging event handler we need: _job = job; _messaging = (EventMessagingHandler)notificationHandler; var url = GetUrl(job); //GECKO WEB BROWSER: Create the browser control // https://www.nuget.org/packages/GeckoFX/ // -> If you don't have IE. //_geckoBrowser = new GeckoWebBrowser { Dock = DockStyle.Fill, Name = "browser" }; //_geckoBrowser.DOMContentLoaded += BrowserOnDomContentLoaded; //_geckoBrowser.Navigate(url); //splitPanel.Panel1.Controls.Add(_geckoBrowser); // MONO WEB BROWSER: Create the browser control // Default shipped with VS and Mono. Works OK in Windows, and compiles in linux. _monoBrowser = new WebBrowser() {Dock = DockStyle.Fill, Name = "Browser"}; _monoBrowser.DocumentCompleted += MonoBrowserOnDocumentCompleted; _monoBrowser.Navigate(url); splitPanel.Panel1.Controls.Add(_monoBrowser); //Setup Event Handlers: _messaging.DebugEvent += MessagingOnDebugEvent; _messaging.LogEvent += MessagingOnLogEvent; _messaging.RuntimeErrorEvent += MessagingOnRuntimeErrorEvent; _messaging.HandledErrorEvent += MessagingOnHandledErrorEvent; _messaging.BacktestResultEvent += MessagingOnBacktestResultEvent; _logging = Log.LogHandler as QueueLogHandler; //Show warnings if the API token and UID aren't set. if (_job.UserId == 0) { MessageBox.Show("Your user id is not set. Please check your config.json file 'job-user-id' property.", "LEAN Algorithmic Trading", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (_job.Channel == "") { MessageBox.Show("Your API token is not set. Please check your config.json file 'api-access-token' property.", "LEAN Algorithmic Trading", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// <summary> /// Get the URL for the embedded charting /// </summary> /// <param name="job">Job packet for the URL</param> /// <param name="liveMode">Is this a live mode chart?</param> /// <param name="holdReady">Hold the ready signal to inject data</param> private static string GetUrl(AlgorithmNodePacket job, bool liveMode = false, bool holdReady = false) { var url = ""; var hold = holdReady == false ? "0" : "1"; var embedPage = liveMode ? "embeddedLive" : "embedded"; url = string.Format( "https://www.quantconnect.com/terminal/{0}?user={1}&token={2}&pid={3}&version={4}&holdReady={5}&bid={6}", embedPage, job.UserId, job.Channel, job.ProjectId, Globals.Version, hold, job.AlgorithmId); return url; } /// <summary> /// MONO BROWSER: Browser content has completely loaded. /// </summary> private void MonoBrowserOnDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs webBrowserDocumentCompletedEventArgs) { _messaging.OnConsumerReadyEvent(); } /// <summary> /// GECKO BROWSER: Browser content has completely loaded. /// </summary> //private void BrowserOnDomContentLoaded(object sender, DomEventArgs domEventArgs) //{ // _messaging.OnConsumerReadyEvent(); //} /// <summary> /// Onload Form Initialization /// </summary> private void LeanWinForm_Load(object sender, EventArgs e) { if (OS.IsWindows && !WBEmulator.IsBrowserEmulationSet()) { WBEmulator.SetBrowserEmulationVersion(); } } /// <summary> /// Update the status label at the bottom of the form /// </summary> private void timer_Tick(object sender, EventArgs e) { StatisticsToolStripStatusLabel.Text = string.Concat("Performance: CPU: ", OS.CpuUsage.NextValue().ToString("0.0"), "%", " Ram: ", OS.TotalPhysicalMemoryUsed, " Mb"); if (_logging == null) return; LogEntry log; while (_logging.Logs.TryDequeue(out log)) { switch (log.MessageType) { case LogType.Debug: LogTextBox.AppendText(log.ToString(), Color.Black); break; default: case LogType.Trace: LogTextBox.AppendText(log.ToString(), Color.Black); break; case LogType.Error: LogTextBox.AppendText(log.ToString(), Color.DarkRed); break; } } } /// <summary> /// Backtest result packet /// </summary> /// <param name="packet"></param> private void MessagingOnBacktestResultEvent(BacktestResultPacket packet) { if (packet.Progress != 1) return; //Remove previous event handler: var url = GetUrl(_job, false, true); //Generate JSON: var jObj = new JObject(); var dateFormat = "yyyy-MM-dd HH:mm:ss"; dynamic final = jObj; final.dtPeriodStart = packet.PeriodStart.ToString(dateFormat); final.dtPeriodFinished = packet.PeriodFinish.AddDays(1).ToString(dateFormat); dynamic resultData = new JObject(); resultData.version = "3"; resultData.results = JObject.FromObject(packet.Results); resultData.statistics = JObject.FromObject(packet.Results.Statistics); resultData.iTradeableDates = 1; resultData.ranking = null; final.oResultData = resultData; var json = JsonConvert.SerializeObject(final); //GECKO RESULT SET: //_geckoBrowser.DOMContentLoaded += (sender, args) => //{ // var executor = new JQueryExecutor(_geckoBrowser.Window); // executor.ExecuteJQuery("window.jnBacktest = JSON.parse('" + json + "');"); // executor.ExecuteJQuery("$.holdReady(false)"); //}; //_geckoBrowser.Navigate(url); //MONO WEB BROWSER RESULT SET: _monoBrowser.DocumentCompleted += (sender, args) => { if (_monoBrowser.Document == null) return; _monoBrowser.Document.InvokeScript("eval", new object[] { "window.jnBacktest = JSON.parse('" + json + "');" }); _monoBrowser.Document.InvokeScript("eval", new object[] { "$.holdReady(false)" }); }; _monoBrowser.Navigate(url); foreach (var pair in packet.Results.Statistics) { _logging.Trace("STATISTICS:: " + pair.Key + " " + pair.Value); } } /// <summary> /// Display a handled error /// </summary> private void MessagingOnHandledErrorEvent(HandledErrorPacket packet) { var hstack = (!string.IsNullOrEmpty(packet.StackTrace) ? (Environment.NewLine + " " + packet.StackTrace) : string.Empty); _logging.Error(packet.Message + hstack); } /// <summary> /// Display a runtime error /// </summary> private void MessagingOnRuntimeErrorEvent(RuntimeErrorPacket packet) { var rstack = (!string.IsNullOrEmpty(packet.StackTrace) ? (Environment.NewLine + " " + packet.StackTrace) : string.Empty); _logging.Error(packet.Message + rstack); } /// <summary> /// Display a log packet /// </summary> private void MessagingOnLogEvent(LogPacket packet) { _logging.Trace(packet.Message); } /// <summary> /// Display a debug packet /// </summary> /// <param name="packet"></param> private void MessagingOnDebugEvent(DebugPacket packet) { _logging.Trace(packet.Message); } /// <summary> /// Closing the form exit the LEAN engine too. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void LeanWinForm_FormClosed(object sender, FormClosedEventArgs e) { Log.Trace("LeanWinForm(): Form closed."); Environment.Exit(0); } } }
39.512
198
0.574104
[ "Apache-2.0" ]
CircleOnCircles/Lean
UserInterface/WinForms/LeanWinForm.cs
9,880
C#
using System; namespace PrintDesignFinalizer.Engine { public class LambdaNodeVisitor : INodeVisitor { public LambdaNodeVisitor(Action<INode> nodeAction) { _nodeAction = nodeAction; } public void OnVisitNode(INode node) { _nodeAction(node); } private readonly Action<INode> _nodeAction; } }
15.85
52
0.735016
[ "MIT" ]
stu-smith/PrintDesignFinalizer
PrintDesignFinalizer/PrintDesignFinalizer.Engine/LambdaNodeVisitor.cs
319
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using MasteringEFCore.Transactions.Final.Data; using MasteringEFCore.Transactions.Final.Models; using Microsoft.AspNetCore.Authorization; using MasteringEFCore.Transactions.Final.ViewModels; using MasteringEFCore.Transactions.Final.Helpers; namespace MasteringEFCore.Transactions.Final.Controllers { //[Authorize] public class UsersController : Controller { private readonly BlogContext _context; public UsersController(BlogContext context) { _context = context; } public async Task<IActionResult> IsUsernameAvailable(string username) { var usernameAvailable = await _context.Users.AnyAsync(x => x.Username.Equals(username, StringComparison.OrdinalIgnoreCase)); return Json(data: !usernameAvailable ); } // GET: Users public async Task<IActionResult> Index() { return View(await _context.Users.ToListAsync()); } // GET: Users/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var user = await _context.Users .SingleOrDefaultAsync(m => m.Id == id); if (user == null) { return NotFound(); } return View(user); } // GET: Users/Create public IActionResult Create() { return View(); } // POST: Users/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,DisplayName,Username,PasswordHash,Email")] User user) { if (ModelState.IsValid) { _context.Add(user); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } return View(user); } // GET: Users/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var user = await _context.Users.SingleOrDefaultAsync(m => m.Id == id); if (user == null) { return NotFound(); } return View(user); } // POST: Users/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,DisplayName,Username,PasswordHash,Email")] User user) { if (id != user.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(user); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!UserExists(user.Id)) { return NotFound(); } else { throw; } } return RedirectToAction("Index"); } return View(user); } // GET: Users/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var user = await _context.Users .SingleOrDefaultAsync(m => m.Id == id); if (user == null) { return NotFound(); } return View(user); } // POST: Users/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var user = await _context.Users.SingleOrDefaultAsync(m => m.Id == id); _context.Users.Remove(user); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } public IActionResult Register() { return View(); } public async Task<IActionResult> Register(RegistrationViewModel registrationViewModel) { var user = new User { Username = registrationViewModel.Username, Email = registrationViewModel.Email, PasswordHash = Cryptography.Instance.HashPassword(registrationViewModel.Password) }; if (TryValidateModel(user)) { await _context.Users.AddAsync(user); ViewBag.Message = "User created successfully"; return RedirectToAction("Index"); } else { ViewBag.Message = "Error occurred while validating the user"; } return View(user); } private bool UserExists(int id) { return _context.Users.Any(e => e.Id == id); } } }
29.530928
117
0.519986
[ "MIT" ]
PacktPublishing/Mastering-Entity-Framework-Core
Chapter 9/Final/MasteringEFCore.Transactions.Final/Controllers/UsersController.cs
5,729
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 09.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete2__objs.NullableSByte.NullableSByte{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.SByte>; using T_DATA2 =System.Nullable<System.SByte>; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__03__NV public static class TestSet_504__param__03__NV { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => ((object)vv1) /*OP{*/ == /*}OP*/ ((object)vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=4; var recs=db.testTable.Where(r => !(((object)vv1) /*OP{*/ == /*}OP*/ ((object)vv2))); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 };//class TestSet_504__param__03__NV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete2__objs.NullableSByte.NullableSByte
26.613139
147
0.532364
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/Equal/Complete2__objs/NullableSByte/NullableSByte/TestSet_504__param__03__NV.cs
3,648
C#
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using Conditions; using Config; /// <summary> /// Filtering rule for <see cref="PostFilteringTargetWrapper"/>. /// </summary> [NLogConfigurationItem] public class FilteringRule { /// <summary> /// Initializes a new instance of the FilteringRule class. /// </summary> public FilteringRule() : this(null, null) { } /// <summary> /// Initializes a new instance of the FilteringRule class. /// </summary> /// <param name="whenExistsExpression">Condition to be tested against all events.</param> /// <param name="filterToApply">Filter to apply to all log events when the first condition matches any of them.</param> public FilteringRule(ConditionExpression whenExistsExpression, ConditionExpression filterToApply) { Exists = whenExistsExpression; Filter = filterToApply; } /// <summary> /// Gets or sets the condition to be tested. /// </summary> /// <docgen category='Filtering Options' order='10' /> [RequiredParameter] public ConditionExpression Exists { get; set; } /// <summary> /// Gets or sets the resulting filter to be applied when the condition matches. /// </summary> /// <docgen category='Filtering Options' order='10' /> [RequiredParameter] public ConditionExpression Filter { get; set; } } }
40.316456
127
0.681947
[ "BSD-3-Clause" ]
AlanLiu90/NLog
src/NLog/Targets/Wrappers/FilteringRule.cs
3,185
C#
using System; using System.Runtime.Serialization; namespace Stringier.Patterns { /// <summary> /// Thrown when a Consume failed to match /// </summary> [Serializable] public sealed class ConsumeFailedException : ParserException { public ConsumeFailedException() { } public ConsumeFailedException(String message) : base(message) { } public ConsumeFailedException(String message, Exception inner) : base(message, inner) { } private ConsumeFailedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
29.052632
108
0.757246
[ "BSD-3-Clause" ]
HugoRoss/Stringier
Patterns/Exceptions/ConsumeFailedException.cs
554
C#
using System; using System.Xml.Linq; using Umbraco.Core.Logging; using uSync8.Core; using uSync8.Core.Extensions; using uSync8.Core.Models; using uSync8.Core.Serialization; using Vendr.Core; using Vendr.Core.Api; using Vendr.Core.Models; using Vendr.uSync.Extensions; namespace Vendr.uSync.Serializers { [SyncSerializer("FA15B3E1-8100-431E-BC95-4B74134A42DD", "OrderStatus Serializer", VendrConstants.Serialization.OrderStatus)] public class OrderStatusSerializer : VendrSerializerBase<OrderStatusReadOnly>, ISyncSerializer<OrderStatusReadOnly> { public OrderStatusSerializer(IVendrApi vendrApi, IUnitOfWorkProvider uowProvider, ILogger logger) : base(vendrApi, uowProvider, logger) { } protected override SyncAttempt<XElement> SerializeCore(OrderStatusReadOnly item, SyncSerializerOptions options) { var node = InitializeBaseNode(item, ItemAlias(item)); node.Add(new XElement(nameof(item.Name), item.Name)); node.Add(new XElement(nameof(item.SortOrder), item.SortOrder)); node.AddStoreId(item.StoreId); node.Add(new XElement(nameof(item.Color), item.Color)); return SyncAttempt<XElement>.SucceedIf(node != null, item.Name, node, ChangeType.Export); } public override bool IsValid(XElement node) => base.IsValid(node) && node.GetStoreId() != Guid.Empty; protected override SyncAttempt<OrderStatusReadOnly> DeserializeCore(XElement node, SyncSerializerOptions options) { var readonlyItem = FindItem(node); var alias = node.GetAlias(); var id = node.GetKey(); var name = node.Element(nameof(readonlyItem.Name)).ValueOrDefault(alias); var storeId = node.GetStoreId(); using (var uow = _uowProvider.Create()) { OrderStatus item; if (readonlyItem == null) { item = OrderStatus.Create(uow, id, storeId, alias, name); } else { item = readonlyItem.AsWritable(uow); item.SetAlias(alias) .SetName(name); } item.SetColor(node.Element(nameof(item.Color)).ValueOrDefault(item.Color)); item.SetSortOrder(node.Element(nameof(item.SortOrder)).ValueOrDefault(item.SortOrder)); _vendrApi.SaveOrderStatus(item); uow.Complete(); return SyncAttempt<OrderStatusReadOnly>.Succeed(name, item.AsReadOnly(), ChangeType.Import); } } protected override void DeleteItem(OrderStatusReadOnly item) => _vendrApi.DeleteOrderStatus(item.Id); protected override OrderStatusReadOnly FindItem(Guid key) => _vendrApi.GetOrderStatus(key); protected override string ItemAlias(OrderStatusReadOnly item) => item.Alias; protected override void SaveItem(OrderStatusReadOnly item) { using (var uow = _uowProvider.Create()) { var entity = item.AsWritable(uow); _vendrApi.SaveOrderStatus(entity); uow.Complete(); } } } }
34.697917
128
0.616331
[ "MIT" ]
Xanashi/vendr-usync
src/Vendr.uSync/Serializers/OrderStatusSerializer.cs
3,333
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace server.Migrations { public partial class initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Tasks", columns: table => new { Name = table.Column<string>(type: "text", nullable: false), Color = table.Column<string>(type: "text", nullable: false), Precidence = table.Column<int>(type: "integer", nullable: false), Interval = table.Column<int>(type: "integer", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Tasks", x => x.Name); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Tasks"); } } }
32.612903
85
0.51731
[ "MIT" ]
isnakolah/Event-Tracker-System
server/Migrations/20210126045703_initial.cs
1,013
C#
using EPiServer.Personalization.Commerce.Tracking; using System.Collections.Generic; namespace Foundation.Features.CatalogContent.Package { public class GenericPackageViewModel : PackageViewModelBase<GenericPackage>, IEntryViewModelBase { public GenericPackageViewModel() { } public GenericPackageViewModel(GenericPackage fashionPackage) : base(fashionPackage) { } //public ReviewsViewModel Reviews { get; set; } public IEnumerable<Recommendation> AlternativeProducts { get; set; } public IEnumerable<Recommendation> CrossSellProducts { get; set; } } }
30.52381
100
0.714509
[ "Apache-2.0" ]
palle-mertz-merkle/Foundation
src/Foundation/Features/CatalogContent/Package/GenericPackageViewModel.cs
643
C#
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Reactor.EventsClient.Helpers; using System; using System.Collections.Generic; using System.Text; namespace Reactor.EventsClient.Models.Enums { [JsonConverter(typeof(EventTypeConverter))] public enum EventType { Demo, DiversityInclusion, ExecFilming, HackfestHackathon, MeetingExecutives, MeetingPartners, Meetup, OpenHack, Other, ScaleUpEvent } }
19.576923
47
0.671906
[ "MIT" ]
MikeCodesDotNET/Reactor-Events-API
Reactor.Models/Models/Enums/EventType.cs
511
C#
using Abp.Authorization; using Lpb.WebPortal.Authorization.Roles; using Lpb.WebPortal.Authorization.Users; namespace Lpb.WebPortal.Authorization { public class PermissionChecker : PermissionChecker<Role, User> { public PermissionChecker(UserManager userManager) : base(userManager) { } } }
22.666667
66
0.7
[ "Apache-2.0" ]
lpb243310820/MicroservicesDemo
Lpb.WebPortal/Lpb.WebPortal.Core/Authorization/PermissionChecker.cs
342
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using AspxCommerce.Core; using AspxCommerce.MegaCategory; /// <summary> /// Summary description for MegaCategoryWebService /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class MegaCategoryWebService : System.Web.Services.WebService { public MegaCategoryWebService() { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] public MegaCategorySettingInfo GetMegaCategorySetting(AspxCommonInfo aspxCommonObj) { try { MegaCategoryController mega = new MegaCategoryController(); MegaCategorySettingInfo lstGetMegaCategorySetting = mega.GetMegaCategorySetting(aspxCommonObj); return lstGetMegaCategorySetting; } catch (Exception ex) { throw ex; } } [WebMethod] public List<MegaCategorySettingInfo> MegaCategorySettingUpdate(string SettingValues, string SettingKeys, AspxCommonInfo aspxCommonObj) { try { MegaCategoryController mega = new MegaCategoryController(); List<MegaCategorySettingInfo> lstGetMegaCategorySetting = mega.MegaCategorySettingUpdate(SettingValues, SettingKeys, aspxCommonObj); return lstGetMegaCategorySetting; } catch (Exception ex) { throw ex; } } }
29.169492
144
0.694945
[ "MIT" ]
AspxCommerce/AspxCommerce2.7
AspxCommerce.MegaCategory/MegaCategoryWebService.cs
1,723
C#
using System; using System.Collections.Generic; using System.Data; namespace BarcodeLib.Symbologies { /// <summary> /// Code 128 encoding /// Written by: Brad Barnhill /// </summary> class Code128 : BarcodeCommon, IBarcode { public static readonly char FNC1 = Convert.ToChar(200); public static readonly char FNC2 = Convert.ToChar(201); public static readonly char FNC3 = Convert.ToChar(202); public static readonly char FNC4 = Convert.ToChar(203); public enum TYPES : int { DYNAMIC, A, B, C }; private readonly DataTable C128_Code = new DataTable("C128"); private List<string> _FormattedData = new List<string>(); private List<string> _EncodedData = new List<string>(); private DataRow _startCharacter; private TYPES type = TYPES.DYNAMIC; /// <summary> /// Encodes data in Code128 format. /// </summary> /// <param name="input">Data to encode.</param> public Code128(string input) { Raw_Data = input; }//Code128 /// <summary> /// Encodes data in Code128 format. /// </summary> /// <param name="input">Data to encode.</param> /// <param name="type">Type of encoding to lock to. (Code 128A, Code 128B, Code 128C)</param> public Code128(string input, TYPES type) { this.type = type; Raw_Data = input; }//Code128 private string Encode_Code128() { //initialize datastructure to hold encoding information init_Code128(); return GetEncoding(); }//Encode_Code128 private void init_Code128() { //set the table to case sensitive since there are upper and lower case values C128_Code.CaseSensitive = true; //set up columns C128_Code.Columns.Add("Value", typeof(string)); C128_Code.Columns.Add("A", typeof(string)); C128_Code.Columns.Add("B", typeof(string)); C128_Code.Columns.Add("C", typeof(string)); C128_Code.Columns.Add("Encoding", typeof(string)); //populate data C128_Code.Rows.Add(new object[] { "0", " ", " ", "00", "11011001100" }); C128_Code.Rows.Add(new object[] { "1", "!", "!", "01", "11001101100" }); C128_Code.Rows.Add(new object[] { "2", "\"", "\"", "02", "11001100110" }); C128_Code.Rows.Add(new object[] { "3", "#", "#", "03", "10010011000" }); C128_Code.Rows.Add(new object[] { "4", "$", "$", "04", "10010001100" }); C128_Code.Rows.Add(new object[] { "5", "%", "%", "05", "10001001100" }); C128_Code.Rows.Add(new object[] { "6", "&", "&", "06", "10011001000" }); C128_Code.Rows.Add(new object[] { "7", "'", "'", "07", "10011000100" }); C128_Code.Rows.Add(new object[] { "8", "(", "(", "08", "10001100100" }); C128_Code.Rows.Add(new object[] { "9", ")", ")", "09", "11001001000" }); C128_Code.Rows.Add(new object[] { "10", "*", "*", "10", "11001000100" }); C128_Code.Rows.Add(new object[] { "11", "+", "+", "11", "11000100100" }); C128_Code.Rows.Add(new object[] { "12", ",", ",", "12", "10110011100" }); C128_Code.Rows.Add(new object[] { "13", "-", "-", "13", "10011011100" }); C128_Code.Rows.Add(new object[] { "14", ".", ".", "14", "10011001110" }); C128_Code.Rows.Add(new object[] { "15", "/", "/", "15", "10111001100" }); C128_Code.Rows.Add(new object[] { "16", "0", "0", "16", "10011101100" }); C128_Code.Rows.Add(new object[] { "17", "1", "1", "17", "10011100110" }); C128_Code.Rows.Add(new object[] { "18", "2", "2", "18", "11001110010" }); C128_Code.Rows.Add(new object[] { "19", "3", "3", "19", "11001011100" }); C128_Code.Rows.Add(new object[] { "20", "4", "4", "20", "11001001110" }); C128_Code.Rows.Add(new object[] { "21", "5", "5", "21", "11011100100" }); C128_Code.Rows.Add(new object[] { "22", "6", "6", "22", "11001110100" }); C128_Code.Rows.Add(new object[] { "23", "7", "7", "23", "11101101110" }); C128_Code.Rows.Add(new object[] { "24", "8", "8", "24", "11101001100" }); C128_Code.Rows.Add(new object[] { "25", "9", "9", "25", "11100101100" }); C128_Code.Rows.Add(new object[] { "26", ":", ":", "26", "11100100110" }); C128_Code.Rows.Add(new object[] { "27", ";", ";", "27", "11101100100" }); C128_Code.Rows.Add(new object[] { "28", "<", "<", "28", "11100110100" }); C128_Code.Rows.Add(new object[] { "29", "=", "=", "29", "11100110010" }); C128_Code.Rows.Add(new object[] { "30", ">", ">", "30", "11011011000" }); C128_Code.Rows.Add(new object[] { "31", "?", "?", "31", "11011000110" }); C128_Code.Rows.Add(new object[] { "32", "@", "@", "32", "11000110110" }); C128_Code.Rows.Add(new object[] { "33", "A", "A", "33", "10100011000" }); C128_Code.Rows.Add(new object[] { "34", "B", "B", "34", "10001011000" }); C128_Code.Rows.Add(new object[] { "35", "C", "C", "35", "10001000110" }); C128_Code.Rows.Add(new object[] { "36", "D", "D", "36", "10110001000" }); C128_Code.Rows.Add(new object[] { "37", "E", "E", "37", "10001101000" }); C128_Code.Rows.Add(new object[] { "38", "F", "F", "38", "10001100010" }); C128_Code.Rows.Add(new object[] { "39", "G", "G", "39", "11010001000" }); C128_Code.Rows.Add(new object[] { "40", "H", "H", "40", "11000101000" }); C128_Code.Rows.Add(new object[] { "41", "I", "I", "41", "11000100010" }); C128_Code.Rows.Add(new object[] { "42", "J", "J", "42", "10110111000" }); C128_Code.Rows.Add(new object[] { "43", "K", "K", "43", "10110001110" }); C128_Code.Rows.Add(new object[] { "44", "L", "L", "44", "10001101110" }); C128_Code.Rows.Add(new object[] { "45", "M", "M", "45", "10111011000" }); C128_Code.Rows.Add(new object[] { "46", "N", "N", "46", "10111000110" }); C128_Code.Rows.Add(new object[] { "47", "O", "O", "47", "10001110110" }); C128_Code.Rows.Add(new object[] { "48", "P", "P", "48", "11101110110" }); C128_Code.Rows.Add(new object[] { "49", "Q", "Q", "49", "11010001110" }); C128_Code.Rows.Add(new object[] { "50", "R", "R", "50", "11000101110" }); C128_Code.Rows.Add(new object[] { "51", "S", "S", "51", "11011101000" }); C128_Code.Rows.Add(new object[] { "52", "T", "T", "52", "11011100010" }); C128_Code.Rows.Add(new object[] { "53", "U", "U", "53", "11011101110" }); C128_Code.Rows.Add(new object[] { "54", "V", "V", "54", "11101011000" }); C128_Code.Rows.Add(new object[] { "55", "W", "W", "55", "11101000110" }); C128_Code.Rows.Add(new object[] { "56", "X", "X", "56", "11100010110" }); C128_Code.Rows.Add(new object[] { "57", "Y", "Y", "57", "11101101000" }); C128_Code.Rows.Add(new object[] { "58", "Z", "Z", "58", "11101100010" }); C128_Code.Rows.Add(new object[] { "59", "[", "[", "59", "11100011010" }); C128_Code.Rows.Add(new object[] { "60", @"\", @"\", "60", "11101111010" }); C128_Code.Rows.Add(new object[] { "61", "]", "]", "61", "11001000010" }); C128_Code.Rows.Add(new object[] { "62", "^", "^", "62", "11110001010" }); C128_Code.Rows.Add(new object[] { "63", "_", "_", "63", "10100110000" }); C128_Code.Rows.Add(new object[] { "64", "\0", "`", "64", "10100001100" }); C128_Code.Rows.Add(new object[] { "65", Convert.ToChar(1).ToString(), "a", "65", "10010110000" }); C128_Code.Rows.Add(new object[] { "66", Convert.ToChar(2).ToString(), "b", "66", "10010000110" }); C128_Code.Rows.Add(new object[] { "67", Convert.ToChar(3).ToString(), "c", "67", "10000101100" }); C128_Code.Rows.Add(new object[] { "68", Convert.ToChar(4).ToString(), "d", "68", "10000100110" }); C128_Code.Rows.Add(new object[] { "69", Convert.ToChar(5).ToString(), "e", "69", "10110010000" }); C128_Code.Rows.Add(new object[] { "70", Convert.ToChar(6).ToString(), "f", "70", "10110000100" }); C128_Code.Rows.Add(new object[] { "71", Convert.ToChar(7).ToString(), "g", "71", "10011010000" }); C128_Code.Rows.Add(new object[] { "72", Convert.ToChar(8).ToString(), "h", "72", "10011000010" }); C128_Code.Rows.Add(new object[] { "73", Convert.ToChar(9).ToString(), "i", "73", "10000110100" }); C128_Code.Rows.Add(new object[] { "74", Convert.ToChar(10).ToString(), "j", "74", "10000110010" }); C128_Code.Rows.Add(new object[] { "75", Convert.ToChar(11).ToString(), "k", "75", "11000010010" }); C128_Code.Rows.Add(new object[] { "76", Convert.ToChar(12).ToString(), "l", "76", "11001010000" }); C128_Code.Rows.Add(new object[] { "77", Convert.ToChar(13).ToString(), "m", "77", "11110111010" }); C128_Code.Rows.Add(new object[] { "78", Convert.ToChar(14).ToString(), "n", "78", "11000010100" }); C128_Code.Rows.Add(new object[] { "79", Convert.ToChar(15).ToString(), "o", "79", "10001111010" }); C128_Code.Rows.Add(new object[] { "80", Convert.ToChar(16).ToString(), "p", "80", "10100111100" }); C128_Code.Rows.Add(new object[] { "81", Convert.ToChar(17).ToString(), "q", "81", "10010111100" }); C128_Code.Rows.Add(new object[] { "82", Convert.ToChar(18).ToString(), "r", "82", "10010011110" }); C128_Code.Rows.Add(new object[] { "83", Convert.ToChar(19).ToString(), "s", "83", "10111100100" }); C128_Code.Rows.Add(new object[] { "84", Convert.ToChar(20).ToString(), "t", "84", "10011110100" }); C128_Code.Rows.Add(new object[] { "85", Convert.ToChar(21).ToString(), "u", "85", "10011110010" }); C128_Code.Rows.Add(new object[] { "86", Convert.ToChar(22).ToString(), "v", "86", "11110100100" }); C128_Code.Rows.Add(new object[] { "87", Convert.ToChar(23).ToString(), "w", "87", "11110010100" }); C128_Code.Rows.Add(new object[] { "88", Convert.ToChar(24).ToString(), "x", "88", "11110010010" }); C128_Code.Rows.Add(new object[] { "89", Convert.ToChar(25).ToString(), "y", "89", "11011011110" }); C128_Code.Rows.Add(new object[] { "90", Convert.ToChar(26).ToString(), "z", "90", "11011110110" }); C128_Code.Rows.Add(new object[] { "91", Convert.ToChar(27).ToString(), "{", "91", "11110110110" }); C128_Code.Rows.Add(new object[] { "92", Convert.ToChar(28).ToString(), "|", "92", "10101111000" }); C128_Code.Rows.Add(new object[] { "93", Convert.ToChar(29).ToString(), "}", "93", "10100011110" }); C128_Code.Rows.Add(new object[] { "94", Convert.ToChar(30).ToString(), "~", "94", "10001011110" }); C128_Code.Rows.Add(new object[] { "95", Convert.ToChar(31).ToString(), Convert.ToChar(127).ToString(), "95", "10111101000" }); C128_Code.Rows.Add(new object[] { "96", FNC3, FNC3, "96", "10111100010" }); C128_Code.Rows.Add(new object[] { "97", FNC2, FNC2, "97", "11110101000" }); C128_Code.Rows.Add(new object[] { "98", "SHIFT", "SHIFT", "98", "11110100010" }); C128_Code.Rows.Add(new object[] { "99", "CODE_C", "CODE_C", "99", "10111011110" }); C128_Code.Rows.Add(new object[] { "100", "CODE_B", FNC4, "CODE_B", "10111101110" }); C128_Code.Rows.Add(new object[] { "101", FNC4, "CODE_A", "CODE_A", "11101011110" }); C128_Code.Rows.Add(new object[] { "102", FNC1, FNC1, FNC1, "11110101110" }); C128_Code.Rows.Add(new object[] { "103", "START_A", "START_A", "START_A", "11010000100" }); C128_Code.Rows.Add(new object[] { "104", "START_B", "START_B", "START_B", "11010010000" }); C128_Code.Rows.Add(new object[] { "105", "START_C", "START_C", "START_C", "11010011100" }); C128_Code.Rows.Add(new object[] { string.Empty, "STOP", "STOP", "STOP", "11000111010" }); }//init_Code128 private List<DataRow> FindStartorCodeCharacter(string s, ref int col) { var rows = new List<DataRow>(); //if two chars are numbers (or FNC1) then START_C or CODE_C if (s.Length > 1 && (Char.IsNumber(s[0]) || s[0] == FNC1) && (Char.IsNumber(s[1]) || s[1] == FNC1)) { if (_startCharacter == null) { _startCharacter = C128_Code.Select("A = 'START_C'")[0]; rows.Add(_startCharacter); }//if else rows.Add(C128_Code.Select("A = 'CODE_C'")[0]); col = 1; }//if else { var AFound = false; var BFound = false; foreach (DataRow row in C128_Code.Rows) { try { if (!AFound && s == row["A"].ToString()) { AFound = true; col = 2; if (_startCharacter == null) { _startCharacter = C128_Code.Select("A = 'START_A'")[0]; rows.Add(_startCharacter); }//if else { rows.Add(C128_Code.Select("B = 'CODE_A'")[0]);//first column is FNC4 so use B }//else }//if else if (!BFound && s == row["B"].ToString()) { BFound = true; col = 1; if (_startCharacter == null) { _startCharacter = C128_Code.Select("A = 'START_B'")[0]; rows.Add(_startCharacter); }//if else rows.Add(C128_Code.Select("A = 'CODE_B'")[0]); }//else else if (AFound && BFound) break; }//try catch (Exception ex) { Error("EC128-1: " + ex.Message); }//catch }//foreach if (rows.Count <= 0) Error("EC128-2: Could not determine start character."); }//else return rows; } private string CalculateCheckDigit() { var currentStartChar = _FormattedData[0]; uint checkSum = 0; for (uint i = 0; i < _FormattedData.Count; i++) { //replace apostrophes with double apostrophes for escape chars var s = _FormattedData[(int)i].Replace("'", "''"); //try to find value in the A column var rows = C128_Code.Select("A = '" + s + "'"); //try to find value in the B column if (rows.Length <= 0) rows = C128_Code.Select("B = '" + s + "'"); //try to find value in the C column if (rows.Length <= 0) rows = C128_Code.Select("C = '" + s + "'"); var value = UInt32.Parse(rows[0]["Value"].ToString()); var addition = value * ((i == 0) ? 1 : i); checkSum += addition; }//for var remainder = (checkSum % 103); var retRows = C128_Code.Select("Value = '" + remainder.ToString() + "'"); return retRows[0]["Encoding"].ToString(); } private void BreakUpDataForEncoding() { var temp = string.Empty; var tempRawData = Raw_Data; //breaking the raw data up for code A and code B will mess up the encoding switch (type) { case TYPES.A: case TYPES.B: { foreach (var c in Raw_Data) _FormattedData.Add(c.ToString()); return; } case TYPES.C: { var indexOfFirstNumeric = -1; var numericCount = 0; for (var x = 0; x < RawData.Length; x++) { var c = RawData[x]; if (Char.IsNumber(c)) { numericCount++; if (indexOfFirstNumeric == -1) { indexOfFirstNumeric = x; } } else if (c != FNC1) { Error("EC128-6: Only numeric values can be encoded with C128-C (Invalid char at position " + x + ")."); } } //CODE C: adds a 0 to the front of the Raw_Data if the length is not divisible by 2 if (numericCount % 2 == 1) tempRawData = tempRawData.Insert(indexOfFirstNumeric, "0"); break; } } foreach (var c in tempRawData) { if (Char.IsNumber(c)) { if (temp == string.Empty) { temp += c; }//if else { temp += c; _FormattedData.Add(temp); temp = string.Empty; }//else }//if else { if (temp != string.Empty) { _FormattedData.Add(temp); temp = string.Empty; }//if _FormattedData.Add(c.ToString()); }//else }//foreach //if something is still in temp go ahead and push it onto the queue if (temp != string.Empty) { _FormattedData.Add(temp); temp = string.Empty; }//if } private void InsertStartandCodeCharacters() { DataRow CurrentCodeSet = null; var CurrentCodeString = string.Empty; if (type != TYPES.DYNAMIC) { switch (type) { case TYPES.A: _FormattedData.Insert(0, "START_A"); break; case TYPES.B: _FormattedData.Insert(0, "START_B"); break; case TYPES.C: _FormattedData.Insert(0, "START_C"); break; default: Error("EC128-4: Unknown start type in fixed type encoding."); break; } }//if else { try { for (var i = 0; i < (_FormattedData.Count); i++) { var col = 0; var tempStartChars = FindStartorCodeCharacter(_FormattedData[i], ref col); //check all the start characters and see if we need to stay with the same codeset or if a change of sets is required var sameCodeSet = false; foreach (var row in tempStartChars) { if (row["A"].ToString().EndsWith(CurrentCodeString) || row["B"].ToString().EndsWith(CurrentCodeString) || row["C"].ToString().EndsWith(CurrentCodeString)) { sameCodeSet = true; break; }//if }//foreach //only insert a new code char if starting a new codeset //if (CurrentCodeString == "" || !tempStartChars[0][col].ToString().EndsWith(CurrentCodeString)) /* Removed because of bug */ if (CurrentCodeString == string.Empty || !sameCodeSet) { CurrentCodeSet = tempStartChars[0]; var error = true; while (error) { try { CurrentCodeString = CurrentCodeSet[col].ToString().Split(new char[] { '_' })[1]; error = false; }//try catch { error = true; if (col++ > CurrentCodeSet.ItemArray.Length) Error("No start character found in CurrentCodeSet."); }//catch }//while _FormattedData.Insert(i++, CurrentCodeSet[col].ToString()); }//if }//for }//try catch (Exception ex) { Error("EC128-3: Could not insert start and code characters.\n Message: " + ex.Message); }//catch }//else } private string GetEncoding() { //break up data for encoding BreakUpDataForEncoding(); //insert the start characters InsertStartandCodeCharacters(); var CheckDigit = CalculateCheckDigit(); var Encoded_Data = string.Empty; foreach (var s in _FormattedData) { //handle exception with apostrophes in select statements var s1 = s.Replace("'", "''"); DataRow[] E_Row; //select encoding only for type selected switch (type) { case TYPES.A: E_Row = C128_Code.Select("A = '" + s1 + "'"); break; case TYPES.B: E_Row = C128_Code.Select("B = '" + s1 + "'"); break; case TYPES.C: E_Row = C128_Code.Select("C = '" + s1 + "'"); break; case TYPES.DYNAMIC: E_Row = C128_Code.Select("A = '" + s1 + "'"); if (E_Row.Length <= 0) { E_Row = C128_Code.Select("B = '" + s1 + "'"); if (E_Row.Length <= 0) { E_Row = C128_Code.Select("C = '" + s1 + "'"); }//if }//if break; default: E_Row = null; break; }//switch if (E_Row == null || E_Row.Length <= 0) Error("EC128-5: Could not find encoding of a value( " + s1 + " ) in C128 type " + type.ToString()); Encoded_Data += E_Row[0]["Encoding"].ToString(); _EncodedData.Add(E_Row[0]["Encoding"].ToString()); }//foreach //add the check digit Encoded_Data += CalculateCheckDigit(); _EncodedData.Add(CalculateCheckDigit()); //add the stop character Encoded_Data += C128_Code.Select("A = 'STOP'")[0]["Encoding"].ToString(); _EncodedData.Add(C128_Code.Select("A = 'STOP'")[0]["Encoding"].ToString()); //add the termination bars Encoded_Data += "11"; _EncodedData.Add("11"); return Encoded_Data; } #region IBarcode Members public string Encoded_Value => Encode_Code128(); #endregion }//class }//namespace
49.604374
182
0.448639
[ "Apache-2.0" ]
markhazleton/barcodelib
BarcodeStandard/Symbologies/Code128.cs
24,951
C#
using Assistant.Net.Messaging.Exceptions; using System; namespace Assistant.Net.Scheduler.Contracts.Exceptions { /// <summary> /// The queried data wasn't found. /// </summary> public class NotFoundException : MessageException { /// <summary/> public NotFoundException() : base("Resource wasn't found.") { } /// <summary/> public NotFoundException(string? message) : base(message) { } /// <summary/> public NotFoundException(string? message, Exception? ex) : base(message, ex) { } } }
26.904762
88
0.621239
[ "Apache-2.0" ]
iotbusters/assistant.net.iot
src/Scheduler/Scheduler.Contracts/Exceptions/NotFoundException.cs
567
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // Source Executable: c:\windows\system32\httpprxm.dll // Interface ID: 2e6035b2-e8f1-41a7-a044-656b439c4c34 // Interface Version: 1.0 namespace rpc_2e6035b2_e8f1_41a7_a044_656b439c4c34_1_0 { #region Marshal Helpers internal class _Marshal_Helper : NtApiDotNet.Ndr.Marshal.NdrMarshalBuffer { public void Write_0(Struct_0 p0) { WriteStruct<Struct_0>(p0); } public void Write_1(Union_1 p0, long p1) { WriteUnion<Union_1>(p0, p1); } public void Write_2(Struct_2 p0) { WriteStruct<Struct_2>(p0); } public void Write_3(byte[] p0, long p1) { WriteConformantArray<byte>(p0, p1); } } internal class _Unmarshal_Helper : NtApiDotNet.Ndr.Marshal.NdrUnmarshalBuffer { public _Unmarshal_Helper(NtApiDotNet.Win32.Rpc.RpcClientResponse r) : base(r.NdrBuffer, r.Handles, r.DataRepresentation) { } public _Unmarshal_Helper(byte[] ba) : base(ba) { } public Struct_0 Read_0() { return ReadStruct<Struct_0>(); } public Union_1 Read_1() { return ReadStruct<Union_1>(); } public Struct_2 Read_2() { return ReadStruct<Struct_2>(); } public byte[] Read_3() { return ReadConformantArray<byte>(); } } #endregion #region Complex Types public struct Struct_0 : NtApiDotNet.Ndr.Marshal.INdrStructure { void NtApiDotNet.Ndr.Marshal.INdrStructure.Marshal(NtApiDotNet.Ndr.Marshal.NdrMarshalBuffer m) { Marshal(((_Marshal_Helper)(m))); } private void Marshal(_Marshal_Helper m) { m.WriteEnum16(Member0); m.Write_1(Member8, Member0); } void NtApiDotNet.Ndr.Marshal.INdrStructure.Unmarshal(NtApiDotNet.Ndr.Marshal.NdrUnmarshalBuffer u) { Unmarshal(((_Unmarshal_Helper)(u))); } private void Unmarshal(_Unmarshal_Helper u) { Member0 = u.ReadEnum16(); Member8 = u.Read_1(); } int NtApiDotNet.Ndr.Marshal.INdrStructure.GetAlignment() { return 4; } public NtApiDotNet.Ndr.Marshal.NdrEnum16 Member0; public Union_1 Member8; public static Struct_0 CreateDefault() { return new Struct_0(); } public Struct_0(NtApiDotNet.Ndr.Marshal.NdrEnum16 Member0, Union_1 Member8) { this.Member0 = Member0; this.Member8 = Member8; } } public struct Union_1 : NtApiDotNet.Ndr.Marshal.INdrNonEncapsulatedUnion { void NtApiDotNet.Ndr.Marshal.INdrStructure.Marshal(NtApiDotNet.Ndr.Marshal.NdrMarshalBuffer m) { throw new System.NotImplementedException(); } void NtApiDotNet.Ndr.Marshal.INdrNonEncapsulatedUnion.Marshal(NtApiDotNet.Ndr.Marshal.NdrMarshalBuffer m, long l) { Selector = ((int)(l)); Marshal(((_Marshal_Helper)(m))); } private void Marshal(_Marshal_Helper m) { m.WriteInt32(Selector); if ((Selector == 1)) { m.Write_2(Arm_1); goto done; } throw new System.ArgumentException("No matching union selector when marshaling Union_1"); done: return; } void NtApiDotNet.Ndr.Marshal.INdrStructure.Unmarshal(NtApiDotNet.Ndr.Marshal.NdrUnmarshalBuffer u) { Unmarshal(((_Unmarshal_Helper)(u))); } private void Unmarshal(_Unmarshal_Helper u) { Selector = u.ReadInt32(); if ((Selector == 1)) { Arm_1 = u.Read_2(); goto done; } throw new System.ArgumentException("No matching union selector when marshaling Union_1"); done: return; } int NtApiDotNet.Ndr.Marshal.INdrStructure.GetAlignment() { return 1; } private int Selector; public Struct_2 Arm_1; public static Union_1 CreateDefault() { return new Union_1(); } public Union_1(int Selector, Struct_2 Arm_1) { this.Selector = Selector; this.Arm_1 = Arm_1; } } public struct Struct_2 : NtApiDotNet.Ndr.Marshal.INdrStructure { void NtApiDotNet.Ndr.Marshal.INdrStructure.Marshal(NtApiDotNet.Ndr.Marshal.NdrMarshalBuffer m) { Marshal(((_Marshal_Helper)(m))); } private void Marshal(_Marshal_Helper m) { m.WriteEmbeddedPointer<string>(Member0, new System.Action<string>(m.WriteTerminatedString)); m.WriteInt32(Member8); } void NtApiDotNet.Ndr.Marshal.INdrStructure.Unmarshal(NtApiDotNet.Ndr.Marshal.NdrUnmarshalBuffer u) { Unmarshal(((_Unmarshal_Helper)(u))); } private void Unmarshal(_Unmarshal_Helper u) { Member0 = u.ReadEmbeddedPointer<string>(new System.Func<string>(u.ReadConformantVaryingString), false); Member8 = u.ReadInt32(); } int NtApiDotNet.Ndr.Marshal.INdrStructure.GetAlignment() { return 4; } public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<string> Member0; public int Member8; public static Struct_2 CreateDefault() { return new Struct_2(); } public Struct_2(string Member0, int Member8) { this.Member0 = Member0; this.Member8 = Member8; } } #endregion #region Client Implementation public sealed class Client : NtApiDotNet.Win32.Rpc.RpcClientBase { public Client() : base("2e6035b2-e8f1-41a7-a044-656b439c4c34", 1, 0) { } private _Unmarshal_Helper SendReceive(int p, _Marshal_Helper m) { return new _Unmarshal_Helper(SendReceive(p, m.DataRepresentation, m.ToArray(), m.Handles)); } public int ProxyMgrProviderRegisterForEventNotification(out NtApiDotNet.Ndr.Marshal.NdrContextHandle p0) { _Marshal_Helper m = new _Marshal_Helper(); _Unmarshal_Helper u = SendReceive(0, m); p0 = u.ReadContextHandle(); return u.ReadInt32(); } public int ProxyMgrProviderUnregisterEventNotification(ref NtApiDotNet.Ndr.Marshal.NdrContextHandle p0) { _Marshal_Helper m = new _Marshal_Helper(); m.WriteContextHandle(p0); _Unmarshal_Helper u = SendReceive(1, m); p0 = u.ReadContextHandle(); return u.ReadInt32(); } // async public int ProxyMgrProviderGetNotification(NtApiDotNet.Ndr.Marshal.NdrContextHandle p0, out NtApiDotNet.Ndr.Marshal.NdrEnum16 p1) { _Marshal_Helper m = new _Marshal_Helper(); m.WriteContextHandle(p0); _Unmarshal_Helper u = SendReceive(2, m); p1 = u.ReadEnum16(); return u.ReadInt32(); } public int ProxyMgrGetProxyEventInformation(ref Struct_0 p0) { _Marshal_Helper m = new _Marshal_Helper(); m.Write_0(p0); _Unmarshal_Helper u = SendReceive(3, m); p0 = u.Read_0(); return u.ReadInt32(); } public int ProxyMgrSetProxyConfiguration() { _Marshal_Helper m = new _Marshal_Helper(); _Unmarshal_Helper u = SendReceive(4, m); return u.ReadInt32(); } public int ProxyMgrSetProxyCredentials(string p0, int p1, byte[] p2, int p3) { _Marshal_Helper m = new _Marshal_Helper(); m.WriteTerminatedString(NtApiDotNet.Win32.Rpc.RpcUtils.CheckNull(p0, "p0")); m.WriteInt32(p1); m.Write_3(NtApiDotNet.Win32.Rpc.RpcUtils.CheckNull(p2, "p2"), p3); m.WriteInt32(p3); _Unmarshal_Helper u = SendReceive(5, m); return u.ReadInt32(); } } #endregion }
33.523077
137
0.568724
[ "Unlicense" ]
ExpLife0011/WindowsRpcClients
Win10_1809/httpprxm.dll/2e6035b2-e8f1-41a7-a044-656b439c4c34_1.0.cs
8,716
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "NewAbility", menuName = "AbilitySystem/Ability")] public class Ability : ScriptableObject { public new string name; public string description; public IEffect[] effects; public bool isActive = true; public void cast(Icharacter self, Icharacter other) { foreach (var effect in effects) { effect.applyEffect(self, other); } Debug.Log("Used: " + name); } }
23.304348
78
0.664179
[ "MIT" ]
neginsdii/GAME3023-Assignment
Assets/Scripts/Encounter/Ability.cs
536
C#
using OA.Ultima.Core.Network.Packets; using OA.Ultima.Data; using OA.Ultima.Login.Data; using System; namespace OA.Ultima.Network.Client { public class CreateCharacterPacket : SendPacket { internal CreateCharacterPacket(CreateCharacterData data, short locationIndex, short slotNumber, int clientIp) : base(0x00, "Create Character", 104) { var str = (byte)MathHelper.Clamp(data.Attributes[0], 10, 60); var dex = (byte)MathHelper.Clamp(data.Attributes[1], 10, 60); var intel = (byte)MathHelper.Clamp(data.Attributes[2], 10, 60); if (str + dex + intel != 80) throw new Exception("Unable to create character with a combined stat total not equal to 80."); Stream.Write(0xedededed); Stream.Write(0xffffffff); Stream.Write((byte)0); Stream.WriteAsciiFixed(data.Name, 30); Stream.WriteAsciiFixed(string.Empty, 30); Stream.Write((byte)((int)(Genders)data.Gender + (int)(Races)0)); Stream.Write((byte)str); Stream.Write((byte)dex); Stream.Write((byte)intel); Stream.Write((byte)data.SkillIndexes[0]); Stream.Write((byte)data.SkillValues[0]); Stream.Write((byte)data.SkillIndexes[1]); Stream.Write((byte)data.SkillValues[1]); Stream.Write((byte)data.SkillIndexes[2]); Stream.Write((byte)data.SkillValues[2]); Stream.Write((short)data.SkinHue); Stream.Write((short)data.HairStyleID); Stream.Write((short)data.HairHue); Stream.Write((short)data.FacialHairStyleID); Stream.Write((short)data.FacialHairHue); Stream.Write((short)locationIndex); Stream.Write((short)slotNumber); Stream.Write((short)0); Stream.Write(clientIp); Stream.Write((short)data.ShirtColor); Stream.Write((short)data.PantsColor); } } }
43.914894
118
0.589147
[ "MIT" ]
BclEx/object-assets
src/ObjectManager/Object.Ultima.Game/Network/Client/CreateCharacterPacket.cs
2,066
C#
namespace PasswordManager.Encoding { public class ASCIIEncoder : Encoder { public override byte[] Decode(string encoded) { return System.Text.Encoding.ASCII.GetBytes(encoded); } public override string Encode(byte[] data, int offset, int count) { return System.Text.Encoding.ASCII.GetString(data, offset, count); } } }
21.3125
68
0.72434
[ "MIT" ]
lontivero/PasswordManager
PasswordManager/Encoding/ASCIIEncoder.cs
343
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Microsoft.CodeAnalysis.Editor.CSharp { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class CSharpEditorResources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal CSharpEditorResources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.CodeAnalysis.Editor.CSharp.CSharpEditorResources", typeof(CSharpEditorResources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to &apos;{0}&apos; items in cache. /// </summary> internal static string _0_items_in_cache { get { return ResourceManager.GetString("_0_items_in_cache", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Chosen version: &apos;{0}&apos;. /// </summary> internal static string Chosen_version_0 { get { return ResourceManager.GetString("Chosen_version_0", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Complete statement on ;. /// </summary> internal static string Complete_statement_on_semicolon { get { return ResourceManager.GetString("Complete_statement_on_semicolon", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Could not find by name: &apos;{0}&apos;. /// </summary> internal static string Could_not_find_by_name_0 { get { return ResourceManager.GetString("Could_not_find_by_name_0", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Decompilation log. /// </summary> internal static string Decompilation_log { get { return ResourceManager.GetString("Decompilation_log", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Fix interpolated verbatim string. /// </summary> internal static string Fix_interpolated_verbatim_string { get { return ResourceManager.GetString("Fix_interpolated_verbatim_string", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Found &apos;{0}&apos; assemblies for &apos;{1}&apos;:. /// </summary> internal static string Found_0_assemblies_for_1 { get { return ResourceManager.GetString("Found_0_assemblies_for_1", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Found exact match: &apos;{0}&apos;. /// </summary> internal static string Found_exact_match_0 { get { return ResourceManager.GetString("Found_exact_match_0", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Found higher version match: &apos;{0}&apos;. /// </summary> internal static string Found_higher_version_match_0 { get { return ResourceManager.GetString("Found_higher_version_match_0", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Found single assembly: &apos;{0}&apos;. /// </summary> internal static string Found_single_assembly_0 { get { return ResourceManager.GetString("Found_single_assembly_0", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Load from: &apos;{0}&apos;. /// </summary> internal static string Load_from_0 { get { return ResourceManager.GetString("Load_from_0", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Module not found!. /// </summary> internal static string Module_not_found { get { return ResourceManager.GetString("Module_not_found", resourceCulture); } } /// <summary> /// Looks up a localized string similar to (Press TAB to insert). /// </summary> internal static string Press_TAB_to_insert { get { return ResourceManager.GetString("Press_TAB_to_insert", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Resolve: &apos;{0}&apos;. /// </summary> internal static string Resolve_0 { get { return ResourceManager.GetString("Resolve_0", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Resolve module: &apos;{0}&apos; of &apos;{1}&apos;. /// </summary> internal static string Resolve_module_0_of_1 { get { return ResourceManager.GetString("Resolve_module_0_of_1", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Smart Indenting. /// </summary> internal static string Smart_Indenting { get { return ResourceManager.GetString("Smart_Indenting", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Split string. /// </summary> internal static string Split_string { get { return ResourceManager.GetString("Split_string", resourceCulture); } } /// <summary> /// Looks up a localized string similar to WARN: Version mismatch. Expected: &apos;{0}&apos;, Got: &apos;{1}&apos;. /// </summary> internal static string WARN_Version_mismatch_Expected_0_Got_1 { get { return ResourceManager.GetString("WARN_Version_mismatch_Expected_0_Got_1", resourceCulture); } } } }
38.915929
215
0.568505
[ "Apache-2.0" ]
MaherJendoubi/roslyn
src/EditorFeatures/CSharp/CSharpEditorResources.Designer.cs
8,797
C#
using Newtonsoft.Json.Linq; using NJsonSchema.Validation; using NJsonSchema.Validation.FormatValidators; using System; using System.Globalization; using Xunit; namespace NJsonSchema.Tests.Validation { public class CustomValidationTests { [Fact] public void When_format_date_time_correct_with_custom_validator_passed_then_no_errors() { //// Arrange var schema = new JsonSchema { Type = JsonObjectType.String, Format = JsonFormatStrings.DateTime }; var token = new JValue("2014-12-01 11:00:01:55"); //// Act var settings = new JsonSchemaValidatorSettings(); settings.AddCustomFormatValidator(new CustomDateTimeFormatValidator()); var errors = schema.Validate(token, settings); //// Assert Assert.Empty(errors); } private class CustomDateTimeFormatValidator : IFormatValidator { private readonly string[] _acceptableFormats = { "yyyy'-'MM'-'dd HH':'mm':'ss':'ff" }; /// <summary> /// Gets the format attributes value. /// </summary> public string Format { get; } = JsonFormatStrings.DateTime; /// <summary> /// Gets the validation error kind. /// </summary> public ValidationErrorKind ValidationErrorKind { get; } = ValidationErrorKind.DateTimeExpected; /// <summary>Validates if a string is valid DateTime.</summary> /// <param name="value">String value.</param> /// <param name="tokenType">Type of token holding the value.</param> /// <returns></returns> public bool IsValid(string value, JTokenType tokenType) { return tokenType == JTokenType.Date || DateTimeOffset.TryParseExact(value, _acceptableFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out _); } } } }
33.467742
140
0.583614
[ "MIT" ]
NJsonSchema/Core
src/NJsonSchema.Tests/Validation/CustomValidationTests.cs
2,077
C#
using System; using System.Collections.Generic; using System.Text; namespace SilentWave.Obj2Gltf.Geom { public class PolygonUtil { // private static Boolean IsIntersect(SVec2 ln1Start, SVec2 ln1End, SVec2 ln2Start, SVec2 ln2End) { //https://ideone.com/PnPJgb var A = ln1Start; var B = ln1End; var C = ln2Start; var D = ln2End; var CmP = new SVec2(C.U - A.U, C.V - A.V); var r = new SVec2(B.U - A.U, B.V - A.V); var s = new SVec2(D.U - C.U, D.V - C.V); var CmPxr = CmP.U * r.V - CmP.V * r.U; var CmPxs = CmP.U * s.V - CmP.V * s.U; var rxs = r.U * s.V - r.V * s.U; if (CmPxr == 0f) { // Lines are collinear, and so intersect if they have any overlap return ((C.U - A.U < 0f) != (C.U - B.U < 0f)) || ((C.V - A.V < 0f) != (C.V - B.V < 0f)); } if (rxs == 0f) return false; // Lines are parallel. var rxsr = 1f / rxs; var t = CmPxs * rxsr; var u = CmPxr * rxsr; return (t >= 0) && (t <= 1) && (u >= 0) && (u <= 1); //// https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection //double x1 = ln1Start.U, y1 = ln1Start.V; //double x2 = ln1End.U, y2 = ln1End.V; //double x3 = ln2Start.U, y3 = ln2Start.V; //double x4 = ln2End.U, y4 = ln2End.V; //var t1 = (x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4); //var t2 = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); //var t = t1 / t2; //if (t < 0.0 || t > 1.0) return false; ////if (t >= 0.0 && t <= 1.0) return true; ////return false; //var u1 = (x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3); //var u2 = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); //var u = u1 / u2; //return u >= 0.0 && u <= 1.0; } public static PolygonPointRes CrossTest(SVec2 p, IList<SVec2> polygon, Single tol) { Single minX = Single.MaxValue, minY = Single.MaxValue, maxX = Single.MinValue, maxY = Single.MinValue; var angleVs = new List<Single>(); var vecX = new SVec2(1.0f, 0); foreach (var v in polygon) { var d = p.GetDistance(v); if (d < tol) return PolygonPointRes.Vertex; if (minX > v.U) minX = v.U; if (minY > v.V) minY = v.V; if (maxX < v.U) maxX = v.U; if (maxY < v.V) maxY = v.V; var vector = new SVec2(v.U - p.U, v.V - p.V).Normalize(); var an = (Single)Math.Acos(vecX.Dot(vector)); if (vector.V < 0) { an = 2 * (Single)Math.PI - an; } angleVs.Add(an); } for (var i = 0; i < polygon.Count; i++) { var j = i + 1; if (j == polygon.Count) { j = 0; } var v1 = polygon[i]; var v2 = polygon[j]; var d0 = v1.GetDistance(v2); var distance = Math.Abs(p.GetDistance(v1) + p.GetDistance(v2) - d0); if (distance < tol) { return PolygonPointRes.Edge; } } var box = new BoundingBox2 { Min = new SVec2(minX, minY), Max = new SVec2(maxX, maxY) }; if (!box.IsIn(p)) return PolygonPointRes.Outside; angleVs.Sort(); var startIndex = 0; var diff = angleVs[1] - angleVs[0]; for (var i = 1; i < angleVs.Count; i++) { var j = i + 1; if (j == angleVs.Count) j = 0; var anJ = angleVs[j]; if (j == 0) { } var diff1 = angleVs[j] - angleVs[i]; if (diff1 > diff) { diff = diff1; startIndex = i; } } var angle = angleVs[startIndex] + diff / 2.0; var len = box.Max.GetDistance(box.Min); var p2 = new SVec2(len * (Single)Math.Cos(angle), len * (Single)Math.Sin(angle)); var intersectCount = 0; for (var i = 0; i < polygon.Count; i++) { var j = i + 1; if (j == polygon.Count) j = 0; var v1 = polygon[i]; var v2 = polygon[j]; var pnt = IsIntersect(p, p2, v1, v2); IsIntersect(p, p2, v1, v2); if (pnt) { intersectCount++; } } if (intersectCount % 2 == 1) { return PolygonPointRes.Inside; } return PolygonPointRes.Outside; } private static Single GetRayLength(SVec2 p, IList<SVec2> polygon) { throw new NotImplementedException(); } } }
32.9875
114
0.405267
[ "MIT" ]
SilentWave/ObjConvert
src/Obj2Gltf/Geom/PolygonUtil.cs
5,280
C#
using System; using System.Collections.Generic; using Unity.UIWidgets.painting; using Unity.UIWidgets.widgets; using UnityEngine; namespace WidgetFromHtml.Core { internal class StyleMargin { Widget _marginHorizontalBuilder ( Widget w, CssLengthBox b, TextStyleHtml tsh ) { return new Padding( padding: EdgeInsets.only( left: Mathf.Max(b.getValueLeft(tsh) ?? 0f, 0f), right: Mathf.Max(b.getValueRight(tsh) ?? 0f, 0f) ), child: w ); } const int kPriorityBoxModel9k = 9000; public WidgetFactory wf; public StyleMargin(WidgetFactory wf) { this.wf = wf; } public BuildOp buildOp => new BuildOp( onTree: ONTree, onWidgets: ONWidgets, onWidgetsIsOptional: true, priority: kPriorityBoxModel9k ); private void ONTree(AbsBuildMetadata meta, AbsBuildTree tree) { if (meta.willBuildSubtree == true) return; var m = core_parser.tryParseCssLengthBox(meta, Const.kCssMargin); if (m == null || !m.hasPositiveLeftOrRight) return; core_ops.wrapTree ( tree, append: (p) => WidgetBit.inline(p, style_padding._paddingInlineAfter(p.tsb, m)), prepend: (p) => WidgetBit.inline(p, style_padding._paddingInlineBefore(p.tsb, m)) ); } private IEnumerable<Widget> ONWidgets(AbsBuildMetadata meta, IEnumerable<WidgetPlaceholder> widgets) { if (meta.willBuildSubtree == false) return widgets; if (widgets.isEmpty()) return widgets; var m = core_parser.tryParseCssLengthBox(meta, Const.kCssMargin); if (m == null) return null; var tsb = meta.tsb; var retList = new List<Widget>(); if (m.top != null && m.top.Value.isPositive()) { retList.Add(new HeightPlaceholder(m.top.Value, tsb)); } foreach (var widget in widgets) { if (m.hasPositiveLeftOrRight) { var widgetPlaceholder = widget.wrapWith( (c, w) => _marginHorizontalBuilder(w, m, tsb.build(c))); retList.Add(widgetPlaceholder); } else { retList.Add(widget); } } if (m.bottom != null && m.bottom.Value.isPositive()) { retList.Add(new HeightPlaceholder(m.bottom.Value, tsb)); } return retList; } } }
28.58
108
0.507348
[ "MIT" ]
dianchu/HypertextForUnity
hypertext/Assets/WidgetFromHtml/Core/Runtime/internal/ops/style_margin.cs
2,860
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace WiredBrainCoffee.Models { public class Contact { [Required] public string Name { get; set; } [Phone] [Required] public string Phone { get; set; } [Required] public string Email { get; set; } [MinLength(10)] [Required] public string Message { get; set; } } }
19.5
44
0.61144
[ "MIT" ]
bhageshpuri/wired-brain-coffee-1
src/WiredBrainCoffee/Models/Contact.cs
509
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the mediaconvert-2017-08-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.MediaConvert.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.MediaConvert.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for CaptionDescriptionPreset Object /// </summary> public class CaptionDescriptionPresetUnmarshaller : IUnmarshaller<CaptionDescriptionPreset, XmlUnmarshallerContext>, IUnmarshaller<CaptionDescriptionPreset, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> CaptionDescriptionPreset IUnmarshaller<CaptionDescriptionPreset, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public CaptionDescriptionPreset Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; CaptionDescriptionPreset unmarshalledObject = new CaptionDescriptionPreset(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("customLanguageCode", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.CustomLanguageCode = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("destinationSettings", targetDepth)) { var unmarshaller = CaptionDestinationSettingsUnmarshaller.Instance; unmarshalledObject.DestinationSettings = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("languageCode", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.LanguageCode = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("languageDescription", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.LanguageDescription = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static CaptionDescriptionPresetUnmarshaller _instance = new CaptionDescriptionPresetUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static CaptionDescriptionPresetUnmarshaller Instance { get { return _instance; } } } }
37.790909
185
0.631946
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/MediaConvert/Generated/Model/Internal/MarshallTransformations/CaptionDescriptionPresetUnmarshaller.cs
4,157
C#
using System; namespace DP08Decorator { public class Canon : Camera { public override void TakePhoto() { Console.WriteLine("Canon Take Photo"); } } }
15.461538
51
0.557214
[ "MIT" ]
mazhongbin/designpattern
DP08Decorator/Canon.cs
203
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Polardb20170801.Models { public class DescribeDBClusterMonitorResponse : TeaModel { [NameInMap("Period")] [Validation(Required=true)] public string Period { get; set; } [NameInMap("RequestId")] [Validation(Required=true)] public string RequestId { get; set; } } }
21.043478
62
0.669421
[ "Apache-2.0" ]
alibabacloud-sdk-swift/alibabacloud-sdk
polardb-20170801/csharp/core/Models/DescribeDBClusterMonitorResponse.cs
484
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Physics { /// <summary> /// Implements a movement logic that uses the model of angular rotations along a sphere whose /// radius varies. The angle to move by is computed by looking at how much the hand changes /// relative to a pivot point (slightly below and in front of the head). /// /// Usage: /// When a manipulation starts, call Setup. /// Call Update any time to update the move logic and get a new rotation for the object. /// </summary> public class TwoHandMoveLogic { private static readonly Vector3 offsetPosition = new Vector3(0, -0.2f, 0); private readonly MovementConstraintType movementConstraint; private float handRefDistance; private float objRefDistance; /// <summary> /// Constructor. /// </summary> /// <param name="movementConstraint"></param> public TwoHandMoveLogic(MovementConstraintType movementConstraint) { this.movementConstraint = movementConstraint; } /// <summary> /// The initial angle between the hand and the object /// </summary> private Quaternion gazeAngularOffset; private const float NearDistanceScale = 1.0f; private const float FarDistanceScale = 2.0f; public void Setup(Vector3 startHandPositionMeters, Vector3 manipulationObjectPosition) { var newHandPosition = startHandPositionMeters; // The pivot is just below and in front of the head. var pivotPosition = GetHandPivotPosition(); objRefDistance = Vector3.Distance(manipulationObjectPosition, pivotPosition); handRefDistance = Vector3.Distance(newHandPosition, pivotPosition); var objDirection = Vector3.Normalize(manipulationObjectPosition - pivotPosition); var handDirection = Vector3.Normalize(newHandPosition - pivotPosition); // We transform the forward vector of the object, the direction of the object, and the direction of the hand // to camera space so everything is relative to the user's perspective. objDirection = CameraCache.Main.transform.InverseTransformDirection(objDirection); handDirection = CameraCache.Main.transform.InverseTransformDirection(handDirection); // Store the original rotation between the hand an object gazeAngularOffset = Quaternion.FromToRotation(handDirection, objDirection); } public Vector3 Update(Vector3 centroid, bool isNearMode) { float distanceScale = isNearMode ? NearDistanceScale : FarDistanceScale; var newHandPosition = centroid; var pivotPosition = GetHandPivotPosition(); // Compute the pivot -> hand vector in camera space var newHandDirection = Vector3.Normalize(newHandPosition - pivotPosition); newHandDirection = CameraCache.Main.transform.InverseTransformDirection(newHandDirection); // The direction the object should face is the current hand direction rotated by the original hand -> object rotation. var targetDirection = Vector3.Normalize(gazeAngularOffset * newHandDirection); targetDirection = CameraCache.Main.transform.TransformDirection(targetDirection); var targetDistance = objRefDistance; if (movementConstraint != MovementConstraintType.FixDistanceFromHead) { // Compute how far away the object should be based on the ratio of the current to original hand distance var currentHandDistance = Vector3.Magnitude(newHandPosition - pivotPosition); var distanceRatio = currentHandDistance / handRefDistance; var distanceOffset = distanceRatio > 0 ? (distanceRatio - 1f) * distanceScale : 0; targetDistance += distanceOffset; } var newPosition = pivotPosition + (targetDirection * targetDistance); var newDistance = Vector3.Distance(newPosition, pivotPosition); if (newDistance > 4f) { newPosition = pivotPosition + Vector3.Normalize(newPosition - pivotPosition) * 4f; } return newPosition; } /// <summary> /// Get the hand pivot position located a bit lower and behind the camera. /// </summary> /// <returns>A point that is below and just in front of the head.</returns> public static Vector3 GetHandPivotPosition() { Vector3 pivot = CameraCache.Main.transform.position + offsetPosition - CameraCache.Main.transform.forward * 0.2f; // a bit lower and behind return pivot; } } }
45.131579
152
0.652672
[ "MIT" ]
AzureMentor/MapsSDK-Unity
SampleProject/Assets/MixedRealityToolkit/Utilities/Physics/TwoHandMoveLogic.cs
5,147
C#
using System.Collections.Generic; namespace O10.Client.Web.DataContracts.IdentityProvider { public class IssuanceDetailsDto { public IssuanceDetailsRoot RootAttribute { get; set; } public IEnumerable<IssuanceDetailsAssociated> AssociatedAttributes { get; set; } public class IssuanceDetailsRoot { public string AttributeName { get; set; } public string OriginatingCommitment { get; set; } public string AssetCommitment { get; set; } public string SurjectionProof{ get; set; } } public class IssuanceDetailsAssociated { public string AttributeName { get; set; } public string AssetCommitment { get; set; } public string BindingToRootCommitment { get; set; } } } }
31.807692
88
0.637243
[ "Apache-2.0" ]
muaddibco/O10city
Client/Web/O10.Client.Web.DataContracts/IdentityProvider/IssuanceDetailsDto.cs
829
C#
// <copyright file="Convolution2DFilter.cs" company="James Jackson-South"> // Copyright (c) James Jackson-South and contributors. // Licensed under the Apache License, Version 2.0. // </copyright> namespace ImageProcessorCore.Filters { using System; using System.Threading.Tasks; /// <summary> /// Defines a filter that uses two one-dimensional matrices to perform convolution against an image. /// </summary> public abstract class Convolution2DFilter : ParallelImageProcessor { /// <summary> /// Gets the horizontal gradient operator. /// </summary> public abstract float[,] KernelX { get; } /// <summary> /// Gets the vertical gradient operator. /// </summary> public abstract float[,] KernelY { get; } /// <inheritdoc/> protected override void Apply(ImageBase target, ImageBase source, Rectangle targetRectangle, Rectangle sourceRectangle, int startY, int endY) { float[,] kernelX = this.KernelX; float[,] kernelY = this.KernelY; int kernelYHeight = kernelY.GetLength(0); int kernelYWidth = kernelY.GetLength(1); int kernelXHeight = kernelX.GetLength(0); int kernelXWidth = kernelX.GetLength(1); int radiusY = kernelYHeight >> 1; int radiusX = kernelXWidth >> 1; int sourceY = sourceRectangle.Y; int sourceBottom = sourceRectangle.Bottom; int startX = sourceRectangle.X; int endX = sourceRectangle.Right; int maxY = sourceBottom - 1; int maxX = endX - 1; Parallel.For( startY, endY, y => { if (y >= sourceY && y < sourceBottom) { for (int x = startX; x < endX; x++) { float rX = 0; float gX = 0; float bX = 0; float rY = 0; float gY = 0; float bY = 0; // Apply each matrix multiplier to the color components for each pixel. for (int fy = 0; fy < kernelYHeight; fy++) { int fyr = fy - radiusY; int offsetY = y + fyr; offsetY = offsetY.Clamp(0, maxY); for (int fx = 0; fx < kernelXWidth; fx++) { int fxr = fx - radiusX; int offsetX = x + fxr; offsetX = offsetX.Clamp(0, maxX); Color currentColor = source[offsetX, offsetY]; float r = currentColor.R; float g = currentColor.G; float b = currentColor.B; if (fy < kernelXHeight) { rX += kernelX[fy, fx] * r; gX += kernelX[fy, fx] * g; bX += kernelX[fy, fx] * b; } if (fx < kernelYWidth) { rY += kernelY[fy, fx] * r; gY += kernelY[fy, fx] * g; bY += kernelY[fy, fx] * b; } } } float red = (float)Math.Sqrt((rX * rX) + (rY * rY)); float green = (float)Math.Sqrt((gX * gX) + (gY * gY)); float blue = (float)Math.Sqrt((bX * bX) + (bY * bY)); Color targetColor = target[x, y]; target[x, y] = new Color(red, green, blue, targetColor.A); } this.OnRowProcessed(); } }); } } }
39.890909
149
0.394257
[ "Apache-2.0" ]
SeanKilleen/ImageProcessor
src/ImageProcessorCore/Filters/Convolution/Convolution2DFilter.cs
4,390
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using Newtonsoft.Json; using System.IO; namespace Crypto_Prices { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
18.69697
66
0.583468
[ "MIT" ]
dtuck20/Crypto-Prices
Crypto Prices/Crypto Prices/Program.cs
619
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading; using System.Windows.Automation; namespace AutomationConnectIQ.Lib { /// <summary> /// シミュレーターの操作 /// </summary> public partial class Simulator { // このファイルでは設定以外のメニューでの設定を行うものを入れてある /// <summary> /// View Screen Heat Mapが選択可能かどうかを返す<br/> /// trueの場合Low Power ModeをTrueにするとHeat Mapが表示されてしまうので注意が必要 /// </summary> public bool IsEnabledHeatMap => Win32Api.IsEnabledMenu((IntPtr)top_.Current.NativeWindowHandle, new List<string>() { "File", "View Screen Heat Map" }); /// <summary> /// Activity Monitorの設定で時間を進める /// </summary> /// <param name="miniuete">進める時間(分:1~600)</param> /// <exception cref="ArgumentOutOfRangeException">miniueteが1-600以外</exception> public void FastForward(uint miniuete) { if (miniuete < 1 || miniuete > 600) { throw new ArgumentOutOfRangeException(miniuete.ToString()); } OpenWindow(new List<string>() { "Simulation", "Activity Monitoring", "Fast Forward" }, "Fast Forward Activity Tracking", (settingWindow) => { // 入力フィールドのスピンに値を入れる var guiParts = settingWindow.FindAll(TreeScope.Subtree, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Spinner)).Cast<AutomationElement>(); if (guiParts.Count() == 1) { Utility.SetSpinText(guiParts.First(), miniuete.ToString()); return true; } return false; }); } } }
38.4
159
0.601852
[ "MIT" ]
take4blue/AutomationConnectIQ
Utility/SimulatorSetting2.cs
1,960
C#
using System; using System.Collections.Generic; using System.Text; using System.Data; namespace Interface.Pharmacy { public interface IPediatric { DataSet GetPediatricFields(int PatientID); DataSet GetExistPaediatricDetails(int PatientID); int SaveUpdatePaediatricDetail(int patientID, int PharmacyID, int LocationID, int RegimenLine, string PharmacyNotes, DataTable theDT, DataSet theDrgMst, int OrderedBy, DateTime OrderedByDate, int DispensedBy, DateTime DispensedByDate, int Signature, int EmployeeID, int OrderType, int VisitType, int UserID, decimal Height, decimal Weight, int FDC, int ProgID, int ProviderID, DataTable theCustomFieldData, int PeriodTaken, int flag, int SCMFlag, DateTime AppntDate, int AppntReason); int SavePaediatricDetail(int patientID, DataTable theDT, DataSet theDrgMst, int OrderedBy, DateTime OrderedByDate, int DispensedBy, DateTime DispensedByDate, int Signature, int EmployeeID, int LocationID, int OrderType, int VisitType, int UserID, decimal Height, decimal Weight, int FDC, int ProgID, int ProviderID, DataTable theCustomFieldData, int PeriodTaken); int UpdatePaediatricDetail(int patientID, int LocationID, int PharmacyID, DataTable theDT, DataSet theDrgMst, int OrderedBy, int DispensedBy, int Signature, int EmployeeID, int OrderType, int UserID, decimal Height, decimal Weight, int FDC, int ProgID, int ProviderID, DateTime OrderedByDate, DateTime ReportedByDate, DataTable theCustomFieldData, int PeriodTaken); int DeletePediatricForms(string FormName, int OrderNo, int PatientId, int UserID); DataSet GetExistPharmacyForm(int PatientID, DateTime OrderedByDate); DataSet GetExistPharmacyFormDespensedbydate(int PatientID, DateTime DispensedByDate); DataSet GetPatientRecordformStatus(int PatientID); int IQTouchSaveUpdatePharmacy(List<IPharmacyFields> iPharmacyFields); DataSet IQTouchGetPharmacyDetails(int PatientID); DataSet SaveUpdate_CustomPharmacy(String Insert, DataSet DS, int UserId); DataSet GetPharmacyDetailforLabelPrint(int PatientId, int VisitId); DataSet GetPreDefinedDruglist(); int SavePredefineList(string name, DataTable dt, int UserId); DataSet GetDrugGenericDetails(int PatientID); DataSet GetDrugDetails(); DataSet GetPatientContinueARVDetails(int PatientId); } // This class is used for IQTouch pharmacy form [Serializable()] public class IPharmacyFields { public int Ptn_pk { get; set; } public int VisitID { get; set; } public int LocationID { get; set; } public int ptn_pharmacy_pk_old { get; set; } public int ptn_pharmacy_pk { get; set; } public int userid { get; set; } public int EmployeeId { get; set; } public int VisitType { get; set; } public int AppntReason { get; set; } public int TreatmentProgram { get; set; } public int PeriodTaken { get; set; } public int Drugprovider { get; set; } public decimal Weight { get; set; } public decimal Height { get; set; } public int RegimenLine { get; set; } //public DateTime PharmacyRefillDate { get; set; } public string PharmacyRefillDate { get; set; } public string PharmacyNotes { get; set; } public int OrderedBy { get; set; } //public DateTime OrderedByDate { get; set; } public string OrderedByDate { get; set; } public int DispensedBy { get; set; } //public DateTime DispensedByDate { get; set; } public string DispensedByDate { get; set; } public int flag { get; set; } public List<DrugDetails> Druginfo { get; set; } } [Serializable()] public class DrugDetails { public int Drug_Pk { get; set; } public int FrequencyID { get; set; } public int GenericId { get; set; } public decimal SingleDose { get; set; } public decimal Duration { get; set; } public int Prophylaxis { get; set; } public int BatchNo { get; set; } public decimal OrderedQuantity { get; set; } public decimal DispensedQuantity { get; set; } public int refill { get; set; } public DateTime RefillExpiration { get; set; } public int sellingprice { get; set; } public int billamount { get; set; } } }
55.025
492
0.69582
[ "MIT" ]
uon-crissp/IQCare
SourceBase/DataAccess/Interface.Pharmacy/IPediatric.cs
4,402
C#
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class DCETModelNetworkComponentWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(DCET.Model.NetworkComponent); Utils.BeginObjectRegister(type, L, translator, 0, 7, 4, 2); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Awake", _m_Awake); Utils.RegisterFunc(L, Utils.METHOD_IDX, "OnAccept", _m_OnAccept); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Remove", _m_Remove); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Get", _m_Get); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Create", _m_Create); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Update", _m_Update); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Dispose", _m_Dispose); Utils.RegisterFunc(L, Utils.GETTER_IDX, "MessagePacker", _g_get_MessagePacker); Utils.RegisterFunc(L, Utils.GETTER_IDX, "MessageDispatcher", _g_get_MessageDispatcher); Utils.RegisterFunc(L, Utils.GETTER_IDX, "Count", _g_get_Count); Utils.RegisterFunc(L, Utils.GETTER_IDX, "Sessions", _g_get_Sessions); Utils.RegisterFunc(L, Utils.SETTER_IDX, "MessagePacker", _s_set_MessagePacker); Utils.RegisterFunc(L, Utils.SETTER_IDX, "MessageDispatcher", _s_set_MessageDispatcher); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 1, 0, 0); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { return LuaAPI.luaL_error(L, "DCET.Model.NetworkComponent does not have a constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Awake(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); DCET.Model.NetworkComponent gen_to_be_invoked = (DCET.Model.NetworkComponent)translator.FastGetCSObj(L, 1); int gen_param_count = LuaAPI.lua_gettop(L); if(gen_param_count == 3&& translator.Assignable<DCET.Model.NetworkProtocol>(L, 2)&& LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 3)) { DCET.Model.NetworkProtocol _protocol;translator.Get(L, 2, out _protocol); int _packetSize = LuaAPI.xlua_tointeger(L, 3); gen_to_be_invoked.Awake( _protocol, _packetSize ); return 0; } if(gen_param_count == 2&& translator.Assignable<DCET.Model.NetworkProtocol>(L, 2)) { DCET.Model.NetworkProtocol _protocol;translator.Get(L, 2, out _protocol); gen_to_be_invoked.Awake( _protocol ); return 0; } if(gen_param_count == 4&& translator.Assignable<DCET.Model.NetworkProtocol>(L, 2)&& (LuaAPI.lua_isnil(L, 3) || LuaAPI.lua_type(L, 3) == LuaTypes.LUA_TSTRING)&& LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, 4)) { DCET.Model.NetworkProtocol _protocol;translator.Get(L, 2, out _protocol); string _address = LuaAPI.lua_tostring(L, 3); int _packetSize = LuaAPI.xlua_tointeger(L, 4); gen_to_be_invoked.Awake( _protocol, _address, _packetSize ); return 0; } if(gen_param_count == 3&& translator.Assignable<DCET.Model.NetworkProtocol>(L, 2)&& (LuaAPI.lua_isnil(L, 3) || LuaAPI.lua_type(L, 3) == LuaTypes.LUA_TSTRING)) { DCET.Model.NetworkProtocol _protocol;translator.Get(L, 2, out _protocol); string _address = LuaAPI.lua_tostring(L, 3); gen_to_be_invoked.Awake( _protocol, _address ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to DCET.Model.NetworkComponent.Awake!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_OnAccept(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); DCET.Model.NetworkComponent gen_to_be_invoked = (DCET.Model.NetworkComponent)translator.FastGetCSObj(L, 1); { DCET.Model.AChannel _channel = (DCET.Model.AChannel)translator.GetObject(L, 2, typeof(DCET.Model.AChannel)); DCET.Model.Session gen_ret = gen_to_be_invoked.OnAccept( _channel ); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Remove(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); DCET.Model.NetworkComponent gen_to_be_invoked = (DCET.Model.NetworkComponent)translator.FastGetCSObj(L, 1); { long _id = LuaAPI.lua_toint64(L, 2); gen_to_be_invoked.Remove( _id ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Get(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); DCET.Model.NetworkComponent gen_to_be_invoked = (DCET.Model.NetworkComponent)translator.FastGetCSObj(L, 1); { long _id = LuaAPI.lua_toint64(L, 2); DCET.Model.Session gen_ret = gen_to_be_invoked.Get( _id ); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Create(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); DCET.Model.NetworkComponent gen_to_be_invoked = (DCET.Model.NetworkComponent)translator.FastGetCSObj(L, 1); int gen_param_count = LuaAPI.lua_gettop(L); if(gen_param_count == 2&& translator.Assignable<System.Net.IPEndPoint>(L, 2)) { System.Net.IPEndPoint _ipEndPoint = (System.Net.IPEndPoint)translator.GetObject(L, 2, typeof(System.Net.IPEndPoint)); DCET.Model.Session gen_ret = gen_to_be_invoked.Create( _ipEndPoint ); translator.Push(L, gen_ret); return 1; } if(gen_param_count == 2&& (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING)) { string _address = LuaAPI.lua_tostring(L, 2); DCET.Model.Session gen_ret = gen_to_be_invoked.Create( _address ); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to DCET.Model.NetworkComponent.Create!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Update(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); DCET.Model.NetworkComponent gen_to_be_invoked = (DCET.Model.NetworkComponent)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Update( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Dispose(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); DCET.Model.NetworkComponent gen_to_be_invoked = (DCET.Model.NetworkComponent)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Dispose( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_MessagePacker(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); DCET.Model.NetworkComponent gen_to_be_invoked = (DCET.Model.NetworkComponent)translator.FastGetCSObj(L, 1); translator.PushAny(L, gen_to_be_invoked.MessagePacker); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_MessageDispatcher(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); DCET.Model.NetworkComponent gen_to_be_invoked = (DCET.Model.NetworkComponent)translator.FastGetCSObj(L, 1); translator.PushAny(L, gen_to_be_invoked.MessageDispatcher); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_Count(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); DCET.Model.NetworkComponent gen_to_be_invoked = (DCET.Model.NetworkComponent)translator.FastGetCSObj(L, 1); LuaAPI.xlua_pushinteger(L, gen_to_be_invoked.Count); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_Sessions(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); DCET.Model.NetworkComponent gen_to_be_invoked = (DCET.Model.NetworkComponent)translator.FastGetCSObj(L, 1); translator.Push(L, gen_to_be_invoked.Sessions); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _s_set_MessagePacker(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); DCET.Model.NetworkComponent gen_to_be_invoked = (DCET.Model.NetworkComponent)translator.FastGetCSObj(L, 1); gen_to_be_invoked.MessagePacker = (DCET.Model.IMessagePacker)translator.GetObject(L, 2, typeof(DCET.Model.IMessagePacker)); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 0; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _s_set_MessageDispatcher(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); DCET.Model.NetworkComponent gen_to_be_invoked = (DCET.Model.NetworkComponent)translator.FastGetCSObj(L, 1); gen_to_be_invoked.MessageDispatcher = (DCET.Model.IMessageDispatcher)translator.GetObject(L, 2, typeof(DCET.Model.IMessageDispatcher)); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 0; } } }
36.390887
223
0.520461
[ "MIT" ]
zxsean/DCET
Unity/Assets/Model/XLua/Gen/DCETModelNetworkComponentWrap.cs
15,177
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace AdventCode19 { class Program { static void Main(string[] args) { var sections = File.ReadAllText("input.txt") .Split(Environment.NewLine + Environment.NewLine); var messages = sections[1] .Split(Environment.NewLine); var rules = sections[0] .Split(Environment.NewLine) .Select(e => ParseRule(e)) .ToDictionary(k => k.Item1, k => k.Item2); int solution1 = messages.Count(m => ValidRule(m, rules[0], rules)); Console.WriteLine($"Solution 1: {solution1}"); var r1 = ParseRule("8: 42 | 42 8"); var r2 = ParseRule("11: 42 31 | 42 11 31"); rules[r1.Item1] = r1.Item2; rules[r2.Item1] = r2.Item2; int solution2 = messages.Count(m => ValidRule(m, rules[0], rules)); Console.WriteLine($"Solution 2: {solution2}"); } private static bool ValidRule(string message, IEnumerable<string> listRule, Dictionary<int, IEnumerable<IEnumerable<string>>> rules) { if (message.Length == 0 && listRule.Count() == 0) { return true; } else if (message.Length == 0 || listRule.Count() == 0) { return false; } bool isValid; var firstRule = listRule.First(); var otherRules = listRule.Skip(1); if (IsSimpleRule(firstRule)) { string simpleRuleString = GetSimpleRuleValue(firstRule); isValid = message.StartsWith(simpleRuleString) && ValidRule(message[simpleRuleString.Length..], otherRules, rules); } else { int ruleNumber = int.Parse(firstRule); isValid = rules[ruleNumber] .Select(subRule => subRule.Concat(otherRules)) .Any(rule => ValidRule(message, rule, rules)); } return isValid; } private static bool ValidRule(string message, IEnumerable<IEnumerable<string>> conditions, Dictionary<int, IEnumerable<IEnumerable<string>>> rules) => conditions.Any(r => ValidRule(message, r, rules)); private static string GetSimpleRuleValue(string first) => first.Replace("\"", ""); private static bool IsSimpleRule(string ruleCondition) => ruleCondition.Contains("\""); private static (int, IEnumerable<IEnumerable<string>>) ParseRule(string ruleString) { var tokens = ruleString.Split(": "); return (int.Parse(tokens[0]), tokens[1].Split("|").Select(e => e.Split(' ', StringSplitOptions.RemoveEmptyEntries))); } } }
37.384615
122
0.546639
[ "MIT" ]
HF0/advent-of-code-2020
src/AdventCode19/Program.cs
2,918
C#
#region Copyright notice and license // Copyright 2019 The gRPC Authors // // 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. #endregion using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Grpc.Core; using Grpc.Core.Internal; using System; namespace Grpc.Microbenchmarks { // this test measures the overhead of C# wrapping layer when invoking calls; // the marshallers **DO NOT ALLOCATE**, so any allocations // are from the framework, not the messages themselves [ClrJob, CoreJob] // test .NET Core and .NET Framework [MemoryDiagnoser] // allocations public class UnaryCallOverheadBenchmark { private static readonly Task<string> CompletedString = Task.FromResult(""); private static readonly byte[] EmptyBlob = new byte[0]; private static readonly Marshaller<string> EmptyMarshaller = new Marshaller<string>(_ => EmptyBlob, _ => ""); private static readonly Method<string, string> PingMethod = new Method<string, string>(MethodType.Unary, nameof(PingBenchmark), "Ping", EmptyMarshaller, EmptyMarshaller); [Benchmark] public string SyncUnaryCallOverhead() { return client.Ping("", new CallOptions()); } Channel channel; PingClient client; [GlobalSetup] public void Setup() { // create client, the channel will actually never connect because call logic will be short-circuited channel = new Channel("localhost", 10042, ChannelCredentials.Insecure); client = new PingClient(new DefaultCallInvoker(channel)); var native = NativeMethods.Get(); // replace the implementation of a native method with a fake NativeMethods.Delegates.grpcsharp_call_start_unary_delegate fakeCallStartUnary = (CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags) => { return native.grpcsharp_test_call_start_unary_echo(call, ctx, sendBuffer, sendBufferLen, writeFlags, metadataArray, metadataFlags); }; native.GetType().GetField(nameof(native.grpcsharp_call_start_unary)).SetValue(native, fakeCallStartUnary); NativeMethods.Delegates.grpcsharp_completion_queue_pluck_delegate fakeCqPluck = (CompletionQueueSafeHandle cq, IntPtr tag) => { return new CompletionQueueEvent { type = CompletionQueueEvent.CompletionType.OpComplete, success = 1, tag = tag }; }; native.GetType().GetField(nameof(native.grpcsharp_completion_queue_pluck)).SetValue(native, fakeCqPluck); } [GlobalCleanup] public async Task Cleanup() { await channel.ShutdownAsync(); } class PingClient : LiteClientBase { public PingClient(CallInvoker callInvoker) : base(callInvoker) { } public string Ping(string request, CallOptions options) { return CallInvoker.BlockingUnaryCall(PingMethod, null, options, request); } } } }
41.197802
276
0.678848
[ "Apache-2.0" ]
Johnhuang1121/grpc
src/csharp/Grpc.Microbenchmarks/UnaryCallOverheadBenchmark.cs
3,749
C#
namespace Shotr.Core.MimeDetect.Matchers.TextSignature { public class Rust : BaseTextSignature { public override string[] Signatures => new[] { "#[derive(Debug)]", "pub enum", "match ", "&'a ", " -> Self", "fn main()", }; public override LangTypes Lang => LangTypes.Rust; } }
23.058824
57
0.479592
[ "Apache-2.0" ]
shotr-io/shotr-3
src/Shotr.Core.MimeDetect/Matchers/TextSignature/Rust.cs
392
C#
using System.Collections.Generic; namespace TmdbEasy.DTO.Changes { public class ChangeList { public List<ChangeResult> Results { get; set; } public int Page { get; set; } public int Total_pages { get; set; } public int Total_results { get; set; } } }
22.846154
55
0.622896
[ "MIT" ]
PoLaKoSz/TMdbEasy
src/DTO/Changes/ChangeList.cs
299
C#
using Serilog; var builder = WebApplication.CreateBuilder(args); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(builder.Configuration) .CreateLogger(); builder.Host.UseSerilog(Log.Logger); builder.Services.AddServices(builder.Configuration); var app = builder.Build(); app.AddWebApplication(); await app.RunAsync();
20.352941
52
0.771676
[ "MIT" ]
eecmachado/AspnetMicroservices_Store
src/Services/Catolog/Catolog.Api/Program.cs
346
C#
#region using System; using collections.mathematics.src.List; using collections.src; #endregion namespace collections.mathematics.src.Sets { [Serializable] public sealed class AppaSet_bool2x2 : AppaSet<bool2x2, AppaList_bool2x2> { } }
15.875
76
0.751969
[ "MIT" ]
ChristopherSchubert/com.appalachia.unity3d.appa.collections.mathematics
src/Sets/AppaSet_bool2x2.cs
254
C#
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/Beef using Beef.Caching.Policy; using System; namespace Beef.Caching { /// <summary> /// Enables the core cache capabilities including extended <see cref="Flush"/> (see <see cref="OnFlushCache"/>) support. /// </summary> public abstract class CacheCoreBase : ICacheCore { private readonly ICachePolicy _policy; private bool _disposed; /// <summary> /// Gets the internal <see cref="PolicyKey"/> string format. /// </summary> protected const string InternalPolicyKeyFormat = "{0}__INTERNAL__"; /// <summary> /// Initializes a new instance of the <see cref="CacheCoreBase"/> class that automatically <see cref="CachePolicyManager.Register">registers</see> for centralised <see cref="CachePolicyManager.Flush"/> management. /// </summary> /// <param name="policyKey">The policy key used to determine the cache policy configuration (see <see cref="CachePolicyManager"/>); defaults to <see cref="Guid.NewGuid()"/> ensuring uniqueness.</param> /// <param name="doNotRegister">Indicates that the automatic <see cref="CachePolicyManager.Register"/> should not occur (inheriting class must perform).</param> protected CacheCoreBase(string policyKey = null, bool doNotRegister = false) { PolicyKey = string.IsNullOrEmpty(policyKey) ? Guid.NewGuid().ToString() : policyKey; if (!doNotRegister) CachePolicyManager.Register(this); } /// <summary> /// Initializes a new instance of the <see cref="CacheCoreBase"/> class that uses the specified <paramref name="policy"/> versus being managed centrally. /// </summary> /// <param name="policy">The <see cref="ICachePolicy"/>.</param> protected CacheCoreBase(ICachePolicy policy) { _policy = policy ?? throw new ArgumentNullException(nameof(policy)); } /// <summary> /// Gets the policy key used to determine the cache policy configuration (see <see cref="CachePolicyManager"/>). /// </summary> public string PolicyKey { get; protected set; } /// <summary> /// Gets the <see cref="ICachePolicy"/> (as specified via the constructor, or from the centralised <see cref="CachePolicyManager"/> using the <see cref="PolicyKey"/>). /// </summary> public ICachePolicy GetPolicy() => _policy ?? CachePolicyManager.Get(PolicyKey); /// <summary> /// Gets the lock object to enable additional locking in a multithreaded context (all internal operations use the lock). /// </summary> protected object Lock { get; } = new object(); /// <summary> /// Gets the count of items in the cache (both expired and non-expired may co-exist until flushed). /// </summary> public abstract long Count { get; } /// <summary> /// Registers an internal <b>Policy Key</b> (using the <see cref="InternalPolicyKeyFormat"/>) with a <see cref="NoCachePolicy"/> to ensure always invoked; /// it is then expected that the <see cref="OnFlushCache(bool)"/> will handle policy expiration specifically. /// </summary> protected void RegisterInternalPolicyKey() { var overridePolicyKey = string.Format(System.Globalization.CultureInfo.InvariantCulture, InternalPolicyKeyFormat, PolicyKey); CachePolicyManager.Register(this, overridePolicyKey); CachePolicyManager.Set(overridePolicyKey, new NoCachePolicy()); } /// <summary> /// Flush the cache. /// </summary> /// <param name="ignoreExpiry"><c>true</c> indicates to flush immediately; otherwise, <c>false</c> to only flush when the <see cref="ICachePolicy"/> is <see cref="ICachePolicy.IsExpired"/> (default).</param> public void Flush(bool ignoreExpiry = false) { lock (Lock) { if (ignoreExpiry || GetPolicy().IsExpired) OnFlushCache(ignoreExpiry); } } /// <summary> /// Required to be overridden to flush/empty the underlying cache; called by <see cref="Flush"/> within the context of a <see cref="Lock"/>. The <see cref="Flush"/> checks the underlying policy /// to detemine whether it has expired; as such the implementing logic should not revalidate this condition (always assume flush) - this value is passed for context should the implementer need to /// understand the context in which it was called to perform additional logic. /// </summary> /// <param name="ignoreExpiry"><c>true</c> indicates to flush immediately; otherwise, <c>false</c> to only flush when the <see cref="ICachePolicy"/> is <see cref="ICachePolicy.IsExpired"/> (default).</param> protected abstract void OnFlushCache(bool ignoreExpiry); /// <summary> /// Releases all resources (see <see cref="Flush(bool)"/>) and invokes the <see cref="CachePolicyManager.Unregister(string)"/> for the <see cref="PolicyKey"/>. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases the unmanaged resources used by the <see cref="CacheCoreBase"/> and optionally releases the managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { lock (Lock) { Flush(true); CachePolicyManager.Unregister(PolicyKey); } } _disposed = true; } /// <summary> /// Finalizer. /// </summary> ~CacheCoreBase() { Dispose(false); } } }
46.541353
221
0.617286
[ "MIT" ]
vishal-sharma/Beef
src/Beef.Core/Caching/CacheCoreBase.cs
6,192
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Skyline.API.Application.Commands; using Skyline.API.Application.Queries; using Skyline.API.ViewModels; using Skyline.Domain.OrderAggregate; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Skyline.API.Controllers { [ApiController] [Route("[controller]")] public class OrderController : ControllerBase { IMediator _mediator; public OrderController(IMediator mediator) { _mediator = mediator; } [HttpPost] [Route("create")] public async Task<long> CreateOrder([FromBody]CreateOrderCommand cmd) { return await _mediator.Send(cmd, HttpContext.RequestAborted); } [HttpGet] [Route("get")] public async Task<List<BuyerOrderViewModel>> QueryOrder([FromBody]OrderQueryViewModel vmQuery) { List<BuyerOrderViewModel> vmOrderList = new List<BuyerOrderViewModel>(); var query = new OrderQuery(vmQuery.BuyerId); var orderEntities = await _mediator.Send(query); orderEntities.ForEach(orderEntity => { vmOrderList.Add(new BuyerOrderViewModel { BuyerId = orderEntity.BuyerId, BuyerName = orderEntity.BuyerName, ItemCount = orderEntity.ItemCount }); }); return vmOrderList; } } }
30.529412
102
0.622993
[ "MIT" ]
zhaobingwang/Skyline
MicroServicesArchitecture/src/Skyline.API/Controllers/OrderController.cs
1,559
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Util; using System; namespace Amazon.Runtime.CredentialManagement { #if !NETSTANDARD13 /// <summary> /// Represents the different types of authentication available for SAML endpoints. /// </summary> public enum SAMLAuthenticationType { NTLM, Digest, Kerberos, Negotiate } /// <summary> /// Representation of a SAML Endpoint. /// </summary> public class SAMLEndpoint { private SAMLAuthenticationType DefaultAuthenticationType = SAMLAuthenticationType.Kerberos; /// <summary> /// The name given to this SAMLEndpoint. /// </summary> public string Name { get; private set; } /// <summary> /// The URI of the SAML endnpoint. /// </summary> public Uri EndpointUri { get; private set; } /// <summary> /// The authentication type associated with the SAML endpoint. /// </summary> public SAMLAuthenticationType AuthenticationType { get; private set; } /// <summary> /// Internal constructor. Used by SAMLEndpointManager when reading endpoints from the encrypted store. /// </summary> /// <param name="name"></param> /// <param name="endpointUri"></param> /// <param name="authenticationType"></param> internal SAMLEndpoint(string name, string endpointUri, string authenticationType) { var parsedEndpointUri = new Uri(endpointUri, UriKind.RelativeOrAbsolute); var parsedAuthenticationType = DefaultAuthenticationType; if (!string.IsNullOrEmpty(authenticationType)) { parsedAuthenticationType = (SAMLAuthenticationType)Enum.Parse(typeof(SAMLAuthenticationType), authenticationType); } SetProperties(name, parsedEndpointUri, parsedAuthenticationType); } /// <summary> /// Construct a SAMLEndpoint using the default SAMLAuthenticationType - Kerberos. /// </summary> /// <param name="name">The name of the endpoint.</param> /// <param name="endpointUri">The URI of the endpoint.</param> public SAMLEndpoint(string name, Uri endpointUri) { SetProperties(name, endpointUri, DefaultAuthenticationType); } /// <summary> /// Construct a SAMLEndpoint. /// </summary> /// <param name="name">The name of the endpoint.</param> /// <param name="endpointUri">The URI of the endpoint.</param> /// <param name="authenticationType">The authentication type of the endpoint.</param> public SAMLEndpoint(string name, Uri endpointUri, SAMLAuthenticationType authenticationType) { SetProperties(name, endpointUri, authenticationType); } private void SetProperties(string name, Uri endpointUri, SAMLAuthenticationType authenticationType) { if (!string.Equals(endpointUri.Scheme, "https", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("EndpointUri is not Https protocol."); } if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Name is null or empty."); } Name = name; EndpointUri = endpointUri; AuthenticationType = authenticationType; } } #endif }
35.548673
130
0.631815
[ "Apache-2.0" ]
PureKrome/aws-sdk-net
sdk/src/Core/Amazon.Runtime/CredentialManagement/SAMLEndpoint.cs
4,017
C#
using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using WebSite1; public partial class Account_Manage : System.Web.UI.Page { protected string SuccessMessage { get; private set; } protected bool CanRemoveExternalLogins { get; private set; } private bool HasPassword(UserManager manager) { var user = manager.FindById(User.Identity.GetUserId()); return (user != null && user.PasswordHash != null); } protected void Page_Load() { if (!IsPostBack) { // Determine the sections to render UserManager manager = new UserManager(); if (HasPassword(manager)) { changePasswordHolder.Visible = true; } else { setPassword.Visible = true; changePasswordHolder.Visible = false; } CanRemoveExternalLogins = manager.GetLogins(User.Identity.GetUserId()).Count() > 1; // Render success message var message = Request.QueryString["m"]; if (message != null) { // Strip the query string from action Form.Action = ResolveUrl("~/Account/Manage"); SuccessMessage = message == "ChangePwdSuccess" ? "Your password has been changed." : message == "SetPwdSuccess" ? "Your password has been set." : message == "RemoveLoginSuccess" ? "The account was removed." : String.Empty; successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage); } } } protected void ChangePassword_Click(object sender, EventArgs e) { if (IsValid) { UserManager manager = new UserManager(); IdentityResult result = manager.ChangePassword(User.Identity.GetUserId(), CurrentPassword.Text, NewPassword.Text); if (result.Succeeded) { var user = manager.FindById(User.Identity.GetUserId()); IdentityHelper.SignIn(manager, user, isPersistent: false); Response.Redirect("~/Account/Manage?m=ChangePwdSuccess"); } else { AddErrors(result); } } } protected void SetPassword_Click(object sender, EventArgs e) { if (IsValid) { // Create the local login info and link the local account to the user UserManager manager = new UserManager(); IdentityResult result = manager.AddPassword(User.Identity.GetUserId(), password.Text); if (result.Succeeded) { Response.Redirect("~/Account/Manage?m=SetPwdSuccess"); } else { AddErrors(result); } } } public IEnumerable<UserLoginInfo> GetLogins() { UserManager manager = new UserManager(); var accounts = manager.GetLogins(User.Identity.GetUserId()); CanRemoveExternalLogins = accounts.Count() > 1 || HasPassword(manager); return accounts; } public void RemoveLogin(string loginProvider, string providerKey) { UserManager manager = new UserManager(); var result = manager.RemoveLogin(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey)); string msg = String.Empty; if (result.Succeeded) { var user = manager.FindById(User.Identity.GetUserId()); IdentityHelper.SignIn(manager, user, isPersistent: false); msg = "?m=RemoveLoginSuccess"; } Response.Redirect("~/Account/Manage" + msg); } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } }
31.614173
126
0.564134
[ "MIT" ]
kensaku-okada/MIS531TeamProject
ASP.NET/MIS531Project/Account/Manage.aspx.cs
4,017
C#
 namespace Final_Project { partial class Average_Result { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(13, 9); this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(99, 25); this.label1.TabIndex = 0; this.label1.Text = "平均值为: "; // // button1 // this.button1.Font = new System.Drawing.Font("Microsoft YaHei", 8.805756F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.Location = new System.Drawing.Point(87, 128); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(100, 40); this.button1.TabIndex = 2; this.button1.Text = "确定"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Font = new System.Drawing.Font("Microsoft YaHei", 8.805756F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.Location = new System.Drawing.Point(308, 128); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(140, 40); this.button2.TabIndex = 3; this.button2.Text = "复制至剪切板"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.label2.Font = new System.Drawing.Font("Microsoft YaHei", 10.8777F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(13, 61); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(469, 30); this.label2.TabIndex = 4; // // Average_Result // this.AutoScaleDimensions = new System.Drawing.SizeF(11F, 25F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(499, 202); this.Controls.Add(this.label2); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Microsoft YaHei", 9.841726F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Average_Result"; this.ShowIcon = false; this.Text = "计算结果"; this.Load += new System.EventHandler(this.Average_Result_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Label label2; } }
44.796296
169
0.56759
[ "MIT" ]
Lincoln-Zhou/Survey-Adjustment-Calculation
Final Project/Average_Result.Designer.cs
4,872
C#
#pragma warning disable SA1600 // Elements should be documented namespace Accusoft.PrizmDocServer.Exceptions { internal class InnerErrorData { internal InnerErrorData(string errorCode, string rawErrorDetails = null) { this.ErrorCode = errorCode; this.RawErrorDetails = rawErrorDetails; } internal string ErrorCode { get; } internal string RawErrorDetails { get; } } }
24.833333
80
0.662192
[ "MIT" ]
Accusoft/PrizmDocServerDotNetSDK
PrizmDocServerSDK/Exceptions/InnerErrorData.cs
447
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Threading.Tasks { /// <summary> /// Provides a value type that wraps a <see cref="Task{TResult}"/> and a <typeparamref name="TResult"/>, /// only one of which is used. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <remarks> /// <para> /// Methods may return an instance of this value type when it's likely that the result of their /// operations will be available synchronously and when the method is expected to be invoked so /// frequently that the cost of allocating a new <see cref="Task{TResult}"/> for each call will /// be prohibitive. /// </para> /// <para> /// There are tradeoffs to using a <see cref="ValueTask{TResult}"/> instead of a <see cref="Task{TResult}"/>. /// For example, while a <see cref="ValueTask{TResult}"/> can help avoid an allocation in the case where the /// successful result is available synchronously, it also contains two fields whereas a <see cref="Task{TResult}"/> /// as a reference type is a single field. This means that a method call ends up returning two fields worth of /// data instead of one, which is more data to copy. It also means that if a method that returns one of these /// is awaited within an async method, the state machine for that async method will be larger due to needing /// to store the struct that's two fields instead of a single reference. /// </para> /// <para> /// Further, for uses other than consuming the result of an asynchronous operation via await, /// <see cref="ValueTask{TResult}"/> can lead to a more convoluted programming model, which can in turn actually /// lead to more allocations. For example, consider a method that could return either a <see cref="Task{TResult}"/> /// with a cached task as a common result or a <see cref="ValueTask{TResult}"/>. If the consumer of the result /// wants to use it as a <see cref="Task{TResult}"/>, such as to use with in methods like Task.WhenAll and Task.WhenAny, /// the <see cref="ValueTask{TResult}"/> would first need to be converted into a <see cref="Task{TResult}"/> using /// <see cref="ValueTask{TResult}.AsTask"/>, which leads to an allocation that would have been avoided if a cached /// <see cref="Task{TResult}"/> had been used in the first place. /// </para> /// <para> /// As such, the default choice for any asynchronous method should be to return a <see cref="Task"/> or /// <see cref="Task{TResult}"/>. Only if performance analysis proves it worthwhile should a <see cref="ValueTask{TResult}"/> /// be used instead of <see cref="Task{TResult}"/>. There is no non-generic version of <see cref="ValueTask{TResult}"/> /// as the Task.CompletedTask property may be used to hand back a successfully completed singleton in the case where /// a <see cref="Task"/>-returning method completes synchronously and successfully. /// </para> /// </remarks> [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))] [StructLayout(LayoutKind.Auto)] public struct ValueTask<TResult> : IEquatable<ValueTask<TResult>> { /// <summary>The task to be used if the operation completed asynchronously or if it completed synchronously but non-successfully.</summary> internal readonly Task<TResult> _task; /// <summary>The result to be used if the operation completed successfully synchronously.</summary> internal readonly TResult _result; /// <summary>Initialize the <see cref="ValueTask{TResult}"/> with the result of the successful operation.</summary> /// <param name="result">The result.</param> public ValueTask(TResult result) { _task = null; _result = result; } /// <summary> /// Initialize the <see cref="ValueTask{TResult}"/> with a <see cref="Task{TResult}"/> that represents the operation. /// </summary> /// <param name="task">The task.</param> public ValueTask(Task<TResult> task) { if (task == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.task); } _task = task; _result = default(TResult); } /// <summary>Returns the hash code for this instance.</summary> public override int GetHashCode() => _task != null ? _task.GetHashCode() : _result != null ? _result.GetHashCode() : 0; /// <summary>Returns a value indicating whether this value is equal to a specified <see cref="object"/>.</summary> public override bool Equals(object obj) => obj is ValueTask<TResult> && Equals((ValueTask<TResult>)obj); /// <summary>Returns a value indicating whether this value is equal to a specified <see cref="ValueTask{TResult}"/> value.</summary> public bool Equals(ValueTask<TResult> other) => _task != null || other._task != null ? _task == other._task : EqualityComparer<TResult>.Default.Equals(_result, other._result); /// <summary>Returns a value indicating whether two <see cref="ValueTask{TResult}"/> values are equal.</summary> public static bool operator==(ValueTask<TResult> left, ValueTask<TResult> right) => left.Equals(right); /// <summary>Returns a value indicating whether two <see cref="ValueTask{TResult}"/> values are not equal.</summary> public static bool operator!=(ValueTask<TResult> left, ValueTask<TResult> right) => !left.Equals(right); /// <summary> /// Gets a <see cref="Task{TResult}"/> object to represent this ValueTask. It will /// either return the wrapped task object if one exists, or it'll manufacture a new /// task object to represent the result. /// </summary> public Task<TResult> AsTask() => // Return the task if we were constructed from one, otherwise manufacture one. We don't // cache the generated task into _task as it would end up changing both equality comparison // and the hash code we generate in GetHashCode. _task ?? Task.FromResult(_result); /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a completed operation.</summary> public bool IsCompleted => _task == null || _task.IsCompleted; /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a successfully completed operation.</summary> public bool IsCompletedSuccessfully => _task == null || _task.IsCompletedSuccessfully; /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a failed operation.</summary> public bool IsFaulted => _task != null && _task.IsFaulted; /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a canceled operation.</summary> public bool IsCanceled => _task != null && _task.IsCanceled; /// <summary>Gets the result.</summary> public TResult Result => _task == null ? _result : _task.GetAwaiter().GetResult(); /// <summary>Gets an awaiter for this value.</summary> public ValueTaskAwaiter<TResult> GetAwaiter() => new ValueTaskAwaiter<TResult>(this); /// <summary>Configures an awaiter for this value.</summary> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the captured context; otherwise, false. /// </param> public ConfiguredValueTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext) => new ConfiguredValueTaskAwaitable<TResult>(this, continueOnCapturedContext); /// <summary>Gets a string-representation of this <see cref="ValueTask{TResult}"/>.</summary> public override string ToString() { if (_task != null) { return _task.IsCompletedSuccessfully && _task.Result != null ? _task.Result.ToString() : string.Empty; } else { return _result != null ? _result.ToString() : string.Empty; } } // TODO https://github.com/dotnet/corefx/issues/22171: // Remove CreateAsyncMethodBuilder once the C# compiler relies on the AsyncBuilder attribute. /// <summary>Creates a method builder for use with an async method.</summary> /// <returns>The created builder.</returns> [EditorBrowsable(EditorBrowsableState.Never)] // intended only for compiler consumption public static AsyncValueTaskMethodBuilder<TResult> CreateAsyncMethodBuilder() => AsyncValueTaskMethodBuilder<TResult>.Create(); } }
54.470588
147
0.65162
[ "MIT" ]
DotNet-CoreCLR-20170826/CoreCLR
src/mscorlib/shared/System/Threading/Tasks/ValueTask.cs
9,260
C#
namespace Deltatre.BallDetector.Onnx.Demo.Extensions { using System.Drawing; public static class RectangleExtensions { public static float Area(this RectangleF source) { return source.Width * source.Height; } } }
20.538462
56
0.640449
[ "MIT" ]
deltatrelabs/deltatre-net-conf-2022-mlnet
src/BallDetectorOnnxDemo/Deltatre.BallDetector.Onnx.Demo.YoloModel/Extensions/RectangleExtensions.cs
269
C#
using DCL.Components; using DCL.Helpers; using DCL.Models; using NUnit.Framework; using System.Collections; using System.Collections.Generic; using DCL; using UnityEngine; using UnityEngine.TestTools; public class ParametrizedShapesTests : IntegrationTestSuite_Legacy { [UnityTest] public IEnumerator BoxShapeUpdate() { string entityId = "1"; TestHelpers.InstantiateEntityWithShape(scene, entityId, DCL.Models.CLASS_ID.BOX_SHAPE, Vector3.zero); var meshName = scene.entities[entityId].gameObject.GetComponentInChildren<MeshFilter>().mesh.name; Assert.AreEqual("DCL Box Instance", meshName); yield break; } [UnityTest] public IEnumerator SphereShapeUpdate() { string entityId = "2"; TestHelpers.InstantiateEntityWithShape(scene, entityId, DCL.Models.CLASS_ID.SPHERE_SHAPE, Vector3.zero); var meshName = scene.entities[entityId].gameObject.GetComponentInChildren<MeshFilter>().mesh.name; Assert.AreEqual("DCL Sphere Instance", meshName); yield break; } [UnityTest] public IEnumerator CylinderShapeUpdate() { string entityId = "5"; TestHelpers.InstantiateEntityWithShape(scene, entityId, DCL.Models.CLASS_ID.CYLINDER_SHAPE, Vector3.zero); var meshName = scene.entities[entityId].gameObject.GetComponentInChildren<MeshFilter>().mesh.name; Assert.AreEqual("DCL Cylinder Instance", meshName); yield break; } [UnityTest] public IEnumerator ConeShapeUpdate() { string entityId = "4"; TestHelpers.InstantiateEntityWithShape(scene, entityId, DCL.Models.CLASS_ID.CONE_SHAPE, Vector3.zero); var meshName = scene.entities[entityId].gameObject.GetComponentInChildren<MeshFilter>().mesh.name; Assert.AreEqual("DCL Cone50v0t1b2l2o Instance", meshName); yield break; } [UnityTest] public IEnumerator BoxShapeComponentMissingValuesGetDefaultedOnUpdate() { string entityId = "1"; TestHelpers.CreateSceneEntity(scene, entityId); // 1. Create component with non-default configs string componentJSON = JsonUtility.ToJson(new BoxShape.Model { withCollisions = true }); string componentId = TestHelpers.CreateAndSetShape(scene, entityId, DCL.Models.CLASS_ID.BOX_SHAPE, componentJSON ); BoxShape boxShapeComponent = (BoxShape) scene.GetSharedComponent(componentId); // 2. Check configured values Assert.IsTrue(boxShapeComponent.GetModel().withCollisions); // 3. Update component with missing values scene.SharedComponentUpdate(componentId, JsonUtility.ToJson(new BoxShape.Model { })); // 4. Check defaulted values Assert.IsTrue(boxShapeComponent.GetModel().withCollisions); yield break; } [UnityTest] public IEnumerator BoxShapeAttachedGetsReplacedOnNewAttachment() { yield return TestHelpers.TestAttachedSharedComponentOfSameTypeIsReplaced<BoxShape.Model, BoxShape>(scene, CLASS_ID.BOX_SHAPE); } [UnityTest] public IEnumerator SphereShapeComponentMissingValuesGetDefaultedOnUpdate() { var component = TestHelpers.SharedComponentCreate<SphereShape, SphereShape.Model>(scene, CLASS_ID.SPHERE_SHAPE); yield return component.routine; Assert.IsFalse(component == null); yield return TestHelpers.TestSharedComponentDefaultsOnUpdate<SphereShape.Model, SphereShape>(scene, CLASS_ID.SPHERE_SHAPE); } [UnityTest] public IEnumerator SphereShapeAttachedGetsReplacedOnNewAttachment() { yield return TestHelpers.TestAttachedSharedComponentOfSameTypeIsReplaced<SphereShape.Model, SphereShape>( scene, CLASS_ID.SPHERE_SHAPE); } [UnityTest] public IEnumerator ConeShapeComponentMissingValuesGetDefaultedOnUpdate() { var component = TestHelpers.SharedComponentCreate<ConeShape, ConeShape.Model>(scene, CLASS_ID.CONE_SHAPE); yield return component.routine; Assert.IsFalse(component == null); yield return TestHelpers.TestSharedComponentDefaultsOnUpdate<ConeShape.Model, ConeShape>(scene, CLASS_ID.CONE_SHAPE); } [UnityTest] public IEnumerator ConeShapeAttachedGetsReplacedOnNewAttachment() { yield return TestHelpers.TestAttachedSharedComponentOfSameTypeIsReplaced<ConeShape.Model, ConeShape>(scene, CLASS_ID.CONE_SHAPE); } [UnityTest] public IEnumerator CylinderShapeComponentMissingValuesGetDefaultedOnUpdate() { var component = TestHelpers.SharedComponentCreate<CylinderShape, CylinderShape.Model>(scene, CLASS_ID.CYLINDER_SHAPE); yield return component.routine; Assert.IsFalse(component == null); yield return TestHelpers.TestSharedComponentDefaultsOnUpdate<CylinderShape.Model, CylinderShape>(scene, CLASS_ID.CYLINDER_SHAPE); } [UnityTest] public IEnumerator CylinderShapeAttachedGetsReplacedOnNewAttachment() { yield return TestHelpers.TestAttachedSharedComponentOfSameTypeIsReplaced<CylinderShape.Model, CylinderShape>(scene, CLASS_ID.CYLINDER_SHAPE); } [UnityTest] public IEnumerator CollisionProperty() { string entityId = "entityId"; TestHelpers.CreateSceneEntity(scene, entityId); var entity = scene.entities[entityId]; TestHelpers.SetEntityTransform(scene, entity, new DCLTransform.Model { position = new Vector3(8, 1, 8) }); yield return null; // BoxShape BaseShape.Model shapeModel = new BoxShape.Model(); BaseShape shapeComponent = TestHelpers.SharedComponentCreate<BoxShape, BaseShape.Model>(scene, CLASS_ID.BOX_SHAPE, shapeModel); yield return shapeComponent.routine; TestHelpers.SharedComponentAttach(shapeComponent, entity); yield return TestHelpers.TestShapeCollision(shapeComponent, shapeModel, entity); TestHelpers.DetachSharedComponent(scene, entityId, shapeComponent.id); shapeComponent.Dispose(); yield return null; // SphereShape shapeModel = new SphereShape.Model(); shapeComponent = TestHelpers.SharedComponentCreate<SphereShape, BaseShape.Model>(scene, CLASS_ID.SPHERE_SHAPE, shapeModel); yield return shapeComponent.routine; TestHelpers.SharedComponentAttach(shapeComponent, entity); yield return TestHelpers.TestShapeCollision(shapeComponent, shapeModel, entity); TestHelpers.DetachSharedComponent(scene, entityId, shapeComponent.id); shapeComponent.Dispose(); yield return null; // ConeShape shapeModel = new ConeShape.Model(); shapeComponent = TestHelpers.SharedComponentCreate<ConeShape, BaseShape.Model>(scene, CLASS_ID.CONE_SHAPE, shapeModel); yield return shapeComponent.routine; TestHelpers.SharedComponentAttach(shapeComponent, entity); yield return TestHelpers.TestShapeCollision(shapeComponent, shapeModel, entity); TestHelpers.DetachSharedComponent(scene, entityId, shapeComponent.id); shapeComponent.Dispose(); yield return null; // CylinderShape shapeModel = new CylinderShape.Model(); shapeComponent = TestHelpers.SharedComponentCreate<CylinderShape, BaseShape.Model>(scene, CLASS_ID.CYLINDER_SHAPE, shapeModel); yield return shapeComponent.routine; TestHelpers.SharedComponentAttach(shapeComponent, entity); yield return TestHelpers.TestShapeCollision(shapeComponent, shapeModel, entity); TestHelpers.DetachSharedComponent(scene, entityId, shapeComponent.id); shapeComponent.Dispose(); yield return null; // PlaneShape shapeModel = new PlaneShape.Model(); shapeComponent = TestHelpers.SharedComponentCreate<PlaneShape, BaseShape.Model>(scene, CLASS_ID.PLANE_SHAPE, shapeModel); yield return shapeComponent.routine; TestHelpers.SharedComponentAttach(shapeComponent, entity); yield return TestHelpers.TestShapeCollision(shapeComponent, shapeModel, entity); TestHelpers.DetachSharedComponent(scene, entityId, shapeComponent.id); shapeComponent.Dispose(); yield return null; } [UnityTest] public IEnumerator VisibleProperty() { string entityId = "entityId"; TestHelpers.CreateSceneEntity(scene, entityId); var entity = scene.entities[entityId]; TestHelpers.SetEntityTransform(scene, entity, new DCLTransform.Model { position = new Vector3(8, 1, 8) }); yield return null; // BoxShape BaseShape.Model shapeModel = new BoxShape.Model(); BaseShape shapeComponent = TestHelpers.SharedComponentCreate<BoxShape, BaseShape.Model>(scene, CLASS_ID.BOX_SHAPE, shapeModel); yield return shapeComponent.routine; TestHelpers.SharedComponentAttach(shapeComponent, entity); yield return TestHelpers.TestShapeVisibility(shapeComponent, shapeModel, entity); TestHelpers.DetachSharedComponent(scene, entityId, shapeComponent.id); shapeComponent.Dispose(); yield return null; // SphereShape shapeModel = new SphereShape.Model(); shapeComponent = TestHelpers.SharedComponentCreate<SphereShape, BaseShape.Model>(scene, CLASS_ID.SPHERE_SHAPE, shapeModel); yield return shapeComponent.routine; TestHelpers.SharedComponentAttach(shapeComponent, entity); yield return TestHelpers.TestShapeVisibility(shapeComponent, shapeModel, entity); TestHelpers.DetachSharedComponent(scene, entityId, shapeComponent.id); shapeComponent.Dispose(); yield return null; // ConeShape shapeModel = new ConeShape.Model(); shapeComponent = TestHelpers.SharedComponentCreate<ConeShape, BaseShape.Model>(scene, CLASS_ID.CONE_SHAPE, shapeModel); yield return shapeComponent.routine; TestHelpers.SharedComponentAttach(shapeComponent, entity); yield return TestHelpers.TestShapeVisibility(shapeComponent, shapeModel, entity); TestHelpers.DetachSharedComponent(scene, entityId, shapeComponent.id); shapeComponent.Dispose(); yield return null; // CylinderShape shapeModel = new CylinderShape.Model(); shapeComponent = TestHelpers.SharedComponentCreate<CylinderShape, BaseShape.Model>(scene, CLASS_ID.CYLINDER_SHAPE, shapeModel); yield return shapeComponent.routine; TestHelpers.SharedComponentAttach(shapeComponent, entity); yield return TestHelpers.TestShapeVisibility(shapeComponent, shapeModel, entity); TestHelpers.DetachSharedComponent(scene, entityId, shapeComponent.id); shapeComponent.Dispose(); yield return null; // PlaneShape shapeModel = new PlaneShape.Model(); shapeComponent = TestHelpers.SharedComponentCreate<PlaneShape, BaseShape.Model>(scene, CLASS_ID.PLANE_SHAPE, shapeModel); yield return shapeComponent.routine; TestHelpers.SharedComponentAttach(shapeComponent, entity); yield return TestHelpers.TestShapeVisibility(shapeComponent, shapeModel, entity); TestHelpers.DetachSharedComponent(scene, entityId, shapeComponent.id); shapeComponent.Dispose(); yield return null; } [UnityTest] [TestCase(5, true, ExpectedResult = null)] [TestCase(5, false, ExpectedResult = null)] //TODO: When refactoring these tests to split them by shape, replicate this on them public IEnumerator UpdateWithCollisionInMultipleEntities(int entitiesCount, bool withCollision) { Environment.i.world.sceneBoundsChecker.Stop(); // Arrange: set inverse of withCollision to trigger is dirty later BaseShape shapeComponent = TestHelpers.SharedComponentCreate<BoxShape, BaseShape.Model>(scene, CLASS_ID.BOX_SHAPE, new BaseShape.Model { withCollisions = !withCollision }); yield return shapeComponent.routine; List<IDCLEntity> entities = new List<IDCLEntity>(); for (int i = 0; i < entitiesCount; i++) { IDCLEntity entity = TestHelpers.CreateSceneEntity(scene, $"entity{i}"); TestHelpers.SharedComponentAttach(shapeComponent, entity); entities.Add(entity); } // Act: Update withCollision shapeComponent.UpdateFromModel(new BoxShape.Model { withCollisions = withCollision }); yield return shapeComponent.routine; // Assert: foreach (IDCLEntity entity in entities) { for (int i = 0; i < entity.meshesInfo.colliders.Count; i++) { Assert.AreEqual(withCollision, entity.meshesInfo.colliders[i].enabled); } } } [UnityTest] [TestCase(5, true, ExpectedResult = null)] [TestCase(5, false, ExpectedResult = null)] //TODO: When refactoring these tests to split them by shape, replicate this on them public IEnumerator UpdateVisibilityInMultipleEntities(int entitiesCount, bool visible) { Environment.i.world.sceneBoundsChecker.Stop(); // Arrange: set inverse of visible to trigger is dirty later BaseShape shapeComponent = TestHelpers.SharedComponentCreate<BoxShape, BaseShape.Model>(scene, CLASS_ID.BOX_SHAPE, new BaseShape.Model { visible = !visible }); yield return shapeComponent.routine; List<IDCLEntity> entities = new List<IDCLEntity>(); for (int i = 0; i < entitiesCount; i++) { IDCLEntity entity = TestHelpers.CreateSceneEntity(scene, $"entity{i}"); TestHelpers.SharedComponentAttach(shapeComponent, entity); entities.Add(entity); } // Act: Update visible shapeComponent.UpdateFromModel(new BoxShape.Model { visible = visible, withCollisions = true, isPointerBlocker = true }); yield return shapeComponent.routine; // Assert: foreach (IDCLEntity entity in entities) { for (int i = 0; i < entity.meshesInfo.renderers.Length; i++) { Assert.AreEqual(visible, entity.meshesInfo.renderers[i].enabled); } } } }
38.544236
180
0.70265
[ "Apache-2.0" ]
0xBlockchainx0/unity-renderer
unity-renderer/Assets/Scripts/MainScripts/DCL/Components/ParametrizedShapes/Tests/ParametrizedShapesTests.cs
14,377
C#
//////////////////////////////////////////////////////////////////////////////// //EF Core Provider for LCPI OLE DB. // IBProvider and Contributors. 06.07.2021. using System; using System.Reflection; namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.V03_0_0.Query.Local.D0.Expressions.Op2.Code{ //////////////////////////////////////////////////////////////////////////////// //using using T_ARG1 =System.TimeOnly; using T_ARG2 =System.Nullable<System.TimeOnly>; using T_RESULT =System.Nullable<System.Boolean>; //////////////////////////////////////////////////////////////////////////////// //class Op2_Code__LessThan___TimeOnly__NullableTimeOnly static class Op2_Code__LessThan___TimeOnly__NullableTimeOnly { public static readonly System.Reflection.MethodInfo MethodInfo_V_V =typeof(Op2_Code__LessThan___TimeOnly__NullableTimeOnly) .GetTypeInfo() .GetDeclaredMethod(nameof(Exec_V_V)); //----------------------------------------------------------------------- private static T_RESULT Exec_V_V(T_ARG1 a,T_ARG2 b) { if(!b.HasValue) return null; return MasterCode.Op2_MasterCode__LessThan___TimeOnly__TimeOnly.Exec (a, b.Value); }//Exec_V_V };//class Op2_Code__LessThan___TimeOnly__NullableTimeOnly //////////////////////////////////////////////////////////////////////////////// }//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.V03_0_0.Query.Local.D0.Expressions.Op2.Code
34.954545
130
0.575423
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Code/Provider/Source/Basement/EF/Dbms/Firebird/V03_0_0/Query/Local/D0/Expressions/Op2/Code/LessThan/TimeOnly/Op2_Code__LessThan___TimeOnly__NullableTimeOnly.cs
1,540
C#
using Newtonsoft.Json; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Xunit; namespace Telegram.Bot.Tests.Unit.Serialization { public class MessageEntityTests { [Fact(DisplayName = "Should deserialize message entity with phone number type")] public void Should_Deserialize_Message_Entity_With_Phone_Number_Type() { const string json = @"{ ""offset"": 10, ""length"": 10, ""type"": ""phone_number"" }"; var message = JsonConvert.DeserializeObject<MessageEntity>(json); Assert.Equal(MessageEntityType.PhoneNumber, message.Type); } [Fact(DisplayName = "Should serialize message entity with phone number type")] public void Should_Serialize_Message_Entity_With_Phone_Number_Type() { var messageEntity = new MessageEntity { Length = 10, Offset = 10, Type = MessageEntityType.PhoneNumber }; var json = JsonConvert.SerializeObject(messageEntity); Assert.NotNull(json); Assert.True(json.Length > 10); Assert.Contains(@"""type"":""phone_number""", json); } [Fact(DisplayName = "Should deserialize message entity with unknown type")] public void Should_Deserialize_Message_Entity_With_Unknown_Type() { const string json = @"{ ""offset"": 10, ""length"": 10, ""type"": ""totally_unknown_type"" }"; var message = JsonConvert.DeserializeObject<MessageEntity>(json); Assert.Equal((MessageEntityType)0, message.Type); } [Fact(DisplayName = "Should serialize message entity with unknown type")] public void Should_Serialize_Message_Entity_With_Unknown_Type() { var messageEntity = new MessageEntity { Length = 10, Offset = 10, Type = 0 }; var json = JsonConvert.SerializeObject(messageEntity); Assert.NotNull(json); Assert.True(json.Length > 10); Assert.Contains(@"""type"":""unknown""", json); } } }
31.657534
88
0.566421
[ "MIT" ]
AKomyshan/Telegram.Bot
test/Telegram.Bot.Tests.Unit/Serialization/MessageEntityTests.cs
2,313
C#
using System; using Terminal.Gui; namespace tempalted { class Box10x : View { public Box10x (int x, int y) : base (new Rect (x, y, 10, 10)) { } public override void Redraw (Rect region) { Driver.SetAttribute (ColorScheme.Focus); for (int y = 0; y < 10; y++) { Move (0, y); for (int x = 0; x < 10; x++) { Driver.AddRune ((Rune)('0' + (x + y) % 10)); } } } } }
22.695652
69
0.415709
[ "MIT" ]
smacken/templated
Views/Box10x.cs
522
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.open.app.property.message.send /// </summary> public class AlipayOpenAppPropertyMessageSendRequest : IAopRequest<AlipayOpenAppPropertyMessageSendResponse> { /// <summary> /// 社区物业消息发送 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.open.app.property.message.send"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.681818
112
0.606526
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Request/AlipayOpenAppPropertyMessageSendRequest.cs
2,621
C#
namespace RazorLight.Internal { public interface ICharBufferSource { char[] Rent(int bufferSize); void Return(char[] buffer); } }
16
38
0.625
[ "MIT" ]
Rizzen/Blog.Core
src/RazorLight/Internal/Buffering/ICharBufferSource.cs
162
C#
using System; using System.Collections.Generic; using System.Text.Json.Serialization; namespace API.Models { public class PaginatedList<T> { public IList<T> Items { get; } public int PageIndex { get; } public int TotalPages { get; } public int TotalCount { get; } public PaginatedList(IList<T> items, int count, int pageIndex, int pageSize) { PageIndex = pageIndex; TotalPages = (int)Math.Ceiling(count / (double)pageSize); TotalCount = count; Items = items; } public bool HasPreviousPage => PageIndex > 1; public bool HasNextPage => PageIndex < TotalPages; } }
25.888889
84
0.60372
[ "MIT" ]
M-Meydan/SwoopFundingTest
CompanyHouse/Models/PaginatedList.cs
701
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.ResourceManager; using Azure.ResourceManager.KeyVault.Models; using Azure.ResourceManager.Resources; namespace Azure.ResourceManager.KeyVault { /// <summary> A class to add extension methods to Azure.ResourceManager.KeyVault. </summary> public static partial class KeyVaultExtensions { private static SubscriptionResourceExtensionClient GetExtensionClient(SubscriptionResource subscriptionResource) { return subscriptionResource.GetCachedClient((client) => { return new SubscriptionResourceExtensionClient(client, subscriptionResource.Id); } ); } /// <summary> Gets a collection of DeletedVaultResources in the SubscriptionResource. </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <returns> An object representing collection of DeletedVaultResources and their operations over a DeletedVaultResource. </returns> public static DeletedVaultCollection GetDeletedVaults(this SubscriptionResource subscriptionResource) { return GetExtensionClient(subscriptionResource).GetDeletedVaults(); } /// <summary> /// Gets the deleted Azure key vault. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/locations/{location}/deletedVaults/{vaultName} /// Operation Id: Vaults_GetDeleted /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="location"> The location of the deleted vault. </param> /// <param name="vaultName"> The name of the vault. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="vaultName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="vaultName"/> is null. </exception> [ForwardsClientCalls] public static async Task<Response<DeletedVaultResource>> GetDeletedVaultAsync(this SubscriptionResource subscriptionResource, AzureLocation location, string vaultName, CancellationToken cancellationToken = default) { return await subscriptionResource.GetDeletedVaults().GetAsync(location, vaultName, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the deleted Azure key vault. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/locations/{location}/deletedVaults/{vaultName} /// Operation Id: Vaults_GetDeleted /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="location"> The location of the deleted vault. </param> /// <param name="vaultName"> The name of the vault. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="vaultName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="vaultName"/> is null. </exception> [ForwardsClientCalls] public static Response<DeletedVaultResource> GetDeletedVault(this SubscriptionResource subscriptionResource, AzureLocation location, string vaultName, CancellationToken cancellationToken = default) { return subscriptionResource.GetDeletedVaults().Get(location, vaultName, cancellationToken); } /// <summary> Gets a collection of DeletedManagedHsmResources in the SubscriptionResource. </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <returns> An object representing collection of DeletedManagedHsmResources and their operations over a DeletedManagedHsmResource. </returns> public static DeletedManagedHsmCollection GetDeletedManagedHsms(this SubscriptionResource subscriptionResource) { return GetExtensionClient(subscriptionResource).GetDeletedManagedHsms(); } /// <summary> /// Gets the specified deleted managed HSM. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/locations/{location}/deletedManagedHSMs/{name} /// Operation Id: ManagedHsms_GetDeleted /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="location"> The location of the deleted managed HSM. </param> /// <param name="name"> The name of the deleted managed HSM. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="name"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="name"/> is null. </exception> [ForwardsClientCalls] public static async Task<Response<DeletedManagedHsmResource>> GetDeletedManagedHsmAsync(this SubscriptionResource subscriptionResource, AzureLocation location, string name, CancellationToken cancellationToken = default) { return await subscriptionResource.GetDeletedManagedHsms().GetAsync(location, name, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified deleted managed HSM. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/locations/{location}/deletedManagedHSMs/{name} /// Operation Id: ManagedHsms_GetDeleted /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="location"> The location of the deleted managed HSM. </param> /// <param name="name"> The name of the deleted managed HSM. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="name"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="name"/> is null. </exception> [ForwardsClientCalls] public static Response<DeletedManagedHsmResource> GetDeletedManagedHsm(this SubscriptionResource subscriptionResource, AzureLocation location, string name, CancellationToken cancellationToken = default) { return subscriptionResource.GetDeletedManagedHsms().Get(location, name, cancellationToken); } /// <summary> /// The List operation gets information about the vaults associated with the subscription. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/vaults /// Operation Id: Vaults_ListBySubscription /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="top"> Maximum number of results to return. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> An async collection of <see cref="VaultResource" /> that may take multiple service requests to iterate over. </returns> public static AsyncPageable<VaultResource> GetVaultsAsync(this SubscriptionResource subscriptionResource, int? top = null, CancellationToken cancellationToken = default) { return GetExtensionClient(subscriptionResource).GetVaultsAsync(top, cancellationToken); } /// <summary> /// The List operation gets information about the vaults associated with the subscription. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/vaults /// Operation Id: Vaults_ListBySubscription /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="top"> Maximum number of results to return. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> A collection of <see cref="VaultResource" /> that may take multiple service requests to iterate over. </returns> public static Pageable<VaultResource> GetVaults(this SubscriptionResource subscriptionResource, int? top = null, CancellationToken cancellationToken = default) { return GetExtensionClient(subscriptionResource).GetVaults(top, cancellationToken); } /// <summary> /// Gets information about the deleted vaults in a subscription. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/deletedVaults /// Operation Id: Vaults_ListDeleted /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> An async collection of <see cref="DeletedVaultResource" /> that may take multiple service requests to iterate over. </returns> public static AsyncPageable<DeletedVaultResource> GetDeletedVaultsAsync(this SubscriptionResource subscriptionResource, CancellationToken cancellationToken = default) { return GetExtensionClient(subscriptionResource).GetDeletedVaultsAsync(cancellationToken); } /// <summary> /// Gets information about the deleted vaults in a subscription. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/deletedVaults /// Operation Id: Vaults_ListDeleted /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> A collection of <see cref="DeletedVaultResource" /> that may take multiple service requests to iterate over. </returns> public static Pageable<DeletedVaultResource> GetDeletedVaults(this SubscriptionResource subscriptionResource, CancellationToken cancellationToken = default) { return GetExtensionClient(subscriptionResource).GetDeletedVaults(cancellationToken); } /// <summary> /// Checks that the vault name is valid and is not already in use. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/checkNameAvailability /// Operation Id: Vaults_CheckNameAvailability /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="content"> The name of the vault. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception> public static async Task<Response<VaultNameAvailabilityResult>> CheckVaultNameAvailabilityAsync(this SubscriptionResource subscriptionResource, VaultNameAvailabilityContent content, CancellationToken cancellationToken = default) { Argument.AssertNotNull(content, nameof(content)); return await GetExtensionClient(subscriptionResource).CheckVaultNameAvailabilityAsync(content, cancellationToken).ConfigureAwait(false); } /// <summary> /// Checks that the vault name is valid and is not already in use. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/checkNameAvailability /// Operation Id: Vaults_CheckNameAvailability /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="content"> The name of the vault. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception> public static Response<VaultNameAvailabilityResult> CheckVaultNameAvailability(this SubscriptionResource subscriptionResource, VaultNameAvailabilityContent content, CancellationToken cancellationToken = default) { Argument.AssertNotNull(content, nameof(content)); return GetExtensionClient(subscriptionResource).CheckVaultNameAvailability(content, cancellationToken); } /// <summary> /// The List operation gets information about the managed HSM Pools associated with the subscription. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/managedHSMs /// Operation Id: ManagedHsms_ListBySubscription /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="top"> Maximum number of results to return. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> An async collection of <see cref="ManagedHsmResource" /> that may take multiple service requests to iterate over. </returns> public static AsyncPageable<ManagedHsmResource> GetManagedHsmsAsync(this SubscriptionResource subscriptionResource, int? top = null, CancellationToken cancellationToken = default) { return GetExtensionClient(subscriptionResource).GetManagedHsmsAsync(top, cancellationToken); } /// <summary> /// The List operation gets information about the managed HSM Pools associated with the subscription. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/managedHSMs /// Operation Id: ManagedHsms_ListBySubscription /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="top"> Maximum number of results to return. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> A collection of <see cref="ManagedHsmResource" /> that may take multiple service requests to iterate over. </returns> public static Pageable<ManagedHsmResource> GetManagedHsms(this SubscriptionResource subscriptionResource, int? top = null, CancellationToken cancellationToken = default) { return GetExtensionClient(subscriptionResource).GetManagedHsms(top, cancellationToken); } /// <summary> /// The List operation gets information about the deleted managed HSMs associated with the subscription. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/deletedManagedHSMs /// Operation Id: ManagedHsms_ListDeleted /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> An async collection of <see cref="DeletedManagedHsmResource" /> that may take multiple service requests to iterate over. </returns> public static AsyncPageable<DeletedManagedHsmResource> GetDeletedManagedHsmsAsync(this SubscriptionResource subscriptionResource, CancellationToken cancellationToken = default) { return GetExtensionClient(subscriptionResource).GetDeletedManagedHsmsAsync(cancellationToken); } /// <summary> /// The List operation gets information about the deleted managed HSMs associated with the subscription. /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/deletedManagedHSMs /// Operation Id: ManagedHsms_ListDeleted /// </summary> /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <returns> A collection of <see cref="DeletedManagedHsmResource" /> that may take multiple service requests to iterate over. </returns> public static Pageable<DeletedManagedHsmResource> GetDeletedManagedHsms(this SubscriptionResource subscriptionResource, CancellationToken cancellationToken = default) { return GetExtensionClient(subscriptionResource).GetDeletedManagedHsms(cancellationToken); } private static ResourceGroupResourceExtensionClient GetExtensionClient(ResourceGroupResource resourceGroupResource) { return resourceGroupResource.GetCachedClient((client) => { return new ResourceGroupResourceExtensionClient(client, resourceGroupResource.Id); } ); } /// <summary> Gets a collection of VaultResources in the ResourceGroupResource. </summary> /// <param name="resourceGroupResource"> The <see cref="ResourceGroupResource" /> instance the method will execute against. </param> /// <returns> An object representing collection of VaultResources and their operations over a VaultResource. </returns> public static VaultCollection GetVaults(this ResourceGroupResource resourceGroupResource) { return GetExtensionClient(resourceGroupResource).GetVaults(); } /// <summary> /// Gets the specified Azure key vault. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName} /// Operation Id: Vaults_Get /// </summary> /// <param name="resourceGroupResource"> The <see cref="ResourceGroupResource" /> instance the method will execute against. </param> /// <param name="vaultName"> The name of the vault. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="vaultName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="vaultName"/> is null. </exception> [ForwardsClientCalls] public static async Task<Response<VaultResource>> GetVaultAsync(this ResourceGroupResource resourceGroupResource, string vaultName, CancellationToken cancellationToken = default) { return await resourceGroupResource.GetVaults().GetAsync(vaultName, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Azure key vault. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName} /// Operation Id: Vaults_Get /// </summary> /// <param name="resourceGroupResource"> The <see cref="ResourceGroupResource" /> instance the method will execute against. </param> /// <param name="vaultName"> The name of the vault. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="vaultName"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="vaultName"/> is null. </exception> [ForwardsClientCalls] public static Response<VaultResource> GetVault(this ResourceGroupResource resourceGroupResource, string vaultName, CancellationToken cancellationToken = default) { return resourceGroupResource.GetVaults().Get(vaultName, cancellationToken); } /// <summary> Gets a collection of ManagedHsmResources in the ResourceGroupResource. </summary> /// <param name="resourceGroupResource"> The <see cref="ResourceGroupResource" /> instance the method will execute against. </param> /// <returns> An object representing collection of ManagedHsmResources and their operations over a ManagedHsmResource. </returns> public static ManagedHsmCollection GetManagedHsms(this ResourceGroupResource resourceGroupResource) { return GetExtensionClient(resourceGroupResource).GetManagedHsms(); } /// <summary> /// Gets the specified managed HSM Pool. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name} /// Operation Id: ManagedHsms_Get /// </summary> /// <param name="resourceGroupResource"> The <see cref="ResourceGroupResource" /> instance the method will execute against. </param> /// <param name="name"> The name of the managed HSM Pool. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="name"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="name"/> is null. </exception> [ForwardsClientCalls] public static async Task<Response<ManagedHsmResource>> GetManagedHsmAsync(this ResourceGroupResource resourceGroupResource, string name, CancellationToken cancellationToken = default) { return await resourceGroupResource.GetManagedHsms().GetAsync(name, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified managed HSM Pool. /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/managedHSMs/{name} /// Operation Id: ManagedHsms_Get /// </summary> /// <param name="resourceGroupResource"> The <see cref="ResourceGroupResource" /> instance the method will execute against. </param> /// <param name="name"> The name of the managed HSM Pool. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentException"> <paramref name="name"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="ArgumentNullException"> <paramref name="name"/> is null. </exception> [ForwardsClientCalls] public static Response<ManagedHsmResource> GetManagedHsm(this ResourceGroupResource resourceGroupResource, string name, CancellationToken cancellationToken = default) { return resourceGroupResource.GetManagedHsms().Get(name, cancellationToken); } #region VaultResource /// <summary> /// Gets an object representing a <see cref="VaultResource" /> along with the instance operations that can be performed on it but with no data. /// You can use <see cref="VaultResource.CreateResourceIdentifier" /> to create a <see cref="VaultResource" /> <see cref="ResourceIdentifier" /> from its components. /// </summary> /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param> /// <param name="id"> The resource ID of the resource to get. </param> /// <returns> Returns a <see cref="VaultResource" /> object. </returns> public static VaultResource GetVaultResource(this ArmClient client, ResourceIdentifier id) { return client.GetResourceClient(() => { VaultResource.ValidateResourceId(id); return new VaultResource(client, id); } ); } #endregion #region DeletedVaultResource /// <summary> /// Gets an object representing a <see cref="DeletedVaultResource" /> along with the instance operations that can be performed on it but with no data. /// You can use <see cref="DeletedVaultResource.CreateResourceIdentifier" /> to create a <see cref="DeletedVaultResource" /> <see cref="ResourceIdentifier" /> from its components. /// </summary> /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param> /// <param name="id"> The resource ID of the resource to get. </param> /// <returns> Returns a <see cref="DeletedVaultResource" /> object. </returns> public static DeletedVaultResource GetDeletedVaultResource(this ArmClient client, ResourceIdentifier id) { return client.GetResourceClient(() => { DeletedVaultResource.ValidateResourceId(id); return new DeletedVaultResource(client, id); } ); } #endregion #region KeyVaultPrivateEndpointConnectionResource /// <summary> /// Gets an object representing a <see cref="KeyVaultPrivateEndpointConnectionResource" /> along with the instance operations that can be performed on it but with no data. /// You can use <see cref="KeyVaultPrivateEndpointConnectionResource.CreateResourceIdentifier" /> to create a <see cref="KeyVaultPrivateEndpointConnectionResource" /> <see cref="ResourceIdentifier" /> from its components. /// </summary> /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param> /// <param name="id"> The resource ID of the resource to get. </param> /// <returns> Returns a <see cref="KeyVaultPrivateEndpointConnectionResource" /> object. </returns> public static KeyVaultPrivateEndpointConnectionResource GetKeyVaultPrivateEndpointConnectionResource(this ArmClient client, ResourceIdentifier id) { return client.GetResourceClient(() => { KeyVaultPrivateEndpointConnectionResource.ValidateResourceId(id); return new KeyVaultPrivateEndpointConnectionResource(client, id); } ); } #endregion #region ManagedHsmResource /// <summary> /// Gets an object representing a <see cref="ManagedHsmResource" /> along with the instance operations that can be performed on it but with no data. /// You can use <see cref="ManagedHsmResource.CreateResourceIdentifier" /> to create a <see cref="ManagedHsmResource" /> <see cref="ResourceIdentifier" /> from its components. /// </summary> /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param> /// <param name="id"> The resource ID of the resource to get. </param> /// <returns> Returns a <see cref="ManagedHsmResource" /> object. </returns> public static ManagedHsmResource GetManagedHsmResource(this ArmClient client, ResourceIdentifier id) { return client.GetResourceClient(() => { ManagedHsmResource.ValidateResourceId(id); return new ManagedHsmResource(client, id); } ); } #endregion #region DeletedManagedHsmResource /// <summary> /// Gets an object representing a <see cref="DeletedManagedHsmResource" /> along with the instance operations that can be performed on it but with no data. /// You can use <see cref="DeletedManagedHsmResource.CreateResourceIdentifier" /> to create a <see cref="DeletedManagedHsmResource" /> <see cref="ResourceIdentifier" /> from its components. /// </summary> /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param> /// <param name="id"> The resource ID of the resource to get. </param> /// <returns> Returns a <see cref="DeletedManagedHsmResource" /> object. </returns> public static DeletedManagedHsmResource GetDeletedManagedHsmResource(this ArmClient client, ResourceIdentifier id) { return client.GetResourceClient(() => { DeletedManagedHsmResource.ValidateResourceId(id); return new DeletedManagedHsmResource(client, id); } ); } #endregion #region ManagedHsmPrivateEndpointConnectionResource /// <summary> /// Gets an object representing a <see cref="ManagedHsmPrivateEndpointConnectionResource" /> along with the instance operations that can be performed on it but with no data. /// You can use <see cref="ManagedHsmPrivateEndpointConnectionResource.CreateResourceIdentifier" /> to create a <see cref="ManagedHsmPrivateEndpointConnectionResource" /> <see cref="ResourceIdentifier" /> from its components. /// </summary> /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param> /// <param name="id"> The resource ID of the resource to get. </param> /// <returns> Returns a <see cref="ManagedHsmPrivateEndpointConnectionResource" /> object. </returns> public static ManagedHsmPrivateEndpointConnectionResource GetManagedHsmPrivateEndpointConnectionResource(this ArmClient client, ResourceIdentifier id) { return client.GetResourceClient(() => { ManagedHsmPrivateEndpointConnectionResource.ValidateResourceId(id); return new ManagedHsmPrivateEndpointConnectionResource(client, id); } ); } #endregion } }
66.372549
236
0.692007
[ "MIT" ]
damodaravadhani/azure-sdk-for-net
sdk/keyvault/Azure.ResourceManager.KeyVault/src/Generated/Extensions/KeyVaultExtensions.cs
30,465
C#
namespace NLua.Method { public class LuaEventHandler { public LuaFunction Handler = null; public void HandleEvent(object[] args) { Handler.Call(args); } } }
17.75
46
0.558685
[ "MIT" ]
Auios/NLua
src/Method/LuaEventHandler.cs
213
C#
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Hazelcast.IO.Serialization; using NUnit.Framework; namespace Hazelcast.Client.Test.Serialization { public class ClassAndFieldDefinitionTest { private readonly int portableVersion = 1; private static readonly string[] fieldNames = {"f1", "f2", "f3"}; private ClassDefinition classDefinition; [SetUp] public virtual void SetUp() { var builder = new ClassDefinitionBuilder(1, 2, 3); foreach (var fieldName in fieldNames) { builder.AddByteField(fieldName); } classDefinition = (ClassDefinition) builder.Build(); } [Test] public virtual void TestClassDef_equal_hashCode() { var cdEmpty1 = (ClassDefinition) new ClassDefinitionBuilder(1, 2, 3).Build(); var cdEmpty2 = (ClassDefinition) new ClassDefinitionBuilder(1, 2, 3).Build(); var cd1 = (ClassDefinition) new ClassDefinitionBuilder(1, 2, 5).Build(); var cd2 = (ClassDefinition) new ClassDefinitionBuilder(2, 2, 3).Build(); var cd3 = (ClassDefinition) new ClassDefinitionBuilder(1, 9, 3).Build(); var cdWithField = (ClassDefinition) new ClassDefinitionBuilder(1, 2, 3).AddIntField("f1").Build(); Assert.AreEqual(cdEmpty1, cdEmpty2); Assert.AreNotEqual(cd1, cdEmpty1); Assert.AreNotEqual(cd2, cdEmpty1); Assert.AreNotEqual(cd3, cdEmpty1); Assert.AreNotEqual(cdWithField, classDefinition); Assert.AreNotEqual(cdEmpty1, classDefinition); Assert.AreNotEqual(classDefinition, null); Assert.AreNotEqual(classDefinition, "Another Class"); Assert.AreNotEqual(0, cd1.GetHashCode()); } public virtual void TestClassDef_getField_HigherThenSizeIndex() { classDefinition.GetField(classDefinition.GetFieldCount()); } public virtual void TestClassDef_getField_negativeIndex() { classDefinition.GetField(-1); } [Test] public virtual void TestClassDef_getField_properIndex() { for (var i = 0; i < classDefinition.GetFieldCount(); i++) { var field = classDefinition.GetField(i); Assert.IsNotNull(field); } } [Test] public virtual void TestClassDef_getFieldClassId() { foreach (var fieldName in fieldNames) { var classId = classDefinition.GetFieldClassId(fieldName); Assert.AreEqual(0, classId); } } public virtual void TestClassDef_getFieldClassId_invalidField() { classDefinition.GetFieldClassId("The Invalid Field"); } [Test] public virtual void TestClassDef_getFieldType() { foreach (var fieldName in fieldNames) { var fieldType = classDefinition.GetFieldType(fieldName); Assert.IsNotNull(fieldType); } } public virtual void TestClassDef_getFieldType_invalidField() { classDefinition.GetFieldType("The Invalid Field"); } [Test] public virtual void TestClassDef_getter_setter() { var cd = (ClassDefinition) new ClassDefinitionBuilder(1, 2, portableVersion).Build(); cd.SetVersionIfNotSet(3); cd.SetVersionIfNotSet(5); Assert.AreEqual(1, cd.GetFactoryId()); Assert.AreEqual(2, cd.GetClassId()); Assert.AreEqual(portableVersion, cd.GetVersion()); Assert.AreEqual(3, classDefinition.GetFieldCount()); } [Test] public virtual void TestClassDef_hasField() { for (var i = 0; i < classDefinition.GetFieldCount(); i++) { var fieldName = fieldNames[i]; var hasField = classDefinition.HasField(fieldName); Assert.IsTrue(hasField); } } [Test] public virtual void TestClassDef_toString() { Assert.IsNotNull(classDefinition.ToString()); } [Test] public virtual void TestFieldDef_equal_hashCode() { var fd0 = new FieldDefinition(0, "name", FieldType.Boolean, portableVersion); var fd0_1 = new FieldDefinition(0, "name", FieldType.Int, portableVersion); var fd1 = new FieldDefinition(1, "name", FieldType.Boolean, portableVersion); var fd2 = new FieldDefinition(0, "namex", FieldType.Boolean, portableVersion); Assert.AreNotEqual(fd0, fd0_1); Assert.AreNotEqual(fd0, fd1); Assert.AreNotEqual(fd0, fd2); Assert.AreNotEqual(fd0, null); Assert.AreNotEqual(fd0, "Another Class"); Assert.AreNotEqual(0, fd0.GetHashCode()); } [Test] public virtual void TestFieldDef_getter_setter() { var field0 = classDefinition.GetField(0); var field = classDefinition.GetField("f1"); var fd = new FieldDefinition(9, "name", FieldType.Portable, 5, 6, 7); var fd_nullName = new FieldDefinition(10, null, FieldType.Portable, 15, 16, 17); Assert.AreEqual(field, field0); Assert.AreEqual(0, field.GetFactoryId()); Assert.AreEqual(0, field.GetClassId()); Assert.AreEqual(3, field.GetVersion()); Assert.AreEqual(0, field.GetIndex()); Assert.AreEqual("f1", field.GetName()); Assert.AreEqual(FieldType.Byte, field.GetFieldType()); Assert.AreEqual(5, fd.GetFactoryId()); Assert.AreEqual(6, fd.GetClassId()); Assert.AreEqual(7, fd.GetVersion()); Assert.AreEqual(9, fd.GetIndex()); Assert.AreEqual("name", fd.GetName()); Assert.AreEqual(FieldType.Portable, fd.GetFieldType()); Assert.AreEqual(15, fd_nullName.GetFactoryId()); Assert.AreEqual(16, fd_nullName.GetClassId()); Assert.AreEqual(17, fd_nullName.GetVersion()); Assert.AreEqual(10, fd_nullName.GetIndex()); Assert.AreEqual(null, fd_nullName.GetName()); Assert.AreEqual(FieldType.Portable, fd_nullName.GetFieldType()); } [Test] public virtual void TestFieldDef_toString() { Assert.IsNotNull(new FieldDefinition(0, "name", FieldType.Boolean, portableVersion).ToString()); } } }
37.838542
108
0.602202
[ "Apache-2.0" ]
asimarslan/hazelcast-csharp-client
Hazelcast.Test/Hazelcast.Client.Test.Serialization/ClassAndFieldDefinitionTest.cs
7,267
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.StorSimple { /// <summary> /// The access control record. /// API Version: 2017-06-01. /// </summary> [AzureNativeResourceType("azure-native:storsimple:AccessControlRecord")] public partial class AccessControlRecord : Pulumi.CustomResource { /// <summary> /// The iSCSI initiator name (IQN). /// </summary> [Output("initiatorName")] public Output<string> InitiatorName { get; private set; } = null!; /// <summary> /// The Kind of the object. Currently only Series8000 is supported /// </summary> [Output("kind")] public Output<string?> Kind { get; private set; } = null!; /// <summary> /// The name of the object. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The hierarchical type of the object. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// The number of volumes using the access control record. /// </summary> [Output("volumeCount")] public Output<int> VolumeCount { get; private set; } = null!; /// <summary> /// Create a AccessControlRecord resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public AccessControlRecord(string name, AccessControlRecordArgs args, CustomResourceOptions? options = null) : base("azure-native:storsimple:AccessControlRecord", name, args ?? new AccessControlRecordArgs(), MakeResourceOptions(options, "")) { } private AccessControlRecord(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:storsimple:AccessControlRecord", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:storsimple:AccessControlRecord"}, new Pulumi.Alias { Type = "azure-native:storsimple/latest:AccessControlRecord"}, new Pulumi.Alias { Type = "azure-nextgen:storsimple/latest:AccessControlRecord"}, new Pulumi.Alias { Type = "azure-native:storsimple/v20161001:AccessControlRecord"}, new Pulumi.Alias { Type = "azure-nextgen:storsimple/v20161001:AccessControlRecord"}, new Pulumi.Alias { Type = "azure-native:storsimple/v20170601:AccessControlRecord"}, new Pulumi.Alias { Type = "azure-nextgen:storsimple/v20170601:AccessControlRecord"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing AccessControlRecord resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static AccessControlRecord Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new AccessControlRecord(name, id, options); } } public sealed class AccessControlRecordArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the access control record. /// </summary> [Input("accessControlRecordName")] public Input<string>? AccessControlRecordName { get; set; } /// <summary> /// The iSCSI initiator name (IQN). /// </summary> [Input("initiatorName", required: true)] public Input<string> InitiatorName { get; set; } = null!; /// <summary> /// The Kind of the object. Currently only Series8000 is supported /// </summary> [Input("kind")] public Input<Pulumi.AzureNative.StorSimple.Kind>? Kind { get; set; } /// <summary> /// The manager name /// </summary> [Input("managerName", required: true)] public Input<string> ManagerName { get; set; } = null!; /// <summary> /// The resource group name /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; public AccessControlRecordArgs() { } } }
40.863309
144
0.602993
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/StorSimple/AccessControlRecord.cs
5,680
C#
using System; using MathNet.Numerics.LinearAlgebra; using PuzzleBox.NeuralNets.Algebra; using PuzzleBox.NeuralNets.Training; namespace PuzzleBox.NeuralNets.Layers.Weighted { public class DenseLayer : WeightsLayerBase { public DenseLayer(Size inputSize, Size outputSize) : base(inputSize, outputSize) { _weights = Matrix<float>.Build.Dense(outputSize.Length, inputSize.Length) .InsertColumn(0, Vector<float>.Build.Dense(outputSize.Length, 1)); // Bias; _weights.InitRandom(); } public DenseLayer(int inputLength, int outputLength) : this(new Size(inputLength), new Size(outputLength)) { } protected override Tensor FeedForwardsInternal(Tensor input) { var inputWithBias = Vector<float>.Build.Dense(input.Value.Count + 1, 1); inputWithBias.SetSubVector(1, input.Value.Count, input); return new Tensor(OutputSize.Clone(), _weights * inputWithBias); } public override void BackPropagate(TrainingRun trainingRun) { var inputError = _weights.Transpose() * trainingRun.OutputError.Value; trainingRun.InputError = inputError.SubVector(1, inputError.Count - 1); trainingRun.WeightsDelta = CalcWeightsDelta(trainingRun.Input, trainingRun.OutputError); } private Matrix<float> CalcWeightsDelta(Tensor input, Tensor outputError) { var inputWithBias = Vector<float>.Build.Dense(input.Value.Count + 1, 1); inputWithBias.SetSubVector(1, input.Value.Count, input); return outputError.Value.OuterProduct(inputWithBias); } } public static class FullyConnNetExt { public static Net Dense(this Net net, Size outputSize) { net.Add(new DenseLayer(net.OutputSize, outputSize)); return net; } public static Net Dense(this Net net, int outputsize) { return net.Dense(new Size(outputsize)); } } }
36.637931
101
0.625882
[ "Apache-2.0" ]
JasonKStevens/PuzzleBox.NeuralNets
PuzzleBox.NeuralNets/Layers/Weighted/DenseLayer.cs
2,127
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SortudoFeliz { public class NumeroSortudo { public static bool Sortudo(int numero) { bool resultado = false; for (int i = 2; i < numero; i++) { int resto = numero % i; if (resto == 0) { i = numero + 1; } else { resultado = true; } } return resultado; } } }
19.8125
46
0.42429
[ "Apache-2.0" ]
asafcris/NumerosFelizesSortudos
NumeroSortudoFeliz/SortudoFeliz/NumeroSortudo.cs
636
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fritz.Serialization { // NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0. /// <remarks/> [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] public partial class contact { private byte categoryField; private contactPerson personField; private contactTelephony telephonyField; private contactServices servicesField; private object setupField; private contactFeatures featuresField; private uint mod_timeField; private byte uniqueidField; /// <remarks/> public byte category { get { return this.categoryField; } set { this.categoryField = value; } } /// <remarks/> public contactPerson person { get { return this.personField; } set { this.personField = value; } } /// <remarks/> public contactTelephony telephony { get { return this.telephonyField; } set { this.telephonyField = value; } } /// <remarks/> public contactServices services { get { return this.servicesField; } set { this.servicesField = value; } } /// <remarks/> public object setup { get { return this.setupField; } set { this.setupField = value; } } /// <remarks/> public contactFeatures features { get { return this.featuresField; } set { this.featuresField = value; } } /// <remarks/> public uint mod_time { get { return this.mod_timeField; } set { this.mod_timeField = value; } } /// <remarks/> public byte uniqueid { get { return this.uniqueidField; } set { this.uniqueidField = value; } } } /// <remarks/> [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class contactPerson { private string realNameField; private string imageURLField; /// <remarks/> public string realName { get { return this.realNameField; } set { this.realNameField = value; } } /// <remarks/> public string imageURL { get { return this.imageURLField; } set { this.imageURLField = value; } } } /// <remarks/> [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class contactTelephony { private contactTelephonyNumber[] numberField; private byte nidField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("number")] public contactTelephonyNumber[] number { get { return this.numberField; } set { this.numberField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public byte nid { get { return this.nidField; } set { this.nidField = value; } } } /// <remarks/> [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class contactTelephonyNumber { private string typeField; private byte prioField; private bool prioFieldSpecified; private byte idField; private string valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string type { get { return this.typeField; } set { this.typeField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public byte prio { get { return this.prioField; } set { this.prioField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool prioSpecified { get { return this.prioFieldSpecified; } set { this.prioFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public byte id { get { return this.idField; } set { this.idField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string Value { get { return this.valueField; } set { this.valueField = value; } } } /// <remarks/> [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class contactServices { private contactServicesEmail emailField; private byte nidField; /// <remarks/> public contactServicesEmail email { get { return this.emailField; } set { this.emailField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public byte nid { get { return this.nidField; } set { this.nidField = value; } } } /// <remarks/> [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class contactServicesEmail { private string classifierField; private byte idField; private string valueField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string classifier { get { return this.classifierField; } set { this.classifierField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public byte id { get { return this.idField; } set { this.idField = value; } } /// <remarks/> [System.Xml.Serialization.XmlTextAttribute()] public string Value { get { return this.valueField; } set { this.valueField = value; } } } /// <remarks/> [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class contactFeatures { private byte doorphoneField; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public byte doorphone { get { return this.doorphoneField; } set { this.doorphoneField = value; } } } }
22.033097
94
0.460515
[ "MIT" ]
chstorb/Fritz
Fritz/Serialization/Contact.cs
9,322
C#
namespace BasicSalesSystem.Web.Requests.Customer { using FluentValidation; public class GetCustomersListRequest { public string SearchQuery { get; set; } public string SortBy { get; set; } public bool SortDesc { get; set; } public int Page { get; set; } public int PageSize { get; set; } } public class GetCustomersListRequestValidator : AbstractValidator<GetCustomersListRequest> { public GetCustomersListRequestValidator() { } } }
24.363636
52
0.632463
[ "MIT" ]
fcapellino/net-core-vuetify-mongodb-sales-system
BasicSalesSystem.Web/Requests/Customer/GetCustomersListRequest.cs
538
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; namespace Microsoft.Owin.FileSystems { /// <summary> /// Looks up files using the on-disk file system /// </summary> public class PhysicalFileSystem : IFileSystem { // These are restricted file names on Windows, regardless of extension. private static readonly Dictionary<string, string> RestrictedFileNames = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "con", string.Empty }, { "prn", string.Empty }, { "aux", string.Empty }, { "nul", string.Empty }, { "com1", string.Empty }, { "com2", string.Empty }, { "com3", string.Empty }, { "com4", string.Empty }, { "com5", string.Empty }, { "com6", string.Empty }, { "com7", string.Empty }, { "com8", string.Empty }, { "com9", string.Empty }, { "lpt1", string.Empty }, { "lpt2", string.Empty }, { "lpt3", string.Empty }, { "lpt4", string.Empty }, { "lpt5", string.Empty }, { "lpt6", string.Empty }, { "lpt7", string.Empty }, { "lpt8", string.Empty }, { "lpt9", string.Empty }, { "clock$", string.Empty }, }; /// <summary> /// Creates a new instance of a PhysicalFileSystem at the given root directory. /// </summary> /// <param name="root">The root directory</param> public PhysicalFileSystem(string root) { Root = GetFullRoot(root); if (!Directory.Exists(Root)) { throw new DirectoryNotFoundException(Root); } } /// <summary> /// The root directory for this instance. /// </summary> public string Root { get; private set; } private static string GetFullRoot(string root) { var applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; var fullRoot = Path.GetFullPath(Path.Combine(applicationBase, root)); if (!fullRoot.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) { // When we do matches in GetFullPath, we want to only match full directory names. fullRoot += Path.DirectorySeparatorChar; } return fullRoot; } private string GetFullPath(string path) { var fullPath = Path.GetFullPath(Path.Combine(Root, path)); if (!fullPath.StartsWith(Root, StringComparison.OrdinalIgnoreCase)) { return null; } return fullPath; } /// <summary> /// Locate a file at the given path by directly mapping path segments to physical directories. /// </summary> /// <param name="subpath">A path under the root directory</param> /// <param name="fileInfo">The discovered file, if any</param> /// <returns>True if a file was discovered at the given path</returns> public bool TryGetFileInfo(string subpath, out IFileInfo fileInfo) { try { if (subpath.StartsWith("/", StringComparison.Ordinal)) { subpath = subpath.Substring(1); } var fullPath = GetFullPath(subpath); if (fullPath != null) { var info = new FileInfo(fullPath); if (info.Exists && !IsRestricted(info)) { fileInfo = new PhysicalFileInfo(info); return true; } } } catch (ArgumentException) { } fileInfo = null; return false; } /// <summary> /// Enumerate a directory at the given path, if any. /// </summary> /// <param name="subpath">A path under the root directory</param> /// <param name="contents">The discovered directories, if any</param> /// <returns>True if a directory was discovered at the given path</returns> public bool TryGetDirectoryContents(string subpath, out IEnumerable<IFileInfo> contents) { try { if (subpath.StartsWith("/", StringComparison.Ordinal)) { subpath = subpath.Substring(1); } var fullPath = GetFullPath(subpath); if (fullPath != null) { var directoryInfo = new DirectoryInfo(fullPath); if (!directoryInfo.Exists) { contents = null; return false; } FileSystemInfo[] physicalInfos = directoryInfo.GetFileSystemInfos(); var virtualInfos = new IFileInfo[physicalInfos.Length]; for (int index = 0; index != physicalInfos.Length; ++index) { var fileInfo = physicalInfos[index] as FileInfo; if (fileInfo != null) { virtualInfos[index] = new PhysicalFileInfo(fileInfo); } else { virtualInfos[index] = new PhysicalDirectoryInfo((DirectoryInfo)physicalInfos[index]); } } contents = virtualInfos; return true; } } catch (ArgumentException) { } catch (DirectoryNotFoundException) { } catch (IOException) { } contents = null; return false; } private bool IsRestricted(FileInfo fileInfo) { string fileName = Path.GetFileNameWithoutExtension(fileInfo.Name); return RestrictedFileNames.ContainsKey(fileName); } private class PhysicalFileInfo : IFileInfo { private readonly FileInfo _info; public PhysicalFileInfo(FileInfo info) { _info = info; } public long Length { get { return _info.Length; } } public string PhysicalPath { get { return _info.FullName; } } public string Name { get { return _info.Name; } } public DateTime LastModified { get { return _info.LastWriteTime; } } public bool IsDirectory { get { return false; } } public Stream CreateReadStream() { // Note: Buffer size must be greater than zero, even if the file size is zero. return new FileStream(PhysicalPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1024 * 64, FileOptions.Asynchronous | FileOptions.SequentialScan); } } private class PhysicalDirectoryInfo : IFileInfo { private readonly DirectoryInfo _info; public PhysicalDirectoryInfo(DirectoryInfo info) { _info = info; } public long Length { get { return -1; } } public string PhysicalPath { get { return _info.FullName; } } public string Name { get { return _info.Name; } } public DateTime LastModified { get { return _info.LastWriteTime; } } public bool IsDirectory { get { return true; } } public Stream CreateReadStream() { return null; } } } }
32.833333
145
0.483414
[ "Apache-2.0" ]
15901213541/-OAuth2.0
src/Microsoft.Owin.FileSystems/PhysicalFileSystem.cs
8,471
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the appmesh-2019-01-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.AppMesh.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.AppMesh.Model.Internal.MarshallTransformations { /// <summary> /// VirtualGatewayListenerTlsValidationContext Marshaller /// </summary> public class VirtualGatewayListenerTlsValidationContextMarshaller : IRequestMarshaller<VirtualGatewayListenerTlsValidationContext, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(VirtualGatewayListenerTlsValidationContext requestObject, JsonMarshallerContext context) { if(requestObject.IsSetSubjectAlternativeNames()) { context.Writer.WritePropertyName("subjectAlternativeNames"); context.Writer.WriteObjectStart(); var marshaller = SubjectAlternativeNamesMarshaller.Instance; marshaller.Marshall(requestObject.SubjectAlternativeNames, context); context.Writer.WriteObjectEnd(); } if(requestObject.IsSetTrust()) { context.Writer.WritePropertyName("trust"); context.Writer.WriteObjectStart(); var marshaller = VirtualGatewayListenerTlsValidationContextTrustMarshaller.Instance; marshaller.Marshall(requestObject.Trust, context); context.Writer.WriteObjectEnd(); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static VirtualGatewayListenerTlsValidationContextMarshaller Instance = new VirtualGatewayListenerTlsValidationContextMarshaller(); } }
36.141026
158
0.692444
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/AppMesh/Generated/Model/Internal/MarshallTransformations/VirtualGatewayListenerTlsValidationContextMarshaller.cs
2,819
C#
using UnityEngine; namespace LD45 { public class Singleton<T> : MonoBehaviour where T : MonoBehaviour { private static T instance = null; public static T I { get { if (instance == null) { instance = FindObjectOfType<T>(); if (instance == null) { Debug.LogWarning("Singleton<" + typeof(T).Name + ">: Unable to find an instance"); } } return instance; } } } }
19.47619
88
0.608802
[ "MIT" ]
Xenation/Ludum-Dare-45
Assets/Scripts/Singleton.cs
411
C#
using LearnLeaderBoardKata.LeaderBoard.Core.Interfaces; using LearnLeaderBoardKata.LeaderBoard.Core.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LearnLeaderBoardKata.LeaderBoard.Core.Boards { public class RacingBoardCalculator<T> : BoardCalculator<T> where T : RaceCar { public RacingBoardCalculator(List<IScoreSortableItem<T>> scoreableItem, GameRankOrder gameRankOrder) : base(scoreableItem, gameRankOrder) { } } }
30.166667
145
0.775322
[ "Unlicense" ]
kamrul1/LearnLearderBoardKata
LearnLeaderBoardKata.LeaderBoard/Core/Boards/RacingBoardCalculator.cs
545
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iotanalytics-2017-11-27.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.IoTAnalytics.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.IoTAnalytics.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DeleteChannel operation /// </summary> public class DeleteChannelResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DeleteChannelResponse response = new DeleteChannelResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("InternalFailureException")) { return InternalFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequestException")) { return InvalidRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException")) { return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException")) { return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonIoTAnalyticsException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DeleteChannelResponseUnmarshaller _instance = new DeleteChannelResponseUnmarshaller(); internal static DeleteChannelResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteChannelResponseUnmarshaller Instance { get { return _instance; } } } }
40.947826
196
0.639839
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/IoTAnalytics/Generated/Model/Internal/MarshallTransformations/DeleteChannelResponseUnmarshaller.cs
4,709
C#
using System; using AElf.Kernel; using AElf.Sdk.CSharp.State; using AElf.Kernel.SmartContract.Sdk; using AElf.Types; using Moq; using Shouldly; using Xunit; namespace AElf.Sdk.CSharp.Tests { public class StateTest { internal T GetValue<T>() { if (typeof(T) == typeof(bool)) { return (T) (object) true; } if (typeof(T) == typeof(int)) { return (T) (object) (int) -12345; } if (typeof(T) == typeof(uint)) { return (T) (object) (uint) 12345U; } if (typeof(T) == typeof(long)) { return (T) (object) (long) -678910L; } if (typeof(T) == typeof(ulong)) { return (T) (object) (ulong) 678910UL; } if (typeof(T) == typeof(byte[])) { return (T) (object) ByteArrayHelper.HexStringToByteArray("302010"); } if (typeof(T) == typeof(string)) { return (T) (object) "aelf"; } if (typeof(T) == typeof(Address)) { return (T) (object) SampleAddress.AddressList[0]; } throw new Exception("Not supported type."); } private void SetValues(MockContractState state) { state.BoolState.Value = GetValue<bool>(); state.Int32State.Value = GetValue<int>(); state.UInt32State.Value = GetValue<uint>(); state.Int64State.Value = GetValue<long>(); state.UInt64State.Value = GetValue<ulong>(); state.StringState.Value = GetValue<string>(); state.BytesState.Value = GetValue<byte[]>(); state.StructuredState.StringState.Value = GetValue<string>(); state.MappedState[GetValue<Address>()][GetValue<Address>()] = GetValue<string>(); } private void AssertDefault(MockContractState state) { Assert.False(state.BoolState.Value); Assert.Equal(0, state.Int32State.Value); Assert.Equal(0U, state.UInt32State.Value); Assert.Equal(0, state.Int64State.Value); Assert.Equal(0U, state.UInt64State.Value); Assert.Equal("", state.StringState.Value); Assert.Null(state.BytesState.Value); Assert.Equal("", state.StructuredState.StringState.Value); Assert.Equal("", state.MappedState[GetValue<Address>()][GetValue<Address>()]); } private void AssertValues(MockContractState state) { Assert.Equal(GetValue<bool>(), state.BoolState.Value); Assert.Equal(GetValue<int>(), state.Int32State.Value); Assert.Equal(GetValue<uint>(), state.UInt32State.Value); Assert.Equal(GetValue<long>(), state.Int64State.Value); Assert.Equal(GetValue<ulong>(), state.UInt64State.Value); Assert.Equal(GetValue<string>(), state.StringState.Value); Assert.Equal(GetValue<byte[]>(), state.BytesState.Value); Assert.Equal(GetValue<string>(), state.StructuredState.StringState.Value); Assert.Equal(GetValue<string>(), state.MappedState[GetValue<Address>()][GetValue<Address>()]); } [Fact] public void State_Test() { var path = new StatePath(); path.Parts.Add("dummy_address"); var mockProvider = new Mock<IStateProvider>(); var mockContext = new Mock<ISmartContractBridgeContext>(); mockContext.SetupGet(o => o.StateProvider).Returns(mockProvider.Object); mockContext.SetupGet(o => o.Self).Returns(SampleAddress.AddressList[0]); var state = new MockContractState { Path = path, Context = new CSharpSmartContractContext(mockContext.Object) }; // Initial default value AssertDefault(state); // Set values SetValues(state); AssertValues(state); // Get changes var changes = state.GetChanges(); changes.Reads.Count.ShouldBeGreaterThan(0); changes.Writes.Count.ShouldBeGreaterThan(0); // Clear values state.Clear(); AssertDefault(state); } [Fact] public void Func_And_Action_ExtensionTest() { var state = new MockContractState() { ElfToken = new ElfTokenContractReference { Action0 = () => { }, Action1 = (x) => { }, Action2 = (x, y) => { }, Func1 = () => true, Func2 = (x) => false, Func3 = (x, y) => x + y } }; //func test var func1 = state.ElfToken.Func1.GetType(); func1.IsFunc().ShouldBeTrue(); func1.IsAction().ShouldBeFalse(); var func2 = state.ElfToken.Func2.GetType(); func2.IsFunc().ShouldBeTrue(); func2.IsAction().ShouldBeFalse(); var func3 = state.ElfToken.Func3.GetType(); func3.IsFunc().ShouldBeTrue(); func3.IsAction().ShouldBeFalse(); //action test var action0 = state.ElfToken.Action0.GetType(); action0.IsAction().ShouldBeTrue(); action0.IsFunc().ShouldBeFalse(); var action1 = state.ElfToken.Action1.GetType(); action1.IsAction().ShouldBeTrue(); action1.IsFunc().ShouldBeFalse(); var action2 = state.ElfToken.Action2.GetType(); action2.IsAction().ShouldBeTrue(); action2.IsFunc().ShouldBeFalse(); } } }
33.982857
106
0.523457
[ "MIT" ]
IamWenboZhang/AElf
test/AElf.Sdk.CSharp.Tests/StateTest.cs
5,947
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.commerce.cityfacilitator.script.query /// </summary> public class AlipayCommerceCityfacilitatorScriptQueryRequest : IAopRequest<AlipayCommerceCityfacilitatorScriptQueryResponse> { /// <summary> /// 查询城市一卡通的判卡、读卡脚本 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.commerce.cityfacilitator.script.query"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public void PutOtherTextParam(string key, string value) { if(this.udfParams == null) { this.udfParams = new Dictionary<string, string>(); } this.udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); if(udfParams != null) { parameters.AddAll(this.udfParams); } return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
26.217742
129
0.570901
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Request/AlipayCommerceCityfacilitatorScriptQueryRequest.cs
3,281
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Discord; using Discord.WebSocket; using DiscordBot.Data; using DiscordBot.Extensions; using HtmlAgilityPack; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace DiscordBot.Services { public class BotData { public DateTime LastPublisherCheck { get; set; } public List<ulong> LastPublisherId { get; set; } public DateTime LastUnityDocDatabaseUpdate { get; set; } } public class UserData { public Dictionary<ulong, DateTime> MutedUsers { get; set; } public Dictionary<ulong, DateTime> ThanksReminderCooldown { get; set; } public Dictionary<ulong, DateTime> CodeReminderCooldown { get; set; } public UserData() { MutedUsers = new Dictionary<ulong, DateTime>(); ThanksReminderCooldown = new Dictionary<ulong, DateTime>(); CodeReminderCooldown = new Dictionary<ulong, DateTime>(); } } public class CasinoData { public int SlotMachineCashPool { get; set; } public int LotteryCashPool { get; set; } } public class FaqData { public string Question { get; set; } public string Answer { get; set; } public string[] Keywords { get; set; } } public class FeedData { public DateTime LastUnityReleaseCheck { get; set; } public DateTime LastUnityBlogCheck { get; set; } public List<string> PostedIds { get; set; } public FeedData() { PostedIds = new List<string>(); } } //TODO: Download all avatars to cache them public class UpdateService { DiscordSocketClient _client; private readonly ILoggingService _loggingService; private readonly PublisherService _publisherService; private readonly DatabaseService _databaseService; private readonly AnimeService _animeService; private readonly FeedService _feedService; private readonly CancellationToken _token; private readonly Settings.Deserialized.Settings _settings; private BotData _botData; private List<FaqData> _faqData; private Random _random; private AnimeData _animeData; private UserData _userData; private CasinoData _casinoData; private FeedData _feedData; private string[][] _manualDatabase; private string[][] _apiDatabase; public UpdateService(DiscordSocketClient client, ILoggingService loggingService, PublisherService publisherService, DatabaseService databaseService, AnimeService animeService, Settings.Deserialized.Settings settings, FeedService feedService) { _client = client; _loggingService = loggingService; _publisherService = publisherService; _databaseService = databaseService; _animeService = animeService; _feedService = feedService; _settings = settings; _token = new CancellationToken(); _random = new Random(); UpdateLoop(); } private void UpdateLoop() { ReadDataFromFile(); SaveDataToFile(); //CheckDailyPublisher(); UpdateUserRanks(); UpdateAnime(); UpdateDocDatabase(); UpdateRssFeeds(); } private void ReadDataFromFile() { if (File.Exists($"{_settings.ServerRootPath}/botdata.json")) { string json = File.ReadAllText($"{_settings.ServerRootPath}/botdata.json"); _botData = JsonConvert.DeserializeObject<BotData>(json); } else _botData = new BotData(); if (File.Exists($"{_settings.ServerRootPath}/animedata.json")) { string json = File.ReadAllText($"{_settings.ServerRootPath}/animedata.json"); _animeData = JsonConvert.DeserializeObject<AnimeData>(json); } else _animeData = new AnimeData(); if (File.Exists($"{_settings.ServerRootPath}/userdata.json")) { string json = File.ReadAllText($"{_settings.ServerRootPath}/userdata.json"); _userData = JsonConvert.DeserializeObject<UserData>(json); Task.Run( async () => { while (_client.ConnectionState != ConnectionState.Connected || _client.LoginState != LoginState.LoggedIn) await Task.Delay(100, _token); await Task.Delay(1000, _token); //Check if there are users still muted foreach (var userID in _userData.MutedUsers) { if (_userData.MutedUsers.HasUser(userID.Key, evenIfCooldownNowOver: true)) { SocketGuild guild = _client.Guilds.First(); SocketGuildUser sgu = guild.GetUser(userID.Key); if (sgu == null) { continue; } IGuildUser user = sgu as IGuildUser; IRole mutedRole = user.Guild.GetRole(_settings.MutedRoleId); //Make sure they have the muted role if (!user.RoleIds.Contains(_settings.MutedRoleId)) { await user.AddRoleAsync(mutedRole); } //Setup delay to remove role when time is up. await Task.Run(async () => { await _userData.MutedUsers.AwaitCooldown(user.Id); await user.RemoveRoleAsync(mutedRole); }, _token); } } }, _token); } else { _userData = new UserData(); } if (File.Exists($"{_settings.ServerRootPath}/casinodata.json")) { string json = File.ReadAllText($"{_settings.ServerRootPath}/casinodata.json"); _casinoData = JsonConvert.DeserializeObject<CasinoData>(json); } else _casinoData = new CasinoData(); if (File.Exists($"{_settings.ServerRootPath}/FAQs.json")) { string json = File.ReadAllText($"{_settings.ServerRootPath}/FAQs.json"); _faqData = JsonConvert.DeserializeObject<List<FaqData>>(json); } else { _faqData = new List<FaqData>(); } if (File.Exists($"{_settings.ServerRootPath}/feeds.json")) { string json = File.ReadAllText($"{_settings.ServerRootPath}/feeds.json"); _feedData = JsonConvert.DeserializeObject<FeedData>(json); } else { _feedData = new FeedData(); } } /* ** Save data to file every 20s */ private async void SaveDataToFile() { while (true) { var json = JsonConvert.SerializeObject(_botData); File.WriteAllText($"{_settings.ServerRootPath}/botdata.json", json); json = JsonConvert.SerializeObject(_animeData); File.WriteAllText($"{_settings.ServerRootPath}/animedata.json", json); json = JsonConvert.SerializeObject(_userData); File.WriteAllText($"{_settings.ServerRootPath}/userdata.json", json); json = JsonConvert.SerializeObject(_casinoData); File.WriteAllText($"{_settings.ServerRootPath}/casinodata.json", json); json = JsonConvert.SerializeObject(_feedData); File.WriteAllText($"{_settings.ServerRootPath}/feeds.json", json); //await _logging.LogAction("Data successfully saved to file", true, false); await Task.Delay(TimeSpan.FromSeconds(20d), _token); } } public async Task CheckDailyPublisher(bool force = false) { await Task.Delay(TimeSpan.FromSeconds(10d), _token); while (true) { if (_botData.LastPublisherCheck < DateTime.Now - TimeSpan.FromDays(1d) || force) { uint count = _databaseService.GetPublisherAdCount(); ulong id; uint rand; do { rand = (uint) _random.Next((int) count); id = _databaseService.GetPublisherAd(rand).userId; } while (_botData.LastPublisherId.Contains(id)); await _publisherService.PostAd(rand); await _loggingService.LogAction("Posted new daily publisher ad.", true, false); _botData.LastPublisherCheck = DateTime.Now; _botData.LastPublisherId.Add(id); } if (_botData.LastPublisherId.Count > 10) _botData.LastPublisherId.RemoveAt(0); if (force) return; await Task.Delay(TimeSpan.FromMinutes(5d), _token); } } private async void UpdateUserRanks() { await Task.Delay(TimeSpan.FromSeconds(30d), _token); while (true) { _databaseService.UpdateUserRanks(); await Task.Delay(TimeSpan.FromMinutes(1d), _token); } } private async void UpdateAnime() { await Task.Delay(TimeSpan.FromSeconds(30d), _token); while (true) { if (_animeData.LastDailyAnimeAiringList < DateTime.Now - TimeSpan.FromDays(1d)) { _animeService.PublishDailyAnime(); _animeData.LastDailyAnimeAiringList = DateTime.Now; } if (_animeData.LastWeeklyAnimeAiringList < DateTime.Now - TimeSpan.FromDays(7d)) { _animeService.PublishWeeklyAnime(); _animeData.LastWeeklyAnimeAiringList = DateTime.Now; } await Task.Delay(TimeSpan.FromMinutes(1d), _token); } } public async Task<string[][]> GetManualDatabase() { if (_manualDatabase == null) await LoadDocDatabase(); return _manualDatabase; } public async Task<string[][]> GetApiDatabase() { if (_apiDatabase == null) await LoadDocDatabase(); return _apiDatabase; } public List<FaqData> GetFaqData() { return _faqData; } private async Task LoadDocDatabase() { if (File.Exists($"{_settings.ServerRootPath}/unitymanual.json") && File.Exists($"{_settings.ServerRootPath}/unityapi.json")) { string json = File.ReadAllText($"{_settings.ServerRootPath}/unitymanual.json"); _manualDatabase = JsonConvert.DeserializeObject<string[][]>(json); json = File.ReadAllText($"{_settings.ServerRootPath}/unityapi.json"); _apiDatabase = JsonConvert.DeserializeObject<string[][]>(json); } else await DownloadDocDatabase(); } private async Task DownloadDocDatabase() { try { HtmlWeb htmlWeb = new HtmlWeb(); htmlWeb.CaptureRedirect = true; HtmlDocument manual = await htmlWeb.LoadFromWebAsync("https://docs.unity3d.com/Manual/docdata/index.js"); string manualInput = manual.DocumentNode.OuterHtml; HtmlDocument api = await htmlWeb.LoadFromWebAsync("https://docs.unity3d.com/ScriptReference/docdata/index.js"); string apiInput = api.DocumentNode.OuterHtml; _manualDatabase = ConvertJsToArray(manualInput, true); _apiDatabase = ConvertJsToArray(apiInput, false); File.WriteAllText($"{_settings.ServerRootPath}/unitymanual.json", JsonConvert.SerializeObject(_manualDatabase)); File.WriteAllText($"{_settings.ServerRootPath}/unityapi.json", JsonConvert.SerializeObject(_apiDatabase)); string[][] ConvertJsToArray(string data, bool isManual) { List<string[]> list = new List<string[]>(); string pagesInput; if (isManual) { pagesInput = data.Split("info = [")[0].Split("pages=")[1]; pagesInput = pagesInput.Substring(2, pagesInput.Length - 4); } else { pagesInput = data.Split("info =")[0]; pagesInput = pagesInput.Substring(63, pagesInput.Length - 65); } foreach (string s in pagesInput.Split("],[")) { string[] ps = s.Split(","); list.Add(new string[] {ps[0].Replace("\"", ""), ps[1].Replace("\"", "")}); //Console.WriteLine(ps[0].Replace("\"", "") + "," + ps[1].Replace("\"", "")); } return list.ToArray(); } } catch (Exception e) { Console.WriteLine(e); } } private async void UpdateDocDatabase() { while (true) { if (_botData.LastUnityDocDatabaseUpdate < DateTime.Now - TimeSpan.FromDays(1d)) await DownloadDocDatabase(); await Task.Delay(TimeSpan.FromHours(1), _token); } } private async void UpdateRssFeeds() { await Task.Delay(TimeSpan.FromSeconds(30d), _token); while (true) { if (_feedData.LastUnityReleaseCheck < DateTime.Now - TimeSpan.FromMinutes(5)) { _feedData.LastUnityReleaseCheck = DateTime.Now; _feedService.CheckUnityBetas(_feedData); _feedService.CheckUnityReleases(_feedData); } if (_feedData.LastUnityBlogCheck < DateTime.Now - TimeSpan.FromMinutes(10)) { _feedData.LastUnityBlogCheck = DateTime.Now; _feedService.CheckUnityBlog(_feedData); } await Task.Delay(TimeSpan.FromSeconds(30d), _token); } } public async Task<String> DownloadWikipediaArticle(String articleName) { String url = Uri.EscapeUriString(_settings.WikipediaSearchPage + articleName); try { HtmlWeb htmlWeb = new HtmlWeb(); htmlWeb.CaptureRedirect = true; HtmlDocument manual = await htmlWeb.LoadFromWebAsync(url); String jsonData = manual.DocumentNode.OuterHtml; dynamic json = JObject.Parse(jsonData); //2 hours have been spent trying to get this to work - just a warning to not stuff it up foreach(JToken token in json["query"]["pages"].Children()) { //If its null its not an article if (token.First["extract"] == null) { break; } return token.First["extract"].ToString(); } } catch (Exception e) { Console.WriteLine(e); } return null; } public UserData GetUserData() { return _userData; } public void SetUserData(UserData data) { _userData = data; } public CasinoData GetCasinoData() { return _casinoData; } public void SetCasinoData(CasinoData data) { _casinoData = data; } } }
35.735169
137
0.522796
[ "MIT" ]
RafaGnious/UDHBot
DiscordBot/Services/UpdateService.cs
16,869
C#
using System.Collections.ObjectModel; namespace MASGlobalTest.Areas.HelpPage.ModelDescriptions { public class ComplexTypeModelDescription : ModelDescription { public ComplexTypeModelDescription() { Properties = new Collection<ParameterDescription>(); } public Collection<ParameterDescription> Properties { get; private set; } } }
27.642857
80
0.70801
[ "MIT" ]
jrarturo/MASGlobalTest
MASGlobalTest/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs
387
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HttpPlayback.Shared.Tests.Helpers { /// <summary> /// Helper class that ensures that <see cref="TestFilePaths.TestDataPath"/> is clean for each set of tests /// </summary> public static class TestDataDirectoryHelpers { public static void EnsureTestDataDirectory() { if (!Directory.Exists(TestFilePaths.TestDataPath)) Directory.CreateDirectory(TestFilePaths.TestDataPath); } public static void DeleteTestDataDirectory() { if(Directory.Exists(TestFilePaths.TestDataPath)) Directory.Delete(TestFilePaths.TestDataPath, true); } } }
28.642857
110
0.67207
[ "Apache-2.0" ]
petabridge/http-playback
tests/core/HttpPlayback.Shared.Tests/Helpers/TestDataDirectoryHelpers.cs
804
C#
using System.Net.Http; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Web; namespace dashboardUtilities { using System; using System.Linq; using System.Net.Mime; using umbraco.BasePages; using Umbraco.Core.IO; public partial class FeedProxy : UmbracoEnsuredPage { private static HttpClient _httpClient; protected void Page_Load(object sender, EventArgs e) { try { if (Request.QueryString.AllKeys.Contains("url") == false || Request.QueryString["url"] == null) return; var url = Request.QueryString["url"]; if (string.IsNullOrWhiteSpace(url) || url.StartsWith("/")) return; if (Uri.TryCreate(url, UriKind.Absolute, out var requestUri) == false) return; var feedProxyXml = XmlHelper.OpenAsXmlDocument(IOHelper.MapPath(SystemFiles.FeedProxyConfig)); if (feedProxyXml?.SelectSingleNode($"//allow[@host = '{requestUri.Host}']") != null && requestUri.Port == 80) { if (_httpClient == null) _httpClient = new HttpClient(); using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri)) { var response = _httpClient.SendAsync(request).Result; var result = response.Content.ReadAsStringAsync().Result; if (string.IsNullOrEmpty(result)) return; Response.Clear(); Response.ContentType = Request.CleanForXss("type") ?? MediaTypeNames.Text.Xml; Response.Write(result); } } else { LogHelper.Debug<FeedProxy>($"Access to unallowed feedproxy attempted: {requestUri}"); } } catch (Exception ex) { LogHelper.Error<FeedProxy>("Exception occurred", ex); } } } }
35.285714
126
0.503374
[ "MIT" ]
agrath/Umbraco-CMS
src/Umbraco.Web/umbraco.presentation/umbraco/dashboard/FeedProxy.aspx.cs
2,225
C#
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Voximplant.API.Response { /// <summary> /// The specific account callback details. Received as part of the [AccountCallback] structure. /// </summary> public class TranscriptionCompleteCallback { /// <summary> /// The transcription info. /// </summary> [JsonProperty("transcription_complete")] public TranscriptionCompleteCallbackItem TranscriptionComplete { get; private set; } } }
27.894737
99
0.679245
[ "MIT" ]
voximplant/apiclient-dotnet
apiclient/Response/TranscriptionCompleteCallback.cs
530
C#
namespace MusacaRT.Data { public class DatabaseConfiguration { public const string ConnectionString = @"Server=.\SQLEXPRESS;Database=MusacaDBRT;Trusted_Connection=True;Integrated Security=True;"; } }
25.888889
105
0.703863
[ "MIT" ]
EmORz/SULS
MusacaRT.Data/DatabaseConfiguration.cs
235
C#
// // DebugHelpers.cs // // Author: // Martin Baulig <mabaul@microsoft.com> // // Copyright (c) 2019 Microsoft Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Runtime.CompilerServices; using Mono.Cecil; using Mono.Cecil.Cil; namespace Mono.Linker.Optimizer { using BasicBlocks; static class DebugHelpers { public static Exception AssertFail (string message) => throw new OptimizerAssertionException (message); public static Exception AssertFail (MethodDefinition method, string message , [CallerMemberName] string caller = null) { throw new OptimizerAssertionException ($"Assertion failed in `{method}`: {message}{(!string.IsNullOrEmpty (caller) ? " (at " + caller + ")" : "")}"); } public static Exception AssertFail (MethodDefinition method, BasicBlock block, string message, [CallerMemberName] string caller = null) { throw new OptimizerAssertionException ($"Assertion failed in `{method}` ({block}): {message}{(!string.IsNullOrEmpty (caller) ? " (at " + caller + ")" : "")}"); } public static Exception AssertFailUnexpected (MethodDefinition method, BasicBlock block, object unexpected, [CallerMemberName] string caller = null) { string message; if (unexpected == null) message = "got unexpected null reference"; else if (unexpected is Instruction instruction) message = $"got unexpected instruction `{CecilHelper.Format (instruction)}`"; else message = $"got unexpected `{unexpected}`"; throw AssertFail (method, block, message, caller); } public static void Assert (bool condition, [CallerMemberName] string caller = null) { if (!condition) throw new OptimizerAssertionException ($"Assertion failed{(!string.IsNullOrEmpty (caller) ? " in " + caller : "")}."); } } }
40.898551
162
0.734231
[ "MIT" ]
xamarin/linker-optimizer
Mono.Linker.Optimizer/Mono.Linker.Optimizer/DebugHelpers.cs
2,824
C#
using System; namespace RegTesting.Service { /// <summary> /// A helperclass for some common functions. /// </summary> public class Helper { private static readonly Random Rnd = new Random(); /// <summary> /// Get a unique number for screenshot. /// </summary> /// <returns>a integer for a unique screenshot number</returns> public static string GetScreenshotString() { return DateTime.Now.ToString("ddHHmmss") + "-" + Rnd.Next(999998); } } }
21.409091
69
0.66879
[ "Apache-2.0" ]
hotelde/regtesting
RegTesting.Service/Helper.cs
473
C#
using System; namespace CSharpMiscLibrary.Exceptions { /// <summary> /// Invalid equality custom exception. /// </summary> [Serializable()] public class InvalidEqualityException : System.Exception { public InvalidEqualityException() : base() { } public InvalidEqualityException(string message) : base(message) { } public InvalidEqualityException(string message, Exception inner) : base(message, inner) { } protected InvalidEqualityException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } }
37.705882
176
0.714509
[ "MIT" ]
davikawasaki/csharp-misc-library
CSharpMiscLibrary/Exceptions/InvalidEqualityException.cs
643
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // // This file is a C# translation of the NavigationViewItemBase.cpp file from WinUI controls. // using Uno.UI.Helpers.WinUI; using Windows.UI.Xaml.Media; namespace Windows.UI.Xaml.Controls { public partial class NavigationViewItemBase : ListViewItem { NavigationViewListPosition m_position = NavigationViewListPosition.LeftNav; protected virtual void OnNavigationViewListPositionChanged() { } internal NavigationViewListPosition Position() { return m_position; } internal void Position(NavigationViewListPosition value) { if (m_position != value) { m_position = value; OnNavigationViewListPositionChanged(); } } internal NavigationView GetNavigationView() { //Because of Overflow popup, we can't get NavigationView by SharedHelpers::GetAncestorOfType NavigationView navigationView = null; var navigationViewList = GetNavigationViewList(); if (navigationViewList != null) { navigationView = navigationViewList.GetNavigationViewParent(); } else { // Like Settings, it's NavigationViewItem, but it's not in NavigationViewList. Give it a second chance navigationView = SharedHelpers.GetAncestorOfType<NavigationView>(VisualTreeHelper.GetParent(this)); } return navigationView; } internal SplitView GetSplitView() { SplitView splitView = null; var navigationView = GetNavigationView(); if (navigationView != null) { splitView = navigationView.GetSplitView(); } return splitView; } internal NavigationViewList GetNavigationViewList() { // Find parent NavigationViewList return SharedHelpers.GetAncestorOfType<NavigationViewList>(VisualTreeHelper.GetParent(this)); } } }
27.279412
106
0.752022
[ "Apache-2.0" ]
06needhamt/uno
src/Uno.UI/UI/Xaml/Controls/NavigationView/NavigationViewItemBase.cs
1,855
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT License. // See the LICENSE file in the project root for more information. // <auto-generated /> #if HAS_REMOTING using System.Linq.Expressions; using System.Reflection; using System.Runtime.Remoting.Lifetime; namespace System.Reactive.Linq { /// <summary> /// Provides a set of static methods for exposing observable sequences through .NET Remoting. /// </summary> public static partial class RemotingObservable { #region Remotable /// <summary> /// Makes an observable sequence remotable, using an infinite lease for the <see cref="MarshalByRefObject"/> wrapping the source. /// </summary> /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam> /// <param name="source">Source sequence.</param> /// <returns>The observable sequence that supports remote subscriptions.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception> [Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Remotable", Justification = "In honor of the .NET Remoting heroes.")] public static IObservable<TSource> Remotable<TSource>(this IObservable<TSource> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return Remotable_(source); } /// <summary> /// Makes an observable sequence remotable, using a controllable lease for the <see cref="MarshalByRefObject"/> wrapping the source. /// </summary> /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam> /// <param name="source">Source sequence.</param> /// <param name="lease">Lease object to control lifetime of the remotable sequence. Notice null is a supported value.</param> /// <returns>The observable sequence that supports remote subscriptions.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception> [Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Remotable", Justification = "In honor of the .NET Remoting heroes.")] public static IObservable<TSource> Remotable<TSource>(this IObservable<TSource> source, ILease lease) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return Remotable_(source, lease); } /// <summary> /// Makes an observable sequence remotable, using an infinite lease for the <see cref="MarshalByRefObject"/> wrapping the source. /// </summary> /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam> /// <param name="source">Source sequence.</param> /// <returns>The observable sequence that supports remote subscriptions.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception> [Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Remotable", Justification = "In honor of the .NET Remoting heroes.")] public static IQbservable<TSource> Remotable<TSource>(this IQbservable<TSource> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source.Provider.CreateQuery<TSource>( Expression.Call( null, #if CRIPPLED_REFLECTION InfoOf(() => RemotingObservable.Remotable<TSource>(default(IQbservable<TSource>))), #else ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)), #endif source.Expression ) ); } /// <summary> /// Makes an observable sequence remotable, using a controllable lease for the <see cref="MarshalByRefObject"/> wrapping the source. /// </summary> /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam> /// <param name="source">Source sequence.</param> /// <param name="lease">Lease object to control lifetime of the remotable sequence. Notice null is a supported value.</param> /// <returns>The observable sequence that supports remote subscriptions.</returns> /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception> [Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Remotable", Justification = "In honor of the .NET Remoting heroes.")] public static IQbservable<TSource> Remotable<TSource>(this IQbservable<TSource> source, ILease lease) { if (source == null) { throw new ArgumentNullException(nameof(source)); } return source.Provider.CreateQuery<TSource>( Expression.Call( null, #if CRIPPLED_REFLECTION InfoOf(() => RemotingObservable.Remotable<TSource>(default(IQbservable<TSource>), default(ILease))), #else ((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)), #endif source.Expression, Expression.Constant(lease, typeof(ILease)) ) ); } #if CRIPPLED_REFLECTION internal static MethodInfo InfoOf<R>(Expression<Func<R>> f) { return ((MethodCallExpression)f.Body).Method; } #endif #endregion } } #endif
47.634921
198
0.645118
[ "MIT" ]
Awsmolak/ReactiveUI
src/ReactiveUI.Uwp/Rx/Linq/Observable.Remoting.cs
6,004
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Problem 1. Action Point")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Problem 1. Action Point")] [assembly: System.Reflection.AssemblyTitleAttribute("Problem 1. Action Point")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
42.458333
81
0.648675
[ "MIT" ]
hristokrastev/CSharpAdvace
Functional Programming/Problem 1. Action Point/Problem 1. Action Point/obj/Debug/netcoreapp3.1/Problem 1. Action Point.AssemblyInfo.cs
1,019
C#
using System; using System.Runtime.InteropServices; using ff14bot.Enums; using ff14bot.Managers; namespace LlamaLibrary.Structs { [StructLayout(LayoutKind.Explicit, Size = 0xA0)] public struct GCSupplyItem { [FieldOffset(0)] public IntPtr ItemPtr; [FieldOffset(0x68)] public uint BagId; [FieldOffset(0x78)] public uint Seals; [FieldOffset(0x84)] public uint ItemId; [FieldOffset(0x97)] public ushort BagSlotId; [FieldOffset(0x99)] public byte HandInType; [FieldOffset(0x9C)] public bool InGearSet; public bool InArmory => BagId == 3500 || (BagId - 3200) <= 9 || BagId == 3300 || BagId == 3400; public BagSlot BagSlot => InventoryManager.GetBagByInventoryBagId((InventoryBagId) BagId)[BagSlotId]; public bool IsHQ => BagSlot.IsHighQuality; public override string ToString() { return $"Item: {DataManager.GetItem(ItemId).CurrentLocaleName}, {nameof(InGearSet)}: {InGearSet}, {nameof(InArmory)}: {InArmory} HQ: {IsHQ}"; } } }
26.093023
153
0.627451
[ "MIT" ]
nt153133/__LlamaLibrary
Structs/GCSupplyItem.cs
1,124
C#
namespace Week4.Demo { using System; using Common.Lab; class Program { static void Main(string[] args) { CarStatic voiture = new CarStatic(); voiture.ReservoirEssence = CarStatic.CapaciteReservoirEssence; AfficherVoiture(voiture); Console.WriteLine("=============================="); voiture.ParcourirDistance(58); Console.WriteLine("Parcourrir 58km avec la voiture"); voiture.ParcourirDistance(21); Console.WriteLine("Parcourrir 21km avec la voiture"); Console.WriteLine("=============================="); AfficherVoiture(voiture); Console.WriteLine("=============================="); Console.WriteLine("Faire le plein d'essence de la voiture!"); voiture.FaireLePlein(); Console.WriteLine("=============================="); AfficherVoiture(voiture); } static void AfficherVoiture(CarStatic voiture) { Console.WriteLine("Reservoir global: {0}/{1} litres", CarStatic.ReservoirEssenceGlobal, CarStatic.CapaciteReservoirEssenceGlobal); Console.WriteLine("Kilométrage de la voiture: {0}km", voiture.Kilometrage); Console.WriteLine("Essence de la voiture: {0}/{1} litres", voiture.ReservoirEssence, CarStatic.CapaciteReservoirEssence); } } }
36.615385
142
0.563025
[ "MIT" ]
enriqueescobar-askida/UdeS.Cefti.Inf731
Week4.Demo/Program.cs
1,431
C#
using System; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using AutoMapper; using AutoMapper.QueryableExtensions; using MediatR; using SFA.DAS.EmployerAccounts.Data; using SFA.DAS.EmployerAccounts.Dtos; namespace SFA.DAS.EmployerAccounts.Queries.GetTransferConnectionInvitations { public class GetTransferConnectionInvitationsQueryHandler : IAsyncRequestHandler<GetTransferConnectionInvitationsQuery, GetTransferConnectionInvitationsResponse> { private readonly Lazy<EmployerAccountsDbContext> _db; private readonly IConfigurationProvider _configurationProvider; public GetTransferConnectionInvitationsQueryHandler(Lazy<EmployerAccountsDbContext> db, IConfigurationProvider configurationProvider) { _db = db; _configurationProvider = configurationProvider; } public async Task<GetTransferConnectionInvitationsResponse> Handle(GetTransferConnectionInvitationsQuery message) { var transferConnectionInvitations = await _db.Value.TransferConnectionInvitations .Where(i => i.SenderAccount.Id == message.AccountId.Value && !i.DeletedBySender || i.ReceiverAccount.Id == message.AccountId.Value && !i.DeletedByReceiver) .OrderBy(i => i.ReceiverAccount.Id == message.AccountId.Value ? i.SenderAccount.Name : i.ReceiverAccount.Name) .ThenBy(i => i.CreatedDate) .ProjectTo<TransferConnectionInvitationDto>(_configurationProvider) .ToListAsync(); return new GetTransferConnectionInvitationsResponse { TransferConnectionInvitations = transferConnectionInvitations }; } } }
44.615385
171
0.732184
[ "MIT" ]
SkillsFundingAgency/das-employeraccounts
src/SFA.DAS.EmployerAccounts/Queries/GetTransferConnectionInvitations/GetTransferConnectionInvitationsQueryHandler.cs
1,742
C#
using System.Maui.CustomAttributes; using System.Maui.Internals; using System; using System.Linq; using System.ComponentModel; using System.Collections.ObjectModel; #if UITEST using Xamarin.UITest; using NUnit.Framework; #endif namespace System.Maui.Controls.Issues { [Preserve(AllMembers = true)] [Issue(IssueTracker.Bugzilla, 57910, "ObjectDisposedException in System.Maui.Platform.Android.Renderers.ProgressBarRenderer", PlatformAffected.Android)] public class Bugzilla57910 : QuickCollectNavigationPage { const string ButtonId = "btnPush"; const string Button2Id = "btnPop"; const string Instructions = "Tap Push. Then quickly tap Pop on the subsequent screen. Do this several times. If there is no crash, then this test has passed."; const string Instructions2 = "Tap Pop. Then quickly tap Push on the subsequent screen. Do this several times. If there is no crash, then this test has passed."; protected override void Init() { Navigation.PushAsync(new HomePage()); } [Preserve(AllMembers = true)] class HomePage : ContentPage { public HomePage() { Button button = new Button { Text = "Push", AutomationId = ButtonId }; button.Clicked += Button_Clicked; Content = new StackLayout { Children = { new Label { Text = Instructions }, button } }; } async void Button_Clicked(object sender, EventArgs e) { await Navigation.PushAsync(new ListPage()); GarbageCollectionHelper.Collect(); } } [Preserve(AllMembers = true)] class ListItemView : ViewCell { public ListItemView() { ProgressBar progressBar = new ProgressBar { IsVisible = false }; progressBar.SetBinding(ProgressBar.ProgressProperty, nameof(ListItemViewModel.DownloadProgressPercentage)); // Need a trigger to set a property on a VisualElement. Not actually specific to ProgressBar. DataTrigger newDataTrigger = new DataTrigger(typeof(ProgressBar)) { Binding = new Binding(nameof(ListItemViewModel.State)), Value = ListItemViewModel.InstallableState.Downloading }; newDataTrigger.Setters.Add(new Setter { Property = ProgressBar.IsVisibleProperty, Value = true }); progressBar.Triggers.Add(newDataTrigger); View = new ContentView { Content = new StackLayout { Children = { progressBar } } }; } } [Preserve(AllMembers = true)] class ListHeaderView : ContentView { public ListHeaderView() { Label newLabel = new Label(); newLabel.SetBinding(Label.TextProperty, nameof(ListPageViewModel.Header)); Content = newLabel; } } [Preserve(AllMembers = true)] class ListFooterView : ContentView { public ListFooterView() { Label newLabel = new Label(); newLabel.SetBinding(Label.TextProperty, nameof(ListPageViewModel.Footer)); var stack = new StackLayout { Children = { newLabel } }; Content = stack; } } [Preserve(AllMembers = true)] class ListPageViewModel : INotifyPropertyChanged { ObservableCollection<ListItemViewModel> _items; string _footer; string _header; int _counter; public ListPageViewModel() { _header = "Header!"; _footer = "Footer!"; _counter = 0; _items = new ObservableCollection<ListItemViewModel>(Enumerable.Range(0, 100).Select(c => new ListItemViewModel())); // Need an asynchronous action that happens sometime between creation of the Element and Pop of the containing page Device.StartTimer(TimeSpan.FromMilliseconds((100)), () => { Header = $"Header! {_counter++}"; Footer = $"Footer! {_counter++}"; return true; }); } public event PropertyChangedEventHandler PropertyChanged; public ObservableCollection<ListItemViewModel> Items { get { return _items; } set { _items = value; OnPropertyChanged(nameof(Items)); } } public string Header { get { return _header; } set { _header = value; OnPropertyChanged(nameof(Header)); } } public string Footer { get { return _footer; } set { _footer = value; OnPropertyChanged(nameof(Footer)); } } protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } [Preserve(AllMembers = true)] class ListItemViewModel : INotifyPropertyChanged { double _downloadProgressPercentage; InstallableState _state; public ListItemViewModel() { DownloadProgressPercentage = 0d; State = InstallableState.Downloading; // Need an asynchronous action that happens sometime between creation of the Element and Pop of the containing page Device.StartTimer(TimeSpan.FromMilliseconds((1000)), () => { DownloadProgressPercentage += 0.05d; if (DownloadProgressPercentage > 0.99d) { State = InstallableState.Local; } return DownloadProgressPercentage != 1.0d; }); } public event PropertyChangedEventHandler PropertyChanged; public enum InstallableState { Local, Downloading } public double DownloadProgressPercentage { get { return _downloadProgressPercentage; } set { _downloadProgressPercentage = value; OnPropertyChanged(nameof(DownloadProgressPercentage)); } } public InstallableState State { get { return _state; } set { _state = value; OnPropertyChanged(nameof(State)); } } protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } [Preserve(AllMembers = true)] class ListPage : ContentPage { public ListPage() { ListView listView = new ListView(ListViewCachingStrategy.RecycleElement) { RowHeight = 70, ItemTemplate = new DataTemplate(typeof(ListItemView)), HeaderTemplate = new DataTemplate(typeof(ListHeaderView)), FooterTemplate = new DataTemplate(typeof(ListFooterView)), }; listView.SetBinding(ListView.ItemsSourceProperty, nameof(ListPageViewModel.Items)); listView.SetBinding(ListView.HeaderProperty, "."); listView.SetBinding(ListView.FooterProperty, "."); Button newButton = new Button { Text = "Pop", AutomationId = Button2Id }; newButton.Clicked += NewButton_Clicked; Content = new StackLayout { Children = { new Label { Text = Instructions2 }, newButton, listView } }; BindingContext = new ListPageViewModel(); } void NewButton_Clicked(object sender, EventArgs e) { Navigation.PopAsync(); } } #if UITEST [Test] public void Bugzilla57910Test() { for (int i = 0; i < 10; i++) { RunningApp.WaitForElement(q => q.Marked(ButtonId)); RunningApp.Tap(q => q.Marked(ButtonId)); RunningApp.WaitForElement(q => q.Marked(Button2Id)); RunningApp.Tap(q => q.Marked(Button2Id)); } } #endif } }
26.898039
185
0.698061
[ "MIT" ]
AswinPG/maui
System.Maui.Controls.Issues/System.Maui.Controls.Issues.Shared/Bugzilla57910.cs
6,859
C#
using Melinoe.Shared.Objectives; namespace Melinoe.Client.State.UpdateObjectives { public class UpdateObjectiveAction { public Objective Objective { get; } public bool IsEnabled { get; } public UpdateObjectiveAction(Objective objective, bool isEnabled) { Objective = objective; IsEnabled = isEnabled; } } }
22.705882
73
0.637306
[ "MIT" ]
alexnoddings/Melinoe
Client/State/UpdateObjectives/UpdateObjectiveAction.cs
388
C#
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2010 Leopold Bushkin. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq.Test { using NUnit.Framework; /// <summary> /// Verify the behavior of the Lead operator. /// </summary> [TestFixture] public class LeadTests { /// <summary> /// Verify that Lead() behaves in a lazy manner. /// </summary> [Test] public void TestLeadIsLazy() { new BreakingSequence<int>().Lead(5, BreakingFunc.Of<int, int, int>()); new BreakingSequence<int>().Lead(5, -1, BreakingFunc.Of<int, int, int>()); } /// <summary> /// Verify that attempting to lead by a negative offset will result in an exception. /// </summary> [Test] public void TestLeadNegativeOffset() { AssertThrowsArgument.OutOfRangeException("offset", () => Enumerable.Range(1, 100).Lead(-5, (val, leadVal) => val + leadVal)); } /// <summary> /// Verify that attempting to lead by a zero offset will result in an exception. /// </summary> [Test] public void TestLeadZeroOffset() { AssertThrowsArgument.OutOfRangeException("offset", () => Enumerable.Range(1, 100).Lead(0, (val, leadVal) => val + leadVal)); } /// <summary> /// Verify that lead can accept and propagate a default value passed to it. /// </summary> [Test] public void TestLeadExplicitDefaultValue() { const int count = 100; const int leadBy = 10; const int leadDefault = -1; var sequence = Enumerable.Range(1, count); var result = sequence.Lead(leadBy, leadDefault, (val, leadVal) => leadVal); Assert.AreEqual(count, result.Count()); Assert.That(result.Skip(count - leadBy), Is.EqualTo(Enumerable.Repeat(leadDefault, leadBy))); } /// <summary> /// Verify that Lead() willuse default(T) if a specific default value is not supplied for the lead value. /// </summary> [Test] public void TestLeadImplicitDefaultValue() { const int count = 100; const int leadBy = 10; var sequence = Enumerable.Range(1, count); var result = sequence.Lead(leadBy, (val, leadVal) => leadVal); Assert.AreEqual(count, result.Count()); Assert.That(result.Skip(count - leadBy), Is.EqualTo(Enumerable.Repeat(default(int), leadBy))); } /// <summary> /// Verify that if the lead offset is greater than the length of the sequence /// Lead() still yield all of the elements of the source sequence. /// </summary> [Test] public void TestLeadOffsetGreaterThanSequenceLength() { const int count = 100; const int leadDefault = -1; var sequence = Enumerable.Range(1, count); var result = sequence.Lead(count + 1, leadDefault, (val, leadVal) => new { A = val, B = leadVal }); Assert.AreEqual(count, result.Count()); Assert.That(result, Is.EqualTo(sequence.Select(x => new { A = x, B = leadDefault }))); } /// <summary> /// Verify that Lead() actually yields the correct pair of values from the sequence /// when the lead offset is 1. /// </summary> [Test] public void TestLeadPassesCorrectValueOffsetBy1() { const int count = 100; var sequence = Enumerable.Range(1, count); var result = sequence.Lead(1, count + 1, (val, leadVal) => new { A = val, B = leadVal }); Assert.AreEqual(count, result.Count()); Assert.IsTrue(result.All(x => x.B == (x.A + 1))); } /// <summary> /// Verify that Lead() yields the correct pair of values from the sequence /// when the lead offset is greater than 1. /// </summary> [Test] public void TestLeadPassesCorrectValueOffsetBy2() { const int count = 100; const int leadDefault = count + 1; var sequence = Enumerable.Range(1, count); var result = sequence.Lead(2, leadDefault, (val, leadVal) => new { A = val, B = leadVal }); Assert.AreEqual(count, result.Count()); Assert.IsTrue(result.Take(count - 2).All(x => x.B == (x.A + 2))); Assert.IsTrue(result.Skip(count - 2).All(x => x.B == leadDefault && (x.A == count || x.A == count - 1))); } } }
38.072464
117
0.577274
[ "Apache-2.0" ]
FeodorFitsner/MoreLINQ
MoreLinq.Test/LeadTest.cs
5,254
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.DataFactory.Latest.Inputs { /// <summary> /// Xero Service linked service. /// </summary> public sealed class XeroLinkedServiceArgs : Pulumi.ResourceArgs { [Input("annotations")] private InputList<object>? _annotations; /// <summary> /// List of tags that can be used for describing the linked service. /// </summary> public InputList<object> Annotations { get => _annotations ?? (_annotations = new InputList<object>()); set => _annotations = value; } /// <summary> /// The integration runtime reference. /// </summary> [Input("connectVia")] public Input<Inputs.IntegrationRuntimeReferenceArgs>? ConnectVia { get; set; } /// <summary> /// Properties used to connect to Xero. It is mutually exclusive with any other properties in the linked service. Type: object. /// </summary> [Input("connectionProperties")] public Input<object>? ConnectionProperties { get; set; } /// <summary> /// The consumer key associated with the Xero application. /// </summary> [Input("consumerKey")] public InputUnion<Inputs.AzureKeyVaultSecretReferenceArgs, Inputs.SecureStringArgs>? ConsumerKey { get; set; } /// <summary> /// Linked service description. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The encrypted credential used for authentication. Credentials are encrypted using the integration runtime credential manager. Type: string (or Expression with resultType string). /// </summary> [Input("encryptedCredential")] public Input<object>? EncryptedCredential { get; set; } /// <summary> /// The endpoint of the Xero server. (i.e. api.xero.com) /// </summary> [Input("host")] public Input<object>? Host { get; set; } [Input("parameters")] private InputMap<Inputs.ParameterSpecificationArgs>? _parameters; /// <summary> /// Parameters for linked service. /// </summary> public InputMap<Inputs.ParameterSpecificationArgs> Parameters { get => _parameters ?? (_parameters = new InputMap<Inputs.ParameterSpecificationArgs>()); set => _parameters = value; } /// <summary> /// The private key from the .pem file that was generated for your Xero private application. You must include all the text from the .pem file, including the Unix line endings( /// ). /// </summary> [Input("privateKey")] public InputUnion<Inputs.AzureKeyVaultSecretReferenceArgs, Inputs.SecureStringArgs>? PrivateKey { get; set; } /// <summary> /// Type of linked service. /// Expected value is 'Xero'. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; /// <summary> /// Specifies whether the data source endpoints are encrypted using HTTPS. The default value is true. /// </summary> [Input("useEncryptedEndpoints")] public Input<object>? UseEncryptedEndpoints { get; set; } /// <summary> /// Specifies whether to require the host name in the server's certificate to match the host name of the server when connecting over SSL. The default value is true. /// </summary> [Input("useHostVerification")] public Input<object>? UseHostVerification { get; set; } /// <summary> /// Specifies whether to verify the identity of the server when connecting over SSL. The default value is true. /// </summary> [Input("usePeerVerification")] public Input<object>? UsePeerVerification { get; set; } public XeroLinkedServiceArgs() { } } }
37.434783
190
0.615563
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/DataFactory/Latest/Inputs/XeroLinkedServiceArgs.cs
4,305
C#
using Avalonia.Controls; using Avalonia.Markup.Xaml; namespace AvalonStudio.Debugging.GDB.JLink { public class JLinkSettingsFormView : UserControl { public JLinkSettingsFormView() { InitializeComponent(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
20.333333
52
0.620219
[ "MIT" ]
FlaviusHouk/AvalonStudio
AvalonStudio/AvalonStudio.Debugging.GDB.JLink/JLinkSettingsFormView.xaml.cs
366
C#
// // This file has been generated automatically by MonoDevelop to store outlets and // actions made in the Xcode designer. If it is removed, they will be lost. // Manual changes to this file may not be handled correctly. // using Foundation; namespace MyKeyboardExtension { [Register ("KeyboardViewController")] partial class KeyboardViewController { void ReleaseDesignerOutlets () { } } }
20.25
81
0.748148
[ "BSD-3-Clause" ]
1975781737/xamarin-macios
msbuild/tests/MyKeyboardExtension/KeyboardViewController.designer.cs
407
C#
#if CSHotFix using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using CSHotFix.CLR.TypeSystem; using CSHotFix.CLR.Method; using CSHotFix.Runtime.Enviorment; using CSHotFix.Runtime.Intepreter; using CSHotFix.Runtime.Stack; using CSHotFix.Reflection; using CSHotFix.CLR.Utils; using System.Linq; namespace CSHotFix.Runtime.Generated { unsafe class UnityEngine_OcclusionPortal_Binding { public static void Register(CSHotFix.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(UnityEngine.OcclusionPortal); args = new Type[]{}; method = type.GetMethod("get_open", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_open_0); args = new Type[]{typeof(System.Boolean)}; method = type.GetMethod("set_open", flag, null, args, null); app.RegisterCLRMethodRedirection(method, set_open_1); app.RegisterCLRCreateDefaultInstance(type, () => new UnityEngine.OcclusionPortal()); app.RegisterCLRCreateArrayInstance(type, s => new UnityEngine.OcclusionPortal[s]); args = new Type[]{}; method = type.GetConstructor(flag, null, args, null); app.RegisterCLRMethodRedirection(method, Ctor_0); } static StackObject* get_open_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { CSHotFix.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); UnityEngine.OcclusionPortal instance_of_this_method = (UnityEngine.OcclusionPortal)typeof(UnityEngine.OcclusionPortal).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.open; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* set_open_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { CSHotFix.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Boolean @value = ptr_of_this_method->Value == 1; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); UnityEngine.OcclusionPortal instance_of_this_method = (UnityEngine.OcclusionPortal)typeof(UnityEngine.OcclusionPortal).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.open = value; return __ret; } static StackObject* Ctor_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { CSHotFix.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* __ret = ILIntepreter.Minus(__esp, 0); var result_of_this_method = new UnityEngine.OcclusionPortal(); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } } } #endif
39.670103
208
0.669179
[ "MIT" ]
591094733/cshotfix
CSHotFix_SimpleFramework/Assets/CSHotFixLibaray/Generated/CLRGen1/UnityEngine_OcclusionPortal_Binding.cs
3,848
C#
namespace Projector.Fakes.WithSharedTraitSpec { public interface ITypeB { } }
16.6
46
0.759036
[ "Apache-2.0" ]
sharpjs/Projector
Projector.Tests.FakeAssembly/Fakes/WithSharedTraitSpec/ITypeB.cs
85
C#
namespace UnityEngine.Rendering.UI { /// <summary> /// DebugUIHandler for vertical layoyut widget. /// </summary> public class DebugUIHandlerVBox : DebugUIHandlerWidget { DebugUIHandlerContainer m_Container; internal override void SetWidget(DebugUI.Widget widget) { base.SetWidget(widget); m_Container = GetComponent<DebugUIHandlerContainer>(); } /// <summary> /// OnSelection implementation. /// </summary> /// <param name="fromNext">True if the selection wrapped around.</param> /// <param name="previous">Previous widget.</param> /// <returns>True if the selection is allowed.</returns> public override bool OnSelection(bool fromNext, DebugUIHandlerWidget previous) { if (!fromNext && !m_Container.IsDirectChild(previous)) { var lastItem = m_Container.GetLastItem(); DebugManager.instance.ChangeSelection(lastItem, false); return true; } return false; } /// <summary> /// Next implementation. /// </summary> /// <returns>Next widget UI handler, parent if there is none.</returns> public override DebugUIHandlerWidget Next() { if (m_Container == null) return base.Next(); var firstChild = m_Container.GetFirstItem(); if (firstChild == null) return base.Next(); return firstChild; } } }
30.365385
86
0.567448
[ "MIT" ]
ACBGZM/JasonMaToonRenderPipeline
Packages/com.unity.render-pipelines.core@10.5.0/Runtime/Debugging/Prefabs/Scripts/DebugUIHandlerVBox.cs
1,579
C#
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Threading; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using NLog.Common; using NLog.Config; using NLog.Targets; namespace NLog.Target.Datadog { [Target("DataDog")] public class DataDogTarget : TargetWithLayout, IDatadogConfiguration //TargetWithContext, { /// <summary> /// The Datadog logs-backend URL. /// </summary> public const string DDUrl = "https://http-intake.logs.datadoghq.com"; /// <summary> /// The Datadog logs-backend TCP SSL port. /// </summary> public const int DDPort = 10516; /// <summary> /// The Datadog logs-backend TCP unsecure port. /// </summary> public const int DDPortNoSSL = 10514; private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}; private readonly HashSet<string> _excludedProperties = new HashSet<string>(new[] {"CallerMemberName", "CallerFilePath", "CallerLineNumber", "MachineName", "ThreadId"}); private readonly Lazy<JsonSerializerSettings> _jsonSerializerSettings = new Lazy<JsonSerializerSettings>(CreateJsonSerializerSettings, LazyThreadSafetyMode.PublicationOnly); private IDatadogClient _client; private JsonSerializer _jsonSerializer; private const int DefaultMaxRetries = 5; private int _maxRetries = DefaultMaxRetries; private const int DefaultMaxBackoff = 10; private int _maxBackoff = DefaultMaxBackoff; public DataDogTarget() { Name = "DataDog"; } private JsonSerializer JsonSerializer => _jsonSerializer ?? (_jsonSerializer = JsonSerializer.CreateDefault(_jsonSerializerSettings.Value)); public string ApiKey { get; set; } public string Source { get; set; } public string Service { get; set; } public string Host { get; set; } public string[] Tags { get; set; } /// <summary> /// URL of the server to send log events to. /// </summary> public string Url { get; set; } = DDUrl; /// <summary> /// Port of the server to send log events to. /// </summary> public int Port { get; set; } /// <summary> /// Use SSL or plain text. /// </summary> public bool UseSSL { get; set; } /// <summary> /// Use TCP or HTTP. /// </summary> public bool UseTCP { get; set; } /// <summary> /// Gets or sets whether to include all properties of the log event in the document /// </summary> public bool IncludeAllProperties { get; set; } /// <summary> /// Gets or sets a comma separated list of excluded properties when setting /// <see cref="IElasticSearchTarget.IncludeAllProperties" /> /// </summary> public string ExcludedProperties { get; set; } /// <summary> /// Gets or sets a list of additional fields to add to the Elasticsearch document. /// </summary> [ArrayParameter(typeof(Field), "field")] public IList<Field> Fields { get; set; } = new List<Field>(); protected override void InitializeTarget() { if (Port == 0) Port = UseSSL ? DDPort : DDPortNoSSL; base.InitializeTarget(); var useTCP = UseTCP; if (Uri.TryCreate(Url, UriKind.Absolute, out var uri) && uri?.Scheme?.StartsWith("http") == true) useTCP = false; if (useTCP) _client = new DatadogTcpClient(Url, Port, UseSSL, ApiKey); else _client = new DatadogHttpClient(Url, ApiKey); } protected override void Write(LogEventInfo logEvent) { } protected override void Write(AsyncLogEventInfo logEvent) => EmitBatch(new[] {logEvent}); protected override void Write(IList<AsyncLogEventInfo> logEvents) => EmitBatch(logEvents); protected void EmitBatch(IList<AsyncLogEventInfo> events) { try { if (!events.Any()) return; var formattedEvents = events.Select(FormPayload).ToArray(); _client.Write(formattedEvents); foreach (var ev in events) ev.Continuation(null); } catch (Exception ex) { InternalLogger.Error(ex.FlattenToActualException(), "ElasticSearch: Error while sending log messages"); foreach (var ev in events) ev.Continuation(ex); } } public string FormPayload(AsyncLogEventInfo ev) { var logEvent = ev.LogEvent; //var document = GetAllProperties(logEvent); //document.Add("date", logEvent.TimeStamp); //document.Add("level", logEvent.Level.Name); //document.Add("message", RenderLogEvent(Layout, logEvent)); var document = new Dictionary<string, object> { {"date", logEvent.TimeStamp}, {"level", logEvent.Level.Name}, {"message", RenderLogEvent(Layout, logEvent)} }; if (Source != null) document.Add("ddsource", Source); if (Service != null) document.Add("service", Service); if (Host != null) document.Add("host", Host); if (Tags != null) document.Add("ddtags", Tags); if (logEvent.Exception != null) { var jsonString = JsonConvert.SerializeObject(logEvent.Exception, _jsonSerializerSettings.Value); var ex = JsonConvert.DeserializeObject<ExpandoObject>(jsonString); document.Add("exception", ex.ReplaceDotInKeys()); } foreach (var field in Fields) { var renderedField = RenderLogEvent(field.Layout, logEvent); if (string.IsNullOrWhiteSpace(renderedField)) continue; try { document[field.Name] = renderedField.ToSystemType(field.LayoutType, logEvent.FormatProvider, JsonSerializer); } catch (Exception ex) { _jsonSerializer = null; // Reset as it might now be in bad state InternalLogger.Error(ex, "ElasticSearch: Error while formatting field: {0}", field.Name); } } if (IncludeAllProperties && logEvent.HasProperties) foreach (var p in logEvent.Properties) { var propertyKey = p.Key.ToString(); if (_excludedProperties.Contains(propertyKey)) continue; if (document.ContainsKey(propertyKey)) continue; document[propertyKey] = p.Value; } var result = JsonConvert.SerializeObject(document, Formatting.None, Settings); return result; } private static JsonSerializerSettings CreateJsonSerializerSettings() { var jsonSerializerSettings = new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore, CheckAdditionalContent = true}; jsonSerializerSettings.Converters.Add(new StringEnumConverter()); return jsonSerializerSettings; } protected override void Dispose(bool disposing) { _client.Close(); base.Dispose(disposing); } } }
35.792793
119
0.567833
[ "Apache-2.0" ]
dmitrynovik/nlog-target-datadog
src/NLog.Target.Datadog/DataDogTarget.cs
7,948
C#