content
stringlengths
23
1.05M
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Dragging : MonoBehaviour { public float catchingDistance = 3f; bool isDragging = false; GameObject draggingObject; // Use this for initialization void Start() { } // Update is called once per frame void Update() { if (Input.GetMouseButton(0)) { if (!isDragging) { draggingObject = GetObjectFromMouseRaycast(); if (draggingObject) { isDragging = true; } } else if (draggingObject != null) { draggingObject.GetComponent<Rigidbody>().AddForce(CalculateMouse3DVector()); } } else { if (draggingObject != null) { } isDragging = false; } } Vector3 dragAnchor; Vector3 draganchor3d; private GameObject GetObjectFromMouseRaycast() { GameObject gmObj = null; RaycastHit hitInfo = new RaycastHit(); bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo); if (hit) { if (hitInfo.collider.gameObject.GetComponent<Rigidbody>() && Vector3.Distance(hitInfo.collider.gameObject.transform.position, transform.position) <= catchingDistance) { gmObj = hitInfo.collider.gameObject; dragAnchor = Input.mousePosition; draganchor3d = gmObj.transform.position; } } return gmObj; } private Vector3 CalculateMouse3DVector() { Vector3 v3 = Input.mousePosition - dragAnchor; v3 = Quaternion.LookRotation(draganchor3d - transform.position) * v3; v3 *= 1f; return v3; } }
using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using static Veldrid.Sdl2.Sdl2Native; namespace Veldrid.Sdl2 { internal static class Sdl2EventProcessor { public static readonly object Lock = new object(); private static readonly Dictionary<uint, Sdl2Window> _eventsByWindowID = new Dictionary<uint, Sdl2Window>(); public static unsafe void PumpEvents() { Debug.Assert(Monitor.IsEntered(Lock)); SDL_Event ev; while (SDL_PollEvent(&ev) == 1) { uint windowID = ev.windowID; if (_eventsByWindowID.TryGetValue(ev.windowID, out Sdl2Window window)) { window.AddEvent(ev); } } } public static void RegisterWindow(Sdl2Window window) { lock (Lock) { _eventsByWindowID.Add(window.WindowID, window); } } public static void RemoveWindow(Sdl2Window window) { lock (Lock) { _eventsByWindowID.Remove(window.WindowID); } } } }
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.Rendering; using SSM.Grid; namespace SSM.GraphDrawing { public static class ScheduleTextureHelper { private static Dictionary<Tuple<int, Color, Color>, Sprite> textureDictionary = new Dictionary<Tuple<int, Color, Color>, Sprite>(); public static Sprite GetSprite(int[] binaryStates, Color colorOn, Color colorOff) { int integerStates = MGHelper.BinaryToInt(binaryStates); var key = Tuple.Create(integerStates, colorOn, colorOff); textureDictionary.TryGetValue(key, out Sprite sprite); if (sprite != null) { return sprite; } else { var barWidth = 4; var width = binaryStates.Length * barWidth; var height = 4; var t = new Texture2D( width, height, TextureFormat.RGB565, mipCount: 4, linear: true) { anisoLevel = 16, filterMode = FilterMode.Bilinear }; var colorArray = new Color[width * height]; for (int iRow = 0; iRow < height; iRow++) { for (int iCol = 0; iCol < width; iCol++) { int i = iRow * width + iCol; int iState = iCol / barWidth; colorArray[i] = binaryStates[iState] == 0 ? colorOff : colorOn; } } t.SetPixels(colorArray); t.Apply(true); var rect = new Rect(0.0f, 0.0f, width, height); sprite = Sprite.Create(t, rect, rect.size / 2.0f, 100.0f, 1); textureDictionary.Add(key, sprite); return sprite; } } } }
 namespace FitForLife.Tests.Controllers { using FitForLife.Controllers; using FitForLife.Web.ViewModels.Events; using FluentAssertions; using MyTested.AspNetCore.Mvc; using Xunit; using static Data.Events; public class EventsControllerTest { [Fact] public void IndexShouldReturnViewWithCorrectModelAndData() => MyMvc .Pipeline() .ShouldMap("/Appointments") .To<AppointmentsController>(c => c.Index()) .Which(controller => controller .WithData(FiveEvents)) .ShouldReturn() .View(view => view .WithModelOfType<AllEventsViewModel>() .Passing(m => m.Events.Should().HaveCount(5))); } }
using FullStackJobs.GraphQL.Core.Domain.Entities; using FullStackJobs.GraphQL.Core.Domain.Values; using GraphQL.Types; namespace FullStackJobs.GraphQL.Infrastructure.GraphQL.Types.Input { public class UpdateJobInputType : InputObjectGraphType<Job> { public UpdateJobInputType() { Name = "UpdateJobInput"; Field(x => x.Id); Field(x => x.Company, true); Field(x => x.Position, true); Field(x => x.Location, true); Field(x => x.AnnualBaseSalary, true); Field(x => x.Description, true); Field(x => x.Responsibilities, true); Field(x => x.Requirements, true); Field(x => x.ApplicationInstructions, true); Field<EnumerationGraphType<Status>>("status"); Field<ListGraphType<TagInputType>>("tags"); } } }
using System; using System.Linq; namespace ClumsyVM.Architecture { public static class MicroCodeDisassembler { public static void Disassemble(string[] codeLines) { var instructions = codeLines .Select(line => new MicroCodeInstruction(line)) .ToArray(); const string indent = " "; for (int i = 0; i < instructions.Length; i++) { var instruction = instructions[i]; if (instruction.IsEmpty) continue; Console.Write($"{i:X8}: "); if (instruction.GetDestinationsCount() > 0) Console.Write(instruction.Destinations.ToString().ToLowerInvariant() + " := "); Console.Write(instruction.GetAluMnemonic()); if (instruction.Memory != 0) { Console.WriteLine(); Console.Write(indent); Console.Write(instruction.GetMemoryMnemonic()); } if (instruction.AddReg3ToNextOffset || instruction.NextOffset != i + 1) { Console.WriteLine(); Console.Write(indent); Console.Write("goto "); Console.Write(instruction.AddReg3ToNextOffset ? "r3" : instruction.NextOffset.ToString("X8")); Console.Write(";"); Console.WriteLine(); } Console.WriteLine(); } } } }
// 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. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.VisualStudio.LanguageServices.Xaml; namespace Microsoft.CodeAnalysis.Xaml.Diagnostics.Analyzers { [DiagnosticAnalyzer(StringConstants.XamlLanguageName)] internal class XamlDocumentDiagnosticAnalyzer : DocumentDiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return XamlProjectService.AnalyzerService?.SupportedDiagnostics ?? ImmutableArray<DiagnosticDescriptor>.Empty; } } public override async Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { if (XamlProjectService.AnalyzerService == null) { return ImmutableArray<Diagnostic>.Empty; } return await XamlProjectService.AnalyzerService.AnalyzeSyntaxAsync(document, cancellationToken).ConfigureAwait(false); } public override async Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken) { if (XamlProjectService.AnalyzerService == null) { return ImmutableArray<Diagnostic>.Empty; } return await XamlProjectService.AnalyzerService.AnalyzeSemanticsAsync(document, cancellationToken).ConfigureAwait(false); } } }
using System; using System.Collections.Generic; using System.Linq; using AutoBuilder.Items; using AutoBuilder.Model; using log4net.Repository.Hierarchy; using Terraria.ModLoader; using Terraria.ModLoader.IO; namespace AutoBuilder { public class AutoBuilderWorld : ModWorld { public override void Initialize() { Constants.Logger = mod.Logger; if (!Constants.GetCatalogEntries().Any()) { Constants.Init(); } base.Initialize(); } public override void Load(TagCompound tag) { try { List<Blueprint> blueprints = tag.Get<List<Blueprint>>("CustomBlueprints"); BlueprintArchive.Instance.LoadCustomBlueprints(blueprints); } catch (Exception e) { mod.Logger.Error(e); } } public override TagCompound Save() { try { return new TagCompound { ["CustomBlueprints"] = BlueprintArchive.Instance.CustomBlueprints }; } catch (Exception e) { mod.Logger.Error(e); } return new TagCompound() { ["CustomBlueprints"] = new List<Blueprint>() }; } } }
namespace RetroGamesGo.Core.ViewModels { using MvvmCross.Navigation; using MvvmCross.ViewModels; /// <summary> /// Root empty ViewModel for setup up the startup. /// </summary> public class RootViewModel : MvxViewModel { private bool viewAppeared; private readonly IMvxNavigationService navigationService; /// <summary> /// Gets by DI the required services /// </summary> public RootViewModel(IMvxNavigationService navigationService) { this.navigationService = navigationService; } /// <summary> /// On appearing loads the login or the menu and main viewmodel /// </summary> public override void ViewAppeared() { if (viewAppeared) return; MvxNotifyTask.Create(async () => { try { // Loads the menu and first viewModel this.viewAppeared = true; await this.navigationService.Navigate<MenuViewModel>(); await this.navigationService.Navigate<MainViewModel>(); } catch { // This shouldn't fail } }); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Single_Socket_Handler : MonoBehaviour { public Sprite availableSprite, unavailableSprite, neutralSprite; public SpriteRenderer spriteRenderer; public bool available = false; void Start() { spriteRenderer = gameObject.GetComponent<SpriteRenderer>(); availableSprite = Resources.Load<Sprite>("sprites/sockets/available"); unavailableSprite = Resources.Load<Sprite>("sprites/sockets/unavailable"); neutralSprite = Resources.Load<Sprite>("sprites/sockets/neutral"); gameObject.transform.localScale = new Vector3(0.3f,0.3f,0.3f); } public void SetSocketAppearanceToUnavailable(){ available = false; gameObject.transform.localScale = new Vector3(0.2f,0.2f,0.2f); spriteRenderer.sprite = unavailableSprite; } public void SetSocketAppearanceToAvailable(){ available = true; gameObject.transform.localScale = new Vector3(0.35f,0.35f,0.35f); spriteRenderer.sprite = availableSprite; } public void HoverOverAvailable(){ if (available){ gameObject.transform.localScale = new Vector3(0.4f,0.4f,0.4f); } } public void UnHover(){ if (available){ gameObject.transform.localScale = new Vector3(0.35f,0.35f,0.35f); } } public void SetSocketAppearanceToNeutral(){ available = false; gameObject.transform.localScale = new Vector3(0.3f,0.3f,0.3f); spriteRenderer.sprite = neutralSprite; } }
//Apache2, 2017, WinterDev //Apache2, 2009, griffm, FO.NET namespace Fonet.Fo.Expr { internal class FromTableColumnFunction : FunctionBase { public override int NumArgs { get { return 1; } } public override Property Eval(Property[] args, PropertyInfo pInfo) { string propName = args[0].GetString(); if (propName == null) { throw new PropertyException("Incorrect parameter to from-table-column function"); } throw new PropertyException("from-table-column unimplemented!"); } } }
using System; using System.Diagnostics.CodeAnalysis; using NUnit.Framework; using BddStyle.NUnit; using FluentAssertions; namespace LogCast.Test.given_LogManager { [SuppressMessage("ReSharper", "ExplicitCallerInfoArgument")] public class when_getting_logger : ContextBase { [TestCase("name1")] [TestCase("<name2>")] [TestCase("name3.postfix")] public void then_logger_name_is_not_changed_for_(string name) { LogManager.GetLogger(name).Name.Should().Be(name); } [Test] public void then_calling_class_is_used_as_default_logger_name() { LogManager.GetLogger().Name.Should().Be(nameof(when_getting_logger)); } [Test] public void then_rooted_file_path_is_trimmed_to_name() { LogManager.GetLogger(@"C:\Users\name.ext").Name.Should().Be("name"); } [Test] public void then_getting_logger_by_type_uses_type_parameter_name() { LogManager.GetLogger<ArgumentException>().Name.Should().Be(nameof(ArgumentException)); } [Test] public void then_getting_logger_by_type_uses_type_name() { LogManager.GetLogger(typeof(ArgumentException)).Name.Should().Be(nameof(ArgumentException)); } } }
// Licensed under the MIT License. // See LICENSE file in the project root for full license information. using Microsoft.Extensions.Logging; namespace Najlot.Log.Extensions.Logging { [ProviderAlias("Najlot.Log")] public sealed class NajlotLogProvider : ILoggerProvider { private LogAdministrator _logAdministrator; private bool _disposed = false; public NajlotLogProvider(LogAdministrator logConfigurator) { _logAdministrator = logConfigurator; } public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) { return new NajlotLogWrapper(_logAdministrator.GetLogger(categoryName)); } public void Dispose() { if (_disposed) { return; } _disposed = true; _logAdministrator.Dispose(); _logAdministrator = null; } } }
using GISCore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GISWinApp { public class LogHelper { static LogHelper() { IsFirstTime = !File.Exists(LOG_PATH); } public static readonly string LOG_PATH = Path.Combine(AppContext.BaseDirectory, GISConst.AppData); private static string GetCode() { if (!File.Exists(LOG_PATH)) { using (var sw = File.CreateText(LOG_PATH)) { sw.Write("00"); } } var code = File.ReadAllText(LOG_PATH); if (string.IsNullOrWhiteSpace(code) || code.Length != 2) { code = "00"; } return code; } private static void Log(LogType type) { // 00 未操作 // 01 web 复制成功 // 10 数据库迁移成功 // 11 web 和数据库迁移成功 var code = GetCode().ToArray(); if (type == LogType.web) { code[1] = '1'; } else if (type == LogType.db) { code[0] = '1'; } else if (type == LogType.rsweb) { code[1] = '0'; } File.WriteAllText(LOG_PATH, string.Join("", code)); } public static bool IsSuccess => GetCode() == "11"; public static void CopyWebOk() { Log(LogType.web); } public static void MigrateDbOk() { Log(LogType.db); } public static void ReSelectWeb() { Log(LogType.rsweb); } public static bool WebIsOk => GetCode()[1] == '1'; public static bool DbIsOk => GetCode()[0] == '1'; public static bool IsFirstTime { get; } } public enum LogType { // web 复制成功 web, // 数据库迁移成功 db, // 撤销 web 复制 rsweb } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using RxAs.Rx4.ProofTests.Mock; namespace RxAs.Rx4.ProofTests.Operators { public class EmptyEventFixture { private IObservable<int> obs; [SetUp] public void Setup() { obs = Observable.Empty<int>(); } [Test] public void immediately_completes_when_subscribed_to_with_no_scheduler() { obs = Observable.Empty<int>(); bool completed = false; using (obs.Subscribe(x => { }, () => completed = true)) { Assert.IsTrue(completed); } } [Test] public void publishing_is_run_through_publishing_scheduler() { ManualScheduler scheduler = new ManualScheduler(); obs = Observable.Empty<int>(scheduler); bool completed = false; var subs = obs.Subscribe(x => { }, () => completed = true); Assert.IsFalse(completed); scheduler.RunAll(); Assert.IsTrue(completed); } [Test] public void schedule_is_cancelled_when_completed() { bool disposed = false; ClosureScheduler scheduler = new ClosureScheduler( a => { a(); return new ClosureDisposable(() => disposed = true); } ); obs = Observable.Empty<int>(scheduler); var subs = obs.Subscribe(x => { }, () => { }); Assert.IsTrue(disposed); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ArvidsonFoto.Data; using ArvidsonFoto.Models; using Serilog; namespace ArvidsonFoto.Services { public class CategoryService : ICategoryService { // Databas koppling private readonly ArvidsonFotoDbContext _entityContext; public CategoryService(ArvidsonFotoDbContext context) { _entityContext = context; } public bool AddCategory(TblMenu category) { bool success = false; try { _entityContext.TblMenus.Add(category); _entityContext.SaveChanges(); success = true; } catch(Exception ex) { success = false; throw new Exception("Fel vid skapande av kategori. Felmeddelande: " + ex.Message); } return success; } public int GetLastId() { int highestID = -1; highestID = _entityContext.TblMenus.OrderBy(c => c.MenuId).LastOrDefault().MenuId; return highestID; } public TblMenu GetByName(string categoryName) { TblMenu category = new TblMenu(); category = _entityContext.TblMenus.FirstOrDefault(c => c.MenuText.Equals(categoryName)); if(category is null) { Log.Warning("Could not find category: '" + categoryName + "'"); } return category; } public TblMenu GetById(int? id) { TblMenu category = _entityContext.TblMenus.FirstOrDefault(c => c.MenuId.Equals(id)); if(category is null) { Log.Information("Could not find id with number: "+id); } return category; } public List<TblMenu> GetAll() { List<TblMenu> categories; categories = _entityContext.TblMenus.ToList(); return categories; } public List<TblMenu> GetSubsList(int categoryID) { List<TblMenu> categories; categories = _entityContext.TblMenus.Where(c => c.MenuMainId.Equals(categoryID)).ToList(); return categories; } public string GetNameById(int? id) { string categoryName = ""; TblMenu category = _entityContext.TblMenus.FirstOrDefault(c => c.MenuId.Equals(id)); if (category is not null) categoryName = category.MenuText; return categoryName; } public int GetIdByName(string categoryName) { int menuID = -1; TblMenu category = _entityContext.TblMenus.FirstOrDefault(c => c.MenuText.Equals(categoryName)); if (category is not null) menuID = category.MenuId; return menuID; } } }
using System.ComponentModel; namespace PublishingUtility { [TypeConverter(typeof(LocaleDisplayNameConverter))] public enum Locale { en_US, en_GB, ja_JP, fr_FR, es_ES, de_DE, it_IT, nl_NL, pt_PT, pt_BR, ru_RU, ko_KR, zh_Hans, zh_Hant, fi_FI, sv_SE, da_DK, nb_NO, pl_PL } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; namespace CommandLineTools.CommandLine { [System.Runtime.Versioning.NonVersionable] public class ArgumentsRule { private readonly Func<AppliedOption, string> validate; private readonly Func<ParseResult, IEnumerable<string>> suggest; private readonly Func<string> defaultValue; public IReadOnlyCollection<string> AllowedValues { get; } internal Func<string> GetDefaultValue { get { return () => defaultValue(); } } public string? Description { get; } public string? Name { get; } internal Func<AppliedOption, object> Materializer { get; } public ArgumentsRule(Func<AppliedOption, string> validate) : this(validate, null) { } internal ArgumentsRule(Func<AppliedOption, string> validate, IReadOnlyCollection<string>? allowedValues = null, Func<string>? defaultValue = null, string? description = null, string? name = null, Func<ParseResult, IEnumerable<string>>? suggest = null, Func<AppliedOption, object>? materialize = null) { this.validate = validate ?? throw new ArgumentNullException(nameof(validate)); this.defaultValue = defaultValue ?? (() => null); Description = description; Name = name; if (suggest == null) { this.suggest = result => AllowedValues.FindSuggestions(result); } else { this.suggest = result => suggest(result).ToArray().FindSuggestions(result.TextToMatch()); } AllowedValues = allowedValues ?? Array.Empty<string>(); Materializer = materialize; } public string Validate(AppliedOption option) { return validate(option); } internal IEnumerable<string> Suggest(ParseResult parseResult) { return suggest(parseResult); } internal object Materialize(AppliedOption appliedOption) { return Materializer?.Invoke(appliedOption); } } }
using System.Collections.Generic; using CommandLine; using CommandLine.Text; using ProSuite.Commons.Essentials.CodeAnnotations; namespace ProSuite.Microservices.Server.AO { [UsedImplicitly(ImplicitUseTargetFlags.WithMembers)] public class MicroserverArguments { [Option('h', "hostname", Required = false, HelpText = "The host name.", Default = "LOCALHOST")] public string HostName { get; set; } [Option('p', "port", Required = false, HelpText = "The port.", Default = 5151)] public int Port { get; set; } [Option('c', "certificate", Required = false, HelpText = "The server certificate to be used for transport security (SSL/TLS). " + "Specify the server certificate subject or thumbprint from the certificate " + "store (Local Computer). Note that the certificate's private key must be " + "accessible to this executable, unless the --key parameter is also specified. " + "Alternatively this can be a PEM file containing the certificate " + "chain (including the root certificate shared with the client).")] public string Certificate { get; set; } [Option('k', "key", Required = false, HelpText = "The private key PEM file (to remain on the server). If not specified and the " + "certificate found in the store has a private exportable key the private key " + "will be extracted from the certificate.")] public string PrivateKeyFile { get; set; } [Option( 't', "mutual_TLS", Required = false, HelpText = "Enforce mutual authentication for transport layer security (SSL/TLS).", Default = false)] public bool EnforceMutualTls { get; set; } [Option('m', "maxparallel", Required = false, HelpText = "The maximum number of parallel threads to be used for processing. " + "Below 0 means one less than the CPU count", Default = -1)] public int MaxParallel { get; set; } [Option('v', "verbose", Required = false, HelpText = "Set log level to verbose.")] public bool VerboseLogging { get; set; } [Option("test", Hidden = true, HelpText = "Hidden and undocumented option to use Test configuration.")] public bool TestConfiguration { get; set; } [Usage] public static IEnumerable<Example> Examples { get { yield return new Example( "Simple example", new MicroserverArguments { HostName = "localhost", Port = 5151 }); yield return new Example( "Using transport layer security", new MicroserverArguments { HostName = "mycomputer.ourdomain.ch", Port = 5151, Certificate = "021f85bc637e33df8d8b1583ea2058e92c73335d" }); } } public override string ToString() { string privateKey = string.IsNullOrEmpty(PrivateKeyFile) ? PrivateKeyFile : "**********"; return $"Host Name: {HostName}, Port: {Port}, Certificate: {Certificate}, " + $"Private Key: {privateKey}, Enforce Mutual TLS: {EnforceMutualTls}, " + $"Maximum parallel processes: {MaxParallel}"; } } }
namespace BitTorrentEdu.DTOs { public class Torrent { public Torrent(string announceUrl, TorrentInfoSingle info) { AnnounceUrl = announceUrl; Info = info; Left = info.Length; } public TorrentInfoSingle Info { get; set; } public string AnnounceUrl { get; set; } public long Uploaded { get; set; } public long Downloaded { get; set; } public long Left { get; set; } } }
// Copyright (c) 2007 James Newton-King. All rights reserved. // Use of this source code is governed by The MIT License, // as found in the license.md file. namespace Argon; /// <summary> /// Provides a base class for converting a <see cref="DateTime"/> to and from JSON. /// </summary> public abstract class DateTimeConverterBase : JsonConverter { /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <returns> /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type type) { if (type == typeof(DateTime) || type == typeof(DateTime?)) { return true; } return type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?); } }
using System.Collections.Generic; using Microsoft.CodeAnalysis; namespace BitTools.Core.Contracts.HtmlClientProxyGenerator { public interface IDefaultHtmlClientProxyGenerator { void GenerateCodes(Workspace workspace, Solution solution, IList<Project> projects); } }
using System.Collections.Generic; using System.IO; using PontoDigitalMVC.Models; namespace PontoDigitalMVC.Repositories { public class AdministradorRepositorio { private List<AdministradorModel> administradores = new List<AdministradorModel>(); private const string PATH = "DataBases/Administrador.csv"; public List<AdministradorModel> DadosDoAdministrador() { var cadastro = File.ReadAllLines(PATH); foreach (var item in cadastro) { var dados = item.Split(";"); AdministradorModel admin = new AdministradorModel(); admin.Id = int.Parse(dados[0]); admin.NomeAdm = dados[1]; admin.EmailAdm = dados[2]; admin.SenhaAdm = dados[3]; administradores.Add(admin); } return administradores; } } }
namespace WhateverDevs.TwoDAudio.Runtime { /// <summary> /// Interface that defines the class that other classes will call to play specific 2D audios. /// </summary> public interface IAudioManager { /// <summary> /// Check if an audio is available to play. /// </summary> /// <param name="audioReference"></param> /// <returns></returns> bool IsAudioAvailable(AudioReference audioReference); /// <summary> /// Play an audio once. /// </summary> /// <param name="audioReference">The audio to play.</param> /// <param name="loop">Loop the audio?</param> void PlayAudio(AudioReference audioReference, bool loop = false); /// <summary> /// Stop the given audio if it's playing. /// </summary> /// <param name="audioReference"></param> void StopAudio(AudioReference audioReference); /// <summary> /// Stop all audios, probably only used in abort situations. /// </summary> void StopAllAudios(); } }
using System.Xml.Serialization; namespace DataAccess.Enums { public enum ColumnType { [XmlEnum(Name = "text")] Text = 0, [XmlEnum(Name = "integer")] Integer = 1, [XmlEnum(Name = "real")] Real = 2, [XmlEnum(Name = "none")] None = 3, [XmlEnum(Name = "numeric")] Numeric = 4, [XmlEnum(Name = "varchar")] Varchar = 5, [XmlEnum(Name = "nvarchar")] Nvarchar = 6, [XmlEnum(Name = "blob")] Blob = 7, [XmlEnum(Name = "timestamp")] Timestamp = 8, } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace rest_api.Models { public class Teacher { public int Id { get; set; } public String Name { get; set; } public String Email { get; set; } public Teacher(int id, String name, String email) { this.Id = id; this.Name = name; this.Email = email; } } }
using LCGoLOverlayProcess.Game; using LCGoLOverlayProcess.Helpers; using SharpDX.Direct3D9; using System.Collections.Concurrent; namespace LCGoLOverlayProcess.Overlay { internal class LCGoLOverlay : IOverlay { private readonly ConcurrentDictionary<GameState, IOverlay> _overlayLookup; public LCGoLOverlay() { var loadingOverlay = new LoadingScreenOverlay(); var otherOverlay = new OtherOverlay(); _overlayLookup = new ConcurrentDictionary<GameState, IOverlay> { [GameState.InEndScreen] = loadingOverlay, [GameState.InLoadScreen] = loadingOverlay, [GameState.Other] = otherOverlay, }; } public void Render(GameInfo game, Device d3d9Device, LiveSplitHelper liveSplitHelper) { // TODO: Pass in a scaling factor here? At least figure our how overlay scaling will work. if (_overlayLookup.TryGetValue(game.State.Current, out var overlay)) { overlay.Render(game, d3d9Device, liveSplitHelper); } else { _overlayLookup[GameState.Other].Render(game, d3d9Device, liveSplitHelper); } } } }
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; namespace Localizations.PhraseApp.Infrastructure { internal static class OptionExtensions { public static IServiceCollection AddOption<T, V>(this IServiceCollection services) where T : class, new() where V : OptionsProviderBase<T> { services.AddSingleton<IConfigureOptions<T>, V>(); services.AddSingleton<IOptionsChangeTokenSource<T>, V>(); services.AddSingleton<IOptionsFactory<T>, V>(); return services; } } }
using ArchaicQuestII.GameLogic.Core; using ArchaicQuestII.GameLogic.Skill.Model; namespace ArchaicQuestII.GameLogic.Skill.Type { /// <summary> /// Handles effects on player attributes which is defined in Attributes.cs /// Effects can be negative or positive, and can stack. /// </summary> public class SkillAffect { private readonly IWriteToClient _writer; private static SkillTarget _skillTarget; private readonly int _value; public SkillAffect(IWriteToClient writer, SkillTarget skillTarget, int value) { _writer = writer; _skillTarget = skillTarget; _value = value; } public void CauseAffect() { var action = new SkillMessage(_writer); if (_skillTarget.Skill.Effect.Modifier.PositiveEffect) { _skillTarget.Target.Attributes.Attribute[_skillTarget.Skill.Effect.Location] += _value; } else { _skillTarget.Target.Attributes.Attribute[_skillTarget.Skill.Effect.Location] -= _value; } } } }
namespace Hatchet.Graphics { public interface ITextured { IHatchetTexture2D Texture { get; set; } } }
namespace Resources.Endurance.Enums { public enum VetGateStatus { NotEntered = 0, Passed = 1, Failed = 2, } }
using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace MedicalExaminer.Models.Enums { [JsonConverter(typeof(StringEnumConverter))] public enum QapDiscussionOutcome { MccdCauseOfDeathProvidedByQAP, MccdCauseOfDeathProvidedByME, MccdCauseOfDeathAgreedByQAPandME, ReferToCoronerFor100a, ReferToCoronerInvestigation, DiscussionUnableToHappen } }
using System.Collections; using System.Collections.Generic; using UnityEditor.PackageManager; using UnityEngine; using UnityEngine.UIElements; public class Waypoint : MonoBehaviour { // ok to use as this is data class public bool isExplored = false; // explored in BFS ? public bool isPlacable = true; // buildeable slot ? public Waypoint exploredFrom; const int gridSize = 10; // public method to get the CONST grid size public int GetGridSize() { return gridSize; } // public method to get the coords of WP public Vector2Int GetGridPos() { return new Vector2Int( Mathf.RoundToInt(transform.position.x / gridSize), Mathf.RoundToInt(transform.position.z / gridSize) ); } // get the current location of mouse - if left click is down, build a tower private void OnMouseOver() { HighlightBlocks(); BuildTowers(); } // build towers on mouse clock private void BuildTowers() { if (Input.GetMouseButtonDown(0)) { if (isPlacable) { FindObjectOfType<TowerFactory>().AddTower(this); } else { print("You can't place that here!"); } } } // highlight buildeable tiles or stop when built upon private void HighlightBlocks() { if (isPlacable) { this.GetComponentInChildren<Renderer>().material.SetFloat("_Metallic", 0.5f); } else { this.GetComponentInChildren<Renderer>().material.SetFloat("_Metallic", 0f); } } // revert the highlight on mouse exit private void OnMouseExit() { this.GetComponentInChildren<Renderer>().material.SetFloat("_Metallic", 0f); } }
using System; using WildFarm.Contracts.Foods; using WildFarm.Models.Foods; namespace WildFarm.Factories { public static class FoodFactory { public static IFood Create(string[] tokens) { var food = tokens[0]; var quantity = int.Parse(tokens[1]); switch (food) { case nameof(Vegetable): return new Vegetable(quantity); case nameof(Fruit): return new Fruit(quantity); case nameof(Meat): return new Meat(quantity); case nameof(Seeds): return new Seeds(quantity); default: throw new NotImplementedException("Current Food Type Does Not Exist!"); } } } }
using System; namespace Services { public class Primary { /// <summary> /// Check if an 32-bit integer is a prime number. /// </summary> /// <param name="candidate">Number to check.</param> /// <returns>TRUE if Prime Number, else FALSE</returns> public bool IsPrime(int candidate) { return IsPrime((long)candidate); } /// <summary> /// Check if an 64-bit integer is a prime number. /// </summary> /// <param name="candidate">Number to check.</param> /// <returns>TRUE if Prime Number, else FALSE</returns> public bool IsPrime(long candidate) { if (candidate < 2) { return false; } throw new NotImplementedException("Please creat a test first."); } } }
namespace JsonPatchGenerator.Core.Tests.Tests.JsonPatchGeneratorServiceTests { public interface IReplaceTests { void ArrayElementPropertyReplaceOperationHasCorrectPath(); void ArrayElementPropertyReplaceOperationHasCorrectValue(); void ArrayElementReplaceOperationHasCorrectPath(); void CanHandleMultipleDifferences(); void CreateCorrectPathForNestedPropertiesOnReplace(); void DontCreateExtraOperationsOnReplace(); void ReplaceOperationForComplexPropertiesHasCorrectValue(); void ReplaceOperationHasCorrectPath(); void ReplaceOperationHasCorrectValue(); void SimpleTypeArrayElementReplaceOperationHasCorrectValue(); void SupportReplaceOperationForSimpleTypes(); void SupportReplaceOperationsForNestedObjects(); void SupportReplacingPropertiesOfArrayElement(); void SupportReplacingValuesWithNull(); void SupportSimpleTypeArrayElementReplacing(); void SupportStringElementReplacing(); void StringElementReplaceOperationHasCorrectPath(); void StringElementReplaceOperationHasCorrectValue(); void SupportSimpleTypeListElementReplacing(); void SimpleTypeListElementReplaceOperationHasCorrectPath(); void SimpleTypeListElementReplaceOperationHasCorrectValue(); void SupportReplacingPropertiesOfListElement(); void ListElementPropertyReplaceOperationHasCorrectPath(); void ListElementPropertyReplaceOperationHasCorrectValue(); } }
using System; namespace StackCalculator { /// <summary> /// Last-in-first-out container of integer values based on array. /// </summary> public class ArrayStack : IStack { private const int size = 100; private int[] stack = new int[size]; private int topIndex = 0; /// <summary> /// Adds value to the top of the stack. /// </summary> /// <param name="value">Value to push into stack.</param> public void Push(int value) { if (topIndex >= size) { Array.Resize(ref stack, size * 2); } stack[topIndex] = value; ++topIndex; } /// <summary> /// Removes value from the top of the stack. /// </summary> /// <returns>The value that has been deleted.</returns> public int Pop() { if (IsEmpty()) { throw new InvalidOperationException("Removing from the empty stack"); } var temp = Peek(); stack[topIndex] = 0; --topIndex; return temp; } /// <summary> /// Shows the value at the top of the stack. /// </summary> /// <returns>The value at the top of the stack.</returns> public int Peek() { if (IsEmpty()) { throw new InvalidOperationException("Peek from the empty stack"); } return stack[topIndex - 1]; } /// <summary> /// Checks if the stack is empty. /// </summary> /// <returns>True if the stack is empty, false if it is not.</returns> public bool IsEmpty() => topIndex == 0; } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// 建筑物属性 /// </summary> /// <author>zhulin</author> /// public class BuildAttribute : NDAttribute { /// <summary> /// 死亡Mana /// </summary> protected int m_DeadMana; public int DeadMana { get { return m_DeadMana; } set { m_DeadMana = value; } } private BuildInfo m_BuildInfo = null; public override void Init(int SceneID, LifeMCore Core, Life Parent) { base.Init(SceneID,Core,Parent); m_Broken = false; if(m_BuildInfo != null) { m_Durability = m_BuildInfo.m_data0 ; BuildAttributeType = SkillM.GetBuildAttributeType(m_BuildInfo.m_RoomKind); JoinMap(SceneID ,m_StartPos ,m_BuildInfo.m_Shape); } } public BuildAttribute(){} public BuildAttribute( BuildInfo Info) { if(Info != null) { m_BuildInfo = Info; m_level = Info.Level; m_AttrType = Info.BuildType; m_phy_defend = Info.m_phydefend; m_magic_defend = Info.m_magicdefend; m_phy_attack = Info.m_phyattack; m_magic_attack = Info.m_magicattack; m_FullHp = Info.m_hp + Info.m_Floorhp; m_StartPos.Unit = Info.m_cx; m_StartPos.Layer = Info.m_cy; //熔炉房如果取中点,得到的点会可能出现再船外,所以特殊处理 /*if (m_BuildInfo.m_Shape.height > 1) { for(int unit = 0; unit < m_BuildInfo.m_Shape.width ; unit ++ ) { if( m_BuildInfo.m_Shape.GetShapeValue (0 , unit) == 1 ) { m_Pos.Layer = m_BuildInfo.m_cy ; m_Pos.Unit = m_BuildInfo.m_cx + unit * MapGrid.m_UnitRoomGridNum + 3; break; } } } else*/ { m_Pos.Unit = Info.m_cx + Info.m_Shape.width * MapGrid.m_UnitRoomGridNum /2; m_Pos.Layer = Info.m_cy; } m_Size = Info.m_Shape.width * MapGrid.m_UnitRoomGridNum; if(Info.m_damage == 0) m_IsDamage = false; else m_IsDamage = true; if(Info.m_RoomType == RoomType.ResRoom) m_IsResource = true; else m_IsResource = false; m_wood = Info.m_wood; m_stone = Info.m_stone; m_steel = Info.m_steel; m_Type = Info.BuildType; m_HideCd = Info.m_HideCD * 0.001f; m_ShipPutdata0 = Info.m_ShipPutdata0; m_ShipPutdata1 = Info.m_ShipPutdata1; m_bear = Info.m_bear; m_DeadMana = Info.Mana; } } public List<MapGrid> GetAllMapGrid() { List<MapGrid> l = new List<MapGrid>(); for(int layer = 0; layer < m_BuildInfo.m_Shape.height ; layer++) { for(int unit = 0; unit < m_BuildInfo.m_Shape.width ; unit ++ ) { if( m_BuildInfo.m_Shape.GetShapeValue (layer , unit) == 1 ) { int y = m_BuildInfo.m_cy + layer; int x = m_BuildInfo.m_cx + unit * MapGrid.m_UnitRoomGridNum + MapGrid.m_UnitRoomGridNum / 2; MapGrid g = MapGrid.GetMG(y,x); l.Add(g); } } } return l; } public bool CheckInBuildMap(Int2 Pos) { if (null == m_BuildInfo) return false; return m_BuildInfo.CheckInBuildMap (Pos); } protected void JoinMap(int SceneID, Int2 Start,ShapeType Info ) { if(Info == null) return ; List<Int2> l = new List<Int2>(); for(int layer = 0; layer < Info.height ; layer++) { for(int unit = 0; unit < Info.width ; unit ++ ) { if( Info.GetShapeValue (layer , unit) == 1 ) { for(int i = 0; i <= MapGrid.m_UnitRoomGridNum; i ++) { l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + i, Start.Layer + layer)); } /*l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + 0, Start.Layer + layer)); l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + 1, Start.Layer + layer)); l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + 2, Start.Layer + layer)); l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + 3, Start.Layer + layer)); l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + 4, Start.Layer + layer)); l.Add(new Int2(Start.Unit + unit * MapGrid.m_UnitRoomGridNum + 5, Start.Layer + layer));*/ } } } // foreach (Int2 Pos in l ) { MapGrid Gird = MapGrid.GetMG(Pos); if(Gird != null) { Gird.JoinBuild(m_SceneID); } } } protected override int GetBaseAttrData(EffectType Type) { if(Type == EffectType.Strength) return m_strength; else if(Type == EffectType.Agility) return m_agility; else if(Type == EffectType.Intelligence) return m_intelligence; else if(Type == EffectType.Hp) return m_FullHp; else if(Type == EffectType.PhyAttack) return m_phy_attack; else if(Type == EffectType.PhyDefense) return m_phy_defend; else if(Type ==EffectType.MagicAttack) return m_magic_attack; else if(Type ==EffectType.MagicDefense) return m_magic_defend; else if(Type ==EffectType.PhyCrit) return 1; else if(Type ==EffectType.MagicCrit) return 1; else if (Type == EffectType.CutPhyDefend) return m_CutPhyDefend; else if(Type == EffectType.CutMagDefend) return m_CutMagDefend; else if(Type == EffectType.CutphyDamage) return m_CutPhyDamage; else if(Type == EffectType.CutMagDamage) return m_CutMagDamage; else if(Type == EffectType.Dodge) return m_dodge; else if(Type == EffectType.Vampire) return m_Vampire; else if(Type == EffectType.Hit) return m_Hit; else if(Type == EffectType.RecoHp) return m_RecoHp; else if(Type == EffectType.RecoAnger) return m_RecoAnger; else if(Type == EffectType.AddDoctor) return m_AddDoctor; return 0; } protected override int GetType() { return m_Type; } /// <summary> /// 获取力量 /// </summary> protected virtual int GetStrength() { return m_strength; } /// <summary> /// 获取敏捷 /// </summary> protected virtual int GetAgility() { return m_agility; } /// <summary> /// 获取智力 /// </summary> protected virtual int GetIntelligence() { return m_intelligence; } /// <summary> /// 获取魔法防御 /// </summary> protected override int GetMagicDefend() { return m_magic_defend; } /// <summary> /// 获取物理防御 /// </summary> protected override int GetPhyDefend() { return m_phy_defend; } /// <summary> /// 获取满血 /// </summary> protected override int GetFullHp() { return m_FullHp; } /// <summary> /// 获取建筑start位置 /// </summary> protected override Int2 GetStartPos() { return m_StartPos; } /// <summary> /// 获取建筑大小,体型 /// </summary> protected override int GetSize() { return m_Size; } /// <summary> /// 获取木材数量 /// </summary> protected override int GetWood() { return m_wood; } /// <summary> /// 获取石头数量 /// </summary> protected override int GetStone() { return m_stone; } /// <summary> /// 获取刚才数量 /// </summary> protected override int GetSteel() { return m_steel; } /// <summary> /// 建筑位置 /// </summary> protected override Int2 GetPos() { return m_Pos; } protected override int GetCritRatio() { return m_CritRatio; } /// <summary> /// 获取满怒气 /// </summary> protected override int GetFullAnger() { return 0; } }
using Examine; namespace Umbraco.Cms.Infrastructure.Examine { public interface IIndexPopulator { /// <summary> /// If this index is registered with this populator /// </summary> /// <param name="index"></param> /// <returns></returns> bool IsRegistered(IIndex index); /// <summary> /// Populate indexers /// </summary> /// <param name="indexes"></param> void Populate(params IIndex[] indexes); } }
using System; using System.Globalization; using System.Windows.Data; namespace MagicMesh { class PercentageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { return (int)Math.Round((float)value * 100) + "%"; } return string.Empty; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var stringValue = value.ToString().TrimEnd('%'); if (!string.IsNullOrEmpty(stringValue)) { float percent; float.TryParse(stringValue, out percent); return percent / 100; } return 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; using System.Xml.Serialization; namespace BuildingSmart.Serialization.Xml { public class headerData { [DataMember(Order = 0)] [XmlElement(ElementName ="name")] public string name { get; set; } [DataMember(Order = 1)] [XmlElement(ElementName = "time_stamp")] public DateTime time_stamp { get; set; } [DataMember(Order = 2)] [XmlElement(ElementName = "author")] public string author { get; set; } [DataMember(Order = 3)] [XmlElement(ElementName = "organization")] public string organization { get; set; } [DataMember(Order = 4)] [XmlElement(ElementName = "preprocessor_version")] public string preprocessor_version { get; set; } [DataMember(Order = 5)] [XmlElement(ElementName = "originating_system")] public string originating_system { get; set; } [DataMember(Order = 6)] [XmlElement(ElementName = "authorization")] public string authorization { get; set; } } }
using System; using System.Net.Sockets; using MineLib.Network.Classic.Packets; using MineLib.Network.IO; namespace MineLib.Network { // -- Classic logic is stored here public sealed partial class NetworkHandler { private void ConnectedClassic(IAsyncResult asyncResult) { _baseSock.EndConnect(asyncResult); // -- Create our Wrapped socket. _stream = new MinecraftStream(new NetworkStream(_baseSock), NetworkMode); // -- Subscribe to DataReceived event. OnDataReceived += HandlePacketClassic; // -- Begin data reading. _stream.BeginRead(new byte[0], 0, 0, PacketReceiverClassicAsync, null); } private void PacketReceiverClassicAsync(IAsyncResult ar) { if (_baseSock == null || !Connected) return; var packetId = _stream.ReadByte(); // Connection lost if (packetId == 255) { Crashed = true; return; } var length = ServerResponseClassic.ServerResponse[packetId]().Size; var data = _stream.ReadByteArray(length - 1); OnDataReceived(packetId, data); _baseSock.EndReceive(ar); _baseSock.BeginReceive(new byte[0], 0, 0, SocketFlags.None, PacketReceiverClassicAsync, null); } /// <summary> /// Packets are handled here. /// </summary> /// <param name="id">Packet ID</param> /// <param name="data">Packet byte[] data</param> private void HandlePacketClassic(int id, byte[] data) { using (var reader = new MinecraftDataReader(data, NetworkMode)) { if (ServerResponseClassic.ServerResponse[id] == null) return; var packet = ServerResponseClassic.ServerResponse[id]().ReadPacket(reader); RaisePacketHandled(id, packet, null); } } } }
using System; using System.IO; using System.Xml; using System.Xml.Schema; using Common.DebugUtils; namespace Common.Message { public class XmlValidation { static XmlValidation instance; XmlReaderSettings settings; private XmlValidation() { settings = new XmlReaderSettings(); settings.Schemas.Add("https://se2.mini.pw.edu.pl/17-results/", "TheProjectGameCommunication.xsd"); settings.ValidationType = ValidationType.Schema; } public static XmlValidation Instance { get { if (instance == null) instance = new XmlValidation(); return instance; } } public void Validate(string message) { XmlReader reader = XmlReader.Create(new StringReader(message), settings); XmlDocument document = new XmlDocument(); document.Load(reader); ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler); document.Validate(eventHandler); } static void ValidationEventHandler(object sender, ValidationEventArgs e) { ConsoleDebug.Error("\n ERROR IN VALIDATION\n "); switch (e.Severity) { case XmlSeverityType.Error: Console.WriteLine("Error: {0}", e.Message); throw new XmlException(); break; case XmlSeverityType.Warning: Console.WriteLine("Warning {0}", e.Message); throw new XmlException(); break; } } } }
using System; namespace DAQ.Pattern.Test { public class SupersonicTestPattern : PatternBuilder32 { private int valveChan = PatternBuilder32.ChannelFromNIPort(0,6); private int flashChan = PatternBuilder32.ChannelFromNIPort(0,5); private int qChan = PatternBuilder32.ChannelFromNIPort(0,2); private int pumpChan = PatternBuilder32.ChannelFromNIPort(0,4); private int detectorTrigChan = PatternBuilder32.ChannelFromNIPort(0,3); public int ShotSequence( int startTime, int sequenceLength, int shotEvery, int valvePulseLength, int delayToQ, int flashToQ, int delayToPump, int pumpPulseLength, int delayToDetection) { // HACK: this fixes a bug in triggered pattern gen, where the first line is // output before the trigger arrives. Needs to be improved. int time = 1; for (int i = 0 ; i < sequenceLength ; i++ ) { Shot( time, valvePulseLength, delayToQ, flashToQ, delayToPump, pumpPulseLength, delayToDetection ); time += shotEvery; } return time; } public int Shot( int startTime, int valvePulseLength, int delayToQ, int flashToQ, int delayToPump, int pumpPulseLength, int delayToDetection) { int time = 0; int tempTime = 0; // valve pulse // tempTime = Pulse(startTime, 0, valvePulseLength, valveChan); for (int z = 0 ; z < 32 ; z++) tempTime = Pulse(startTime, delayToDetection + delayToQ, valvePulseLength, z); if (tempTime > time) time = tempTime; // Flash pulse // tempTime = Pulse(startTime, delayToQ - flashToQ, 20, flashChan); if (tempTime > time) time = tempTime; // Q pulse // tempTime = Pulse(startTime, delayToQ, 20, qChan); if (tempTime > time) time = tempTime; // Pump beam trigger // tempTime = Pulse(startTime, delayToPump + delayToQ, pumpPulseLength, pumpChan); if (tempTime > time) time = tempTime; // Detector trigger // tempTime = Pulse(startTime, delayToDetection + delayToQ, 20, detectorTrigChan); if (tempTime > time) time = tempTime; return time; } } }
using UnityEngine; [RequireComponent(typeof(ParticleSystem))] public class ParticleCleanup : MonoBehaviour { private void Start() { Destroy(gameObject, GetComponent<ParticleSystem>().main.duration); } }
using System; using System.Runtime.InteropServices; namespace DIA { /// <summary> /// Helper interface that can be instantiated using coclass. /// </summary> [ComImport, CoClass(typeof(DiaStackWalkerClass)), Guid("5485216B-A54C-469F-9670-52B24D5229BB")] public interface DiaStackWalker : IDiaStackWalker { } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using AuthorizationWorkshop.Repositories; namespace AuthorizationWorkshop { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath); builder.AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddAuthorization(options => { options.AddPolicy(PolicyNames.AdministratorsOnly, policy => policy.RequireRole("Administrator")); options.AddPolicy(PolicyNames.CanEditAlbum, policy => { policy.RequireAuthenticatedUser(); policy.RequireRole("Administrator"); policy.Requirements.Add(new AlbumOwnerRequirement()); } ); }); services.AddMvc(); services.AddSingleton<IUserRepository, UserRepository>(); services.AddSingleton<IAlbumRepository, AlbumRepository>(); services.AddSingleton<IAuthorizationHandler, AlbumOwnerAuthorizationHandler>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = Constants.MiddlewareScheme, LoginPath = new PathString("/Account/Login/"), AccessDeniedPath = new PathString("/Account/Forbidden/"), AutomaticAuthenticate = true, AutomaticChallenge = true }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChanceNET { public struct USState { public readonly string Abbreviation; public readonly string StateName; public readonly string ZipCodes; public readonly string Capitol; public readonly string Bird; public readonly string Flower; public readonly int Population; public readonly string LargestCity; public readonly double Latitude; public readonly double Longitude; public readonly int SquareMiles; public readonly string AdmittedToUnion; public readonly string HighestPoint; public readonly string LowestPoint; public readonly string MedianAltitude; public readonly string AreaCodes; public readonly string Motto; public readonly string Magnify; public readonly string Nickname; public readonly string Facts; public readonly string Tree; public readonly string OriginOfName; internal USState(string abbreviation, string stateName, string zipCodes, string capitol, string bird, string flower, string population, string largestcity, string latitude, string longitude, string squaremiles, string admittedtounion, string highestpoint, string lowestpoint, string medianaltitude, string areacodes, string motto, string magnify, string nickname, string facts, string tree, string originofname ) { Abbreviation = abbreviation; StateName = stateName; ZipCodes = zipCodes; Capitol = capitol; Bird = bird; Flower = flower; Population = int.Parse(population); LargestCity = largestcity; Latitude = double.Parse(latitude); Longitude = double.Parse(longitude); SquareMiles = int.Parse(squaremiles); AdmittedToUnion = admittedtounion; HighestPoint = highestpoint; LowestPoint = lowestpoint; MedianAltitude = medianaltitude; AreaCodes = areacodes; Motto = motto; Magnify = magnify; Nickname = nickname; Facts = facts; Tree = tree; OriginOfName = originofname; } } }
//------------------------------------------------------------------------------ // <auto-generated> // 此代码已从模板生成。 // // 手动更改此文件可能导致应用程序出现意外的行为。 // 如果重新生成代码,将覆盖对此文件的手动更改。 // </auto-generated> //------------------------------------------------------------------------------ namespace LimeManage.Models { using System; using System.Collections.Generic; public partial class Project { public Project() { this.Invoice = new HashSet<Invoice>(); this.Cost = new HashSet<Cost>(); } public int ID { get; set; } public string Name { get; set; } public int CountyID { get; set; } public string PartyAName { get; set; } public int PartyBID { get; set; } public string ResponsiblePerson { get; set; } public string ContactPhone { get; set; } public System.DateTime Date { get; set; } public int Money { get; set; } public virtual County County { get; set; } public virtual PartyB PartyB { get; set; } public virtual ICollection<Invoice> Invoice { get; set; } public virtual ICollection<Cost> Cost { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Revit.EntityMapper; namespace Sample { public static class MapperInstance { private readonly static IMapper<Task> mapper = Mapper.CreateAdHoc<Task>(); public static IMapper<Task> Get() => mapper; } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class KnowledgeCompare : KnowledgeDecorator { string key; object value; /// <summary> /// Compares a custom knowledge value and a defined value. /// Succeeds if values are identical, otherwise fails. /// </summary> /// <param name="_klg">Knowledge reference.</param> /// <param name="_key">Key/name of the custom knowledge to compare.</param> /// <param name="_value">Defined value to compare.</param> /// <param name="_isNot">Fails if values are identical, otherwise succeeds.</param> public KnowledgeCompare(Knowledge _klg, string _key, object _value, bool _isNot = false) : base(_klg, _isNot) { value = _value; key = _key; } public override NodeState Tick() { Knowledge knowledge = (Knowledge)agentKnowledge; // Check if knowledge can && does contain custom knowledge && check if the values have the same type and value if (knowledge.HasKnowledge(key) && value != null && knowledge.GetKnowledge(key) == value) { if (isNot) { return NodeState.Failure; } return child.Tick(); } else { if (isNot) { return child.Tick(); } return NodeState.Failure; } } }
using System; using System.Runtime.InteropServices; using TitaniumAS.Opc.Client.Common; namespace TitaniumAS.Opc.Client.Interop.Da { [ComConversionLoss] [StructLayout(LayoutKind.Sequential, Pack = 4)] internal struct OPCITEMPROPERTIES { public HRESULT hrErrorID; public int dwNumProperties; [ComConversionLoss] public IntPtr pItemProperties; public int dwReserved; } }
using Leopotam.Ecs; namespace Ingame.Hud { public sealed class PlayerHudInitSystem : IEcsInitSystem { private readonly EcsFilter<HudModel> _hudFilter; public void Init() { foreach (var i in _hudFilter) { ref var hudEntity = ref _hudFilter.GetEntity(i); } } } }
using System.ComponentModel.DataAnnotations; using PaySharp.Core; namespace PaySharp.Unionpay.Domain { public class AppPayModel : BasePayModel { /// <summary> /// 订单描述 /// </summary> [ReName(Name = "orderDesc")] [StringLength(32, ErrorMessage = "订单描述最大长度为32位")] public string Body { get; set; } /// <summary> /// 支付卡类型 /// </summary> public string PayCardType { get; set; } /// <summary> /// 签约协议号 /// </summary> public string ContractId { get => _contractId; set { _contractId = value; if (!string.IsNullOrEmpty(_contractId)) { TxnSubType = "10"; } } } private string _contractId; } }
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Gcp.OsConfig.Outputs { [OutputType] public sealed class PatchDeploymentPatchConfigYum { /// <summary> /// List of KBs to exclude from update. /// </summary> public readonly ImmutableArray<string> Excludes; /// <summary> /// An exclusive list of packages to be updated. These are the only packages that will be updated. /// If these packages are not installed, they will be ignored. This field cannot be specified with /// any other patch configuration fields. /// </summary> public readonly ImmutableArray<string> ExclusivePackages; /// <summary> /// Will cause patch to run yum update-minimal instead. /// </summary> public readonly bool? Minimal; /// <summary> /// Adds the --security flag to yum update. Not supported on all platforms. /// </summary> public readonly bool? Security; [OutputConstructor] private PatchDeploymentPatchConfigYum( ImmutableArray<string> excludes, ImmutableArray<string> exclusivePackages, bool? minimal, bool? security) { Excludes = excludes; ExclusivePackages = exclusivePackages; Minimal = minimal; Security = security; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LeetCode.Challenge.Y21 { /// <summary> /// https://leetcode.com/explore/challenge/card/may-leetcoding-challenge-2021/600/week-3-may-15th-may-21st/3745/ /// /// </summary> internal class May16 { /** * Definition for a binary tree node.*/ public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) { this.val = val; this.left = left; this.right = right; } } public class Solution { enum Kind { Camera, Covered, Uncovered } public int MinCameraCover(TreeNode root) { var dp = new Dictionary<TreeNode, Dictionary<Kind, int>>(); Traverse(dp, root, root); var ans = dp[root].Where(_ => _.Key != Kind.Uncovered).Min(c => c.Value); return ans; } private Dictionary<Kind, int> GetOptions(Dictionary<TreeNode, Dictionary<Kind, int>> dp, TreeNode node) { if (node == null) return new Dictionary<Kind, int>(); return dp[node]; } private void Traverse(Dictionary<TreeNode, Dictionary<Kind, int>> dp, TreeNode node, TreeNode root) { if (node == null) return; dp[node] = new Dictionary<Kind, int>(); Traverse(dp, node.left, root); Traverse(dp, node.right, root); var left = GetOptions(dp, node.left); var right = GetOptions(dp, node.right); // dp[node][Kind.Camera] = int.MaxValue; dp[node][Kind.Covered] = int.MaxValue; dp[node][Kind.Uncovered] = int.MaxValue; if (left.Count == 0 && right.Count == 0) { dp[node][Kind.Camera] = 1; dp[node][Kind.Uncovered] = 0; } if (left.Count > 0 && right.Count == 0) { foreach (var item in left) { dp[node][Kind.Camera] = Math.Min(dp[node][Kind.Camera], item.Value + 1); if (item.Key == Kind.Camera) dp[node][Kind.Covered] = Math.Min(dp[node][Kind.Covered], item.Value); else if (item.Key == Kind.Covered) dp[node][Kind.Uncovered] = Math.Min(dp[node][Kind.Uncovered], item.Value); } } if (left.Count == 0 && right.Count > 0) { foreach (var item in right) { dp[node][Kind.Camera] = Math.Min(dp[node][Kind.Camera], item.Value + 1); if (item.Key == Kind.Camera) dp[node][Kind.Covered] = Math.Min(dp[node][Kind.Covered], item.Value); else if (item.Key == Kind.Covered) dp[node][Kind.Uncovered] = Math.Min(dp[node][Kind.Uncovered], item.Value); } } if (left.Count > 0 && right.Count > 0) { foreach (var l in left) { foreach (var r in right) { dp[node][Kind.Camera] = Math.Min(dp[node][Kind.Camera], l.Value + r.Value + 1); if (l.Key == Kind.Camera && r.Key == Kind.Camera) dp[node][Kind.Covered] = Math.Min(dp[node][Kind.Covered], l.Value + r.Value); if (l.Key == Kind.Camera && r.Key == Kind.Covered || l.Key == Kind.Covered && r.Key == Kind.Camera) dp[node][Kind.Covered] = Math.Min(dp[node][Kind.Covered], l.Value + r.Value); if (l.Key == Kind.Covered && r.Key == Kind.Covered) dp[node][Kind.Uncovered] = Math.Min(dp[node][Kind.Uncovered], l.Value + r.Value); } } } var remove = dp[node].Where(_ => _.Value == int.MaxValue).Select(x => x.Key).ToList(); foreach (var key in remove) dp[node].Remove(key); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class AudioManager : MonoBehaviour { public Audio[] sounds; public static AudioManager instance; private void Awake() { #region singleton DontDestroyOnLoad(gameObject); if(instance == null) { instance = this; } else { Destroy(gameObject); return; } #endregion // Inizializza la source dentro ciascun audio. // Non poteva essere creata direttamente dalla classe audio perchè è un componente che deve stare dentro // un gameobject, dunque la creo in AudioManager e poi la riferenzio dentro le classi Audio. // Poi da AudioManager cerco le classi audio e do play da li. foreach(Audio audio in sounds) { audio.SetSource(gameObject.AddComponent<AudioSource>()); audio.InitializeSource(); } } public void Play(string audioName) { Audio a = Array.Find(sounds, audio => audio.name == audioName); if (a.diversify) { a.GetSource().pitch = a.pitch + UnityEngine.Random.Range(-a.pitchDelta, a.pitchDelta); a.GetSource().Play(); a.GetSource().pitch = a.pitch; } else { a.GetSource().Play(); } } }
namespace VirtoCommerce.SearchModule.Web.Model { public class FilterProperty { public string Name { get; set; } public bool IsSelected { get; set; } } }
using System; using System.Collections.Generic; using Verse; using RimWorld; namespace TorannMagic { public class ItemCollectionGenerator_AncientTempleContents : ItemCollectionGenerator { private const float ArtifactsChance = 0.9f; private const float LuciferiumChance = 0.9f; private static readonly IntRange ArtifactsCountRange = new IntRange(1, 3); private static readonly IntRange LuciferiumCountRange = new IntRange(5, 20); private const float ArcaneScriptChance = 0.9f; private static readonly IntRange ArcaneScriptCountRange = new IntRange(1, 3); protected override void Generate(ItemCollectionGeneratorParams parms, List<Thing> outThings) { Messages.Message("TM item collection called", MessageSound.Benefit); if (Rand.Chance(0.9f)) { Thing thing = ThingMaker.MakeThing(ThingDefOf.Luciferium, null); thing.stackCount = LuciferiumCountRange.RandomInRange; outThings.Add(thing); } if (Rand.Chance(0.9f)) { int randomInRange = ArtifactsCountRange.RandomInRange; for (int i = 0; i < randomInRange; i++) { ThingDef def = ItemCollectionGenerator_Artifacts.artifacts.RandomElement<ThingDef>(); Thing item = ThingMaker.MakeThing(def, null); outThings.Add(item); } } if (Rand.Chance(0.9f)) { Messages.Message("random create called", MessageSound.Benefit); int randomInRange = ArcaneScriptCountRange.RandomInRange; for (int i = 0; i < randomInRange; i++) { Thing thing = ThingMaker.MakeThing(TorannMagicDefOf.BookOfInnerFire, null); outThings.Add(thing); Messages.Message("Book of fire should be created", MessageSound.Benefit); } } } } }
using System; using System.ComponentModel.DataAnnotations; namespace Backend.Dtos { public class AddToCartRequest { [Required] public int? ProductId { get; set; } [Required] [Range(1, Int32.MaxValue, ErrorMessage = "{0} must be greater than {1}.")] public int? Quantity { get; set; } } }
namespace Microsoft.AspNetCore.Razor.Hosting { using System; [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] public sealed class RazorCompiledItemAttribute : Attribute { public RazorCompiledItemAttribute(Type type, string kind, string identifier) { if (type == null) throw new ArgumentNullException(nameof(type)); if (kind == null) throw new ArgumentNullException(nameof(kind)); Type = type; Kind = kind; Identifier = identifier; } public string Kind { get; } public string Identifier { get; } public Type Type { get; } } }
using System.Collections.Generic; using RemoteConnectionCore.EyeTracking.Domain; using RemoteConnectionCore.EyeTracking.Presentation.Model; using UniRx; using UnityEngine; using Zenject; namespace RemoteConnectionCore.EyeTracking.Presentation.Presenter { public class EyeDataReceivePresenter : MonoBehaviour { [SerializeField] SkinnedMeshRenderer meshRenderer; [SerializeField] Transform rightEyeBone; [SerializeField] SetTransform rightEyeBoneTransform; [SerializeField] Transform leftEyeBone; [SerializeField] SetTransform leftEyeBoneTransform; [SerializeField] float intensity = 1f; [SerializeField] string rightEyeOpenessMorphName; [SerializeField] string leftEyeOpenessMorphName; Dictionary<string, int> morphIndexDic = new Dictionary<string, int>(); Vector3 rightInitRotation; Vector3 leftInitRotation; private Subject<EyeData> eyeDataSubject = new Subject<EyeData>(); [Inject] public void Init(EyeDataReceiveModel eyeDataReceiveModel) { morphIndexDic.Add("rightEyeOpenessMorphName", meshRenderer.sharedMesh.GetBlendShapeIndex(rightEyeOpenessMorphName)); morphIndexDic.Add("leftEyeOpenessMorphName", meshRenderer.sharedMesh.GetBlendShapeIndex(leftEyeOpenessMorphName)); rightInitRotation = rightEyeBone.localRotation.eulerAngles; leftInitRotation = leftEyeBone.localRotation.eulerAngles; eyeDataReceiveModel.Register(eyeDataSubject); eyeDataSubject.Subscribe(receivedData => { rightEyeBone.localRotation = Quaternion.Euler(rightInitRotation + rightEyeBoneTransform.translateTransform( new Vector3(receivedData.RightEyeRotationY * intensity, receivedData.RightEyeRotationX * intensity, 0))); leftEyeBone.localRotation = Quaternion.Euler(leftInitRotation + leftEyeBoneTransform.translateTransform( new Vector3(receivedData.RightEyeRotationY * intensity, receivedData.RightEyeRotationX * intensity, 0))); meshRenderer.SetBlendShapeWeight(morphIndexDic["rightEyeOpenessMorphName"], 100 - (100 * receivedData.RightEyeOpeness)); meshRenderer.SetBlendShapeWeight(morphIndexDic["leftEyeOpenessMorphName"], 100 - (100 * receivedData.RightEyeOpeness)); }); } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace MultiTenantWebApp.Models { public class AppDbContext : DbContext { // todo: 初期化用SQL // プログラムで書けるといいけど /* drop table if exists dbo.Blog; create table dbo.Blog( Id int, TenantId int not null, Title nvarchar(20) not null, Content nvarchar(max) not null, constraint PK_Blog primary key(Id) ); insert into dbo.Blog(Id, TenantId, Title, Content) output inserted.* values (1, 1, N'ブログはじめました', N''), (2, 2, N'冷やし中華はじめました', N''); */ private static readonly string _connectionString = new SqlConnectionStringBuilder { DataSource = ".", InitialCatalog = "Test", IntegratedSecurity = true, }.ToString(); private readonly ITenantIdProvider _tenantIdProvider; public AppDbContext(ITenantIdProvider tenantIdProvider) { _tenantIdProvider = tenantIdProvider; } protected int TenantId => _tenantIdProvider.GetTenantId(); public DbSet<Blog> Blogs { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder // インメモリDBだとフィルタが効かないのかも //.UseInMemoryDatabase(nameof(AppDbContext)) .UseSqlServer(_connectionString) .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Blog>() .ToTable(nameof(Blog)) // テナントIDによるフィルタ .HasQueryFilter(blog => blog.TenantId == TenantId); } } }
using MediatR; using SmartHub.Application.Common.Models; namespace SmartHub.Application.UseCases.InitCheck.CheckUsers { public class CheckUsersQuery: IRequest<Response<bool>> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; using Discord; using Discord.WebSocket; using LadyOfSpooky.Helpers; using static LadyOfSpooky.Models.Enums; namespace LadyOfSpooky.Models { public class Player : BaseFighter { public decimal DiscordUserId { get; set; } public Classes ChosenClass { get; set; } = Classes.Civil; public Player() { UpdateClassValues(); } public void UpdateClassValues() { switch (ChosenClass) { case Classes.Wizard: Attack = 12 + Level; Defense = 5 + Level; Health = 8 + (2 * Level); HitProbability = 60; break; case Classes.Tank: Attack = 5 + Level; Defense = 12 + Level; Health = 12 + (2 * Level); HitProbability = 90; break; case Classes.Fighter: Attack = 8 + Level; Defense = 8 + Level; Health = 10 + (2 * Level); HitProbability = 85; break; case Classes.Civil: break; default: break; } } public int GetAwardedXp(int expAmount) { int newPlayerExp = Exp + expAmount; int xpForCurrentLevel = LevelHelper.XpToLevelUp(Level - 1); // don't subtract xp if its at the lowest amount of the current level if (newPlayerExp <= xpForCurrentLevel) { newPlayerExp = xpForCurrentLevel; } int awardedXp = newPlayerExp - Exp; Exp = newPlayerExp; LevelHelper.CheckCurrentXP(this); UpdateClassValues(); return awardedXp; } } }
namespace TinyBee { using System.IO; public static class TFile : object { //儲存檔案 public static void Save(string path, byte[] data, int xor = 0) { string zPath = Path.GetDirectoryName(path); //檢查目錄是否存在 if (!Directory.Exists(zPath)) Directory.CreateDirectory(zPath); //檢查舊檔案 if (File.Exists(path)) File.Delete(path); //檢查是否需要編碼 if (xor != 0) data = XOR(data, xor); //建立檔案 using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write)) { try { //調整起始寫入位置 fileStream.Seek(0, SeekOrigin.Begin); //寫入檔案 fileStream.Write(data, 0, data.Length); } finally { fileStream.Close(); } } } //儲存檔案 public static void Save(string path, string fileName, byte[] data, int xor = 0) { //檢查目錄是否存在 if (!Directory.Exists(path)) Directory.CreateDirectory(path); //檢查舊檔案 if (File.Exists(path + fileName)) File.Delete(path + fileName); //檢查是否需要編碼 if (xor != 0) data = XOR(data, xor); //建立檔案 using (FileStream fileStream = new FileStream(path + fileName, FileMode.Create, FileAccess.Write)) { try { //調整起始寫入位置 fileStream.Seek(0, SeekOrigin.Begin); //寫入檔案 fileStream.Write(data, 0, data.Length); } finally { fileStream.Close(); } } } //讀入檔案 public static byte[] Load(string path, int xor = 0, bool isDel = false) { string zPath = Path.GetDirectoryName(path); //檢查目錄是否存在 if (!Directory.Exists(zPath)) return null; //檢查舊檔案 if (!File.Exists(path)) return null; byte[] data = null; //建立檔案 using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read)) { try { //調整起始寫入位置 fileStream.Seek(0, SeekOrigin.Begin); //建立資料空間 data = new byte[fileStream.Length]; //取得資料長度 int length = (int)fileStream.Length; //讀出資料 fileStream.Read(data, 0, length); //檢查是否需要解碼 if (xor != 0) data = XOR(data, xor); } finally { fileStream.Close(); } } if (isDel) File.Delete(path); return data; } //讀入檔案 public static byte[] Load(string path, string fileName, int xor = 0, bool isDel = false) { //檢查目錄是否存在 if (!Directory.Exists(path)) return null; //檢查舊檔案 if (!File.Exists(path + fileName)) return null; byte[] data = null; //建立檔案 using (FileStream fileStream = new FileStream(path + fileName, FileMode.Open, FileAccess.Read)) { try { //調整起始寫入位置 fileStream.Seek(0, SeekOrigin.Begin); //建立資料空間 data = new byte[fileStream.Length]; //取得資料長度 int length = (int)fileStream.Length; //讀出資料 fileStream.Read(data, 0, length); //檢查是否需要解碼 if (xor != 0) data = XOR(data, xor); } finally { fileStream.Close(); } } if (isDel == true) File.Delete(path + fileName); return data; } //XOR public static byte[] XOR (byte[] data) { return XOR(data, 0); } //XOR public static byte[] XOR (byte[] data, int key) { if (data == null) return null; if (key == 0) return data; byte[] keyArray = System.BitConverter.GetBytes(key); for (int i = 0; i < data.Length; i++) { for (int j = 0; j < keyArray.Length; j++) { data[i] = System.Convert.ToByte(data[i] ^ keyArray[j]); } } return data; } } }
using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using ProjectUntitled.Models; using ProjectUntitled.Models.ViewModels; namespace ProjectUntitled.Controllers { [Authorize] public class MessagesController : Controller { private readonly IMessageRepository messageRepository; private readonly UserManager<IdentityUser> userManager; public MessagesController(IMessageRepository messageRepo, UserManager<IdentityUser> usrMgr) { messageRepository = messageRepo; userManager = usrMgr; } public async Task<IActionResult> Index() { MessagesViewModel messagesViewModel = await GetMessages(); return View(messagesViewModel); } private async Task<MessagesViewModel> GetMessages() { var user = await userManager.GetUserAsync(HttpContext.User); var messages = messageRepository.GetMessages(user); var newMessage = new Message { SenderId = user.Id, SenderUserName = user.UserName }; var messageSource = new MessagesViewModel { Messages = Mapper.Map<IEnumerable<MessageViewModel>>(messages), NewMessage = Mapper.Map<Message, NewMessageViewModel>(newMessage) }; var messagesViewModel = Mapper.Map<MessagesViewModel>(messageSource); return messagesViewModel; } public async Task<IActionResult> GetMessage(int messageId) { var user = await userManager.GetUserAsync(HttpContext.User); var message = messageRepository.GetMessage(messageId, user.Id); return View(message); } public async Task<IActionResult> DeleteMessage(int messageId) { var user = await userManager.GetUserAsync(HttpContext.User); messageRepository.ChangeMessageStatus(messageId, user.Id, MessageStatus.Deleted); TempData["message"] = "Message deleted!"; return RedirectToAction("Index"); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SendMessage([FromForm]NewMessageViewModel newMessage) { if(ModelState.IsValid) { var user = await userManager.FindByNameAsync(newMessage.RecipentUserName); if (user != null) { var allowsMessages = messageRepository.AllowMessages(user.Id); if (allowsMessages) { var sender = await userManager.GetUserAsync(HttpContext.User); newMessage.RecipentId = user.Id; newMessage.SenderId = sender.Id; newMessage.SenderUserName = sender.UserName; var message = Mapper.Map<Message>(newMessage); var Succeeded = await messageRepository.SendMessage(message); if (Succeeded) { TempData["message"] = "Your message has been sent!"; return Redirect("Index"); } } } } MessagesViewModel messagesViewModel = await GetMessages(); messagesViewModel.NewMessage = newMessage; ModelState.AddModelError("", "Error: Could not send your message!"); return View("Index", messagesViewModel); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ReplyMessage([FromForm]GetMessageViewModel replyMessage) { if(ModelState.IsValid) { var sender = await userManager.GetUserAsync(HttpContext.User); var Succeeded = await messageRepository.ReplyMessage(replyMessage, sender); if (Succeeded) { TempData["message"] = "Your message has been sent!"; return Redirect("Index"); } } ModelState.AddModelError("", "Error: Could not send your message!"); return View("GetMessage", replyMessage); } } }
using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using AutoMapper; using FluentValidation; using MediatR; using U.ProductService.Application.Common.Exceptions; using U.ProductService.Application.Pictures.Models; using U.ProductService.Domain.Common; using U.ProductService.Persistance.Repositories.Picture; namespace U.ProductService.Application.Pictures.Commands.Update { [SuppressMessage("ReSharper", "UnusedMember.Global")] public class UpdatePictureCommandHandler : IRequestHandler<UpdatePictureCommand, PictureViewModel> { private readonly IPictureRepository _pictureRepository; private readonly IMapper _mapper; private readonly IMediator _mediator; private readonly IDomainEventsService _domainEventsService; public UpdatePictureCommandHandler(IPictureRepository productRepository, IMapper mapper, IMediator mediator, IDomainEventsService domainEventsService) { _pictureRepository = productRepository; _mapper = mapper; _mediator = mediator; _domainEventsService = domainEventsService; } public async Task<PictureViewModel> Handle(UpdatePictureCommand command, CancellationToken cancellationToken) { var validator = new UpdatePictureCommand.Validator(); await validator.ValidateAndThrowAsync(command, cancellationToken: cancellationToken); var picture = await _pictureRepository.GetAsync(command.PictureId); if (picture is null) { throw new PictureNotFoundException($"Picture with id: '{command.PictureId}' has not been found"); } picture.Update(command.FileStorageUploadId, command.Filename, command.Description, command.Url, command.MimeTypeId); _pictureRepository.Update(picture); await _pictureRepository.UnitOfWork.SaveEntitiesAsync(_domainEventsService, _mediator, cancellationToken); return _mapper.Map<PictureViewModel>(picture); } } }
namespace Booking.Web.ViewModels.Bookings { using System; using System.Collections.Generic; using System.Text; public class BookingInListViewModel { public string Id { get; set; } public string PropertyName { get; set; } public decimal Price { get; set; } public string CurrencyCode { get; set; } public int Members { get; set; } public string Country { get; set; } public string Town { get; set; } public string Address { get; set; } public string CheckIn { get; set; } public string CheckOut { get; set; } } }
using System.Web.Mvc; using System.Web.Mvc.Html; namespace Tarantino.RulesEngine.Mvc { public static class HtmlExtensions { public static string OriginalForm(this HtmlHelper helper) { return OriginalForm(helper, helper.ViewData.Model); } public static string OriginalForm(this HtmlHelper helper, object originalFormInstance) { string formContent = helper.ViewContext.HttpContext.Request.Params[OriginalFormRetriever.ORIGINAL_FORM_KEY] ?? new Serializer(new Base64Utility()).Serialize(originalFormInstance); return helper.Hidden(OriginalFormRetriever.ORIGINAL_FORM_KEY, formContent); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using GOEddie.Dacpac.References; using Microsoft.SqlServer.Dac; using Microsoft.SqlServer.Dac.Extensions; using Microsoft.SqlServer.Dac.Model; namespace Dir2Dac { public class Program { public static int Main(params string[] args) { var argParser = new Args(args); if (argParser.Parse() != ParseResult.Ok) { Args.PrintArgs(); return -1; } var creator = new DacCreator(argParser); if (!creator.Write()) { return -2; } return 0; } private static void ShowHelp() { } } }
using System; using System.Net.Http; using System.Threading.Tasks; namespace Playground.NET5 { public class DownloadSomething { public async Task DownloadFile(string fileName, string fileUrl) { using var http = new HttpClient(); var file = await http.GetByteArrayAsync(fileUrl); await System.IO.File.WriteAllBytesAsync($"C:\\temp\\{fileName}", file); } public async Task Run() { Console.Write("Get FileName: "); var fileName = Console.ReadLine(); Console.Write("Get Url: "); var url = Console.ReadLine(); try { await new DownloadSomething().DownloadFile(fileName, url); Console.WriteLine($"C:\\temp\\{fileName}"); } catch (Exception ex) { await Console.Error.WriteLineAsync(ex.Message); await Console.Error.WriteLineAsync(ex.StackTrace); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using System.Numerics; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Input; using osu.Framework.Input.Events; using osu.Framework.Input.Handlers.Midi; using osu.Framework.Platform; namespace osu.Framework.Tests.Visual.Input { public class TestSceneMidi : FrameworkTestScene { public TestSceneMidi() { var keyFlow = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, }; for (MidiKey k = MidiKey.A0; k < MidiKey.C8; k++) keyFlow.Add(new MidiKeyHandler(k)); Child = keyFlow; } [Resolved] private GameHost host { get; set; } protected override void LoadComplete() { base.LoadComplete(); AddToggleStep("toggle midi handler", enabled => { var midiHandler = host.AvailableInputHandlers.OfType<MidiHandler>().FirstOrDefault(); if (midiHandler != null) midiHandler.Enabled.Value = enabled; }); } protected override bool OnMidiDown(MidiDownEvent e) { Console.WriteLine(e); return base.OnMidiDown(e); } protected override void OnMidiUp(MidiUpEvent e) { Console.WriteLine(e); base.OnMidiUp(e); } protected override bool Handle(UIEvent e) { if (!(e is MouseEvent)) Console.WriteLine("Event: " + e); return base.Handle(e); } private class MidiKeyHandler : CompositeDrawable { private readonly Drawable background; public override bool HandleNonPositionalInput => true; private readonly MidiKey key; public MidiKeyHandler(MidiKey key) { this.key = key; Size = new Vector2(50); InternalChildren = new[] { background = new Container { RelativeSizeAxes = Axes.Both, Colour = Colour4.DarkGreen, Alpha = 0, Child = new Box { RelativeSizeAxes = Axes.Both } }, new SpriteText { Anchor = Anchor.Centre, Origin = Anchor.Centre, Text = key.ToString().Replace("Sharp", "#") } }; } protected override bool OnMidiDown(MidiDownEvent e) { if (e.Key != key) return base.OnMidiDown(e); const float base_opacity = 0.25f; // to make a velocity of 1 not completely invisible background.FadeTo(base_opacity + e.Velocity / 128f * (1 - base_opacity), 100, Easing.OutQuint); return true; } protected override void OnMidiUp(MidiUpEvent e) { if (e.Key != key) base.OnMidiUp(e); else background.FadeOut(100); } } } }
namespace OffByOne.Ql.Checker.Analyzers.CircularDependencies { using System; using MoreDotNet.Extensions.Common; public class Dependency { public Dependency(string startPointId, string endPointId) { if (startPointId == null) { throw new ArgumentNullException(nameof(startPointId)); } if (startPointId == null) { throw new ArgumentNullException(nameof(endPointId)); } this.StartPointId = startPointId; this.EndPointId = endPointId; } public string StartPointId { get; } public string EndPointId { get; } public override int GetHashCode() { var partialHas = this.StartPointId?.GetHashCode() ?? 0; return partialHas + this.EndPointId?.GetHashCode() ?? 0; } public override bool Equals(object obj) { if (obj.IsNot<Dependency>()) { return false; } var dependency = obj.As<Dependency>(); bool inEqualityCondition; if (this.StartPointId != null) { inEqualityCondition = this.StartPointId != dependency.StartPointId; } else { inEqualityCondition = dependency.StartPointId != null; } if (inEqualityCondition) { return false; } return this.EndPointId != null ? this.EndPointId == dependency.EndPointId : dependency.EndPointId == null; } public override string ToString() { return $"[{this.StartPointId},{this.EndPointId}]"; } public bool IsTransitiveTo(Dependency supposedPair) { if (supposedPair == null) { throw new ArgumentNullException(nameof(supposedPair)); } return this.EndPointId == supposedPair.StartPointId; } public bool IsReflexive() { return this.StartPointId == this.EndPointId; } } }
using System; namespace WebApplication.EFCore { public class WeatherForecast { public DateTime TimeStamp { get; set; } public decimal TemperatureC { get; set; } public decimal TemperatureF => 32 + (TemperatureC / 0.5556m); public string Summary { get; set; } } }
using System; namespace Linquest.AspNetCore { public class NonLinquestActionAttribute: Attribute { } }
using System.Net.Http; using System.Text; namespace Coder.WebPusherService.Senders.HttpSender.HttpNotify { internal class HttpRawBodyContent : HttpSendContent { public string Content { get; set; } public override HttpContent MakeContent(string contentType) { return new StringContent(Content, Encoding.UTF8, contentType ?? "application/json"); } public override string MakeQueryString() { return Content; } } }
using System; using System.Collections.Generic; using System.Text; using Generator.Parsing; namespace Generator.CodeTranslation { /// <summary> /// A class for translating source code from one language/format to another. /// </summary> public static class CodeTranslator { /// <summary> /// Translates the specified source code from one language/format to another. /// </summary> /// <param name="sourceCode">The source code to translate.</param> /// <param name="parser">The <see cref="ICodeParser"/> to parse the source code with.</param> /// <param name="generator">The <see cref="ICodeGenerator"/> to generate the new source code with.</param> public static string Translate(string sourceCode, ICodeParser parser, ICodeGenerator generator) { return Translate(new string[] { sourceCode }, parser, generator); } /// <summary> /// Translates the specified source code from one language/format to another. /// </summary> /// <param name="sourceCode">The array of source code strings to translate.</param> /// <param name="parser">The <see cref="ICodeParser"/> to parse the source code with.</param> /// <param name="generator">The <see cref="ICodeGenerator"/> to generate the source code with.</param> public static string Translate(string[] sourceCode, ICodeParser parser, ICodeGenerator generator) { if(sourceCode == null) throw new ArgumentNullException(nameof(sourceCode)); if(parser == null) throw new ArgumentNullException(nameof(parser)); if(generator == null) throw new ArgumentNullException(nameof(generator)); List<FunctionDefinition> functionList = new List<FunctionDefinition>(); List<EnumDefinition> enumList = new List<EnumDefinition>(); List<StructDefinition> structList = new List<StructDefinition>(); int i = 0; int c = 0; string snippet; StringBuilder builder = new StringBuilder(); foreach(string code in sourceCode) { var functions = parser.ParseFunctions(code); functionList.AddRange(functions); var structs = parser.ParseStructs(code); structList.AddRange(structs); var enums = parser.ParseEnums(code); enumList.AddRange(enums); } // Start of file // ------------------------------------------------------------------ snippet = generator.GenerateStart(); if(!string.IsNullOrEmpty(snippet)) builder.Append(snippet); // Structs // ------------------------------------------------------------------ i = 0; c = structList.Count; foreach(var @struct in structList) { snippet = generator.GenerateStruct(@struct, i, c); if(!string.IsNullOrEmpty(snippet)) builder.Append(snippet); i++; } // Enums // ------------------------------------------------------------------ i = 0; c = enumList.Count; foreach(var @enum in enumList) { snippet = generator.GenerateEnum(@enum, i, c); if(!string.IsNullOrEmpty(snippet)) builder.Append(snippet); i++; } // Functions // ------------------------------------------------------------------ i = 0; c = functionList.Count; foreach(var function in functionList) { snippet = generator.GenerateFunction(function, i, c); if(!string.IsNullOrEmpty(snippet)) builder.Append(snippet); i++; } // End of file // ------------------------------------------------------------------ snippet = generator.GenerateEnd(); if(!string.IsNullOrEmpty(snippet)) builder.Append(snippet); return builder.ToString(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] // Flat shadow that orient around Y according to the camera rotation. public class BillboardShadows : MonoBehaviour { void Update() { var camera = Camera.main; if (camera == null) return; var forward = camera.transform.rotation * Vector3.forward; forward.y = 0; transform.LookAt(transform.position + Vector3.down, forward); } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.ProjectMan.V4.Model { /// <summary> /// Response Object /// </summary> public class ShowIterationV4Response : SdkResponse { /// <summary> /// 迭代结束时间,年-月-日 /// </summary> [JsonProperty("begin_time", NullValueHandling = NullValueHandling.Ignore)] public string BeginTime { get; set; } /// <summary> /// 燃尽图 /// </summary> [JsonProperty("charts", NullValueHandling = NullValueHandling.Ignore)] public List<Chart> Charts { get; set; } /// <summary> /// 已关闭的工单数 /// </summary> [JsonProperty("closed_total", NullValueHandling = NullValueHandling.Ignore)] public int? ClosedTotal { get; set; } /// <summary> /// 迭代创建时间 /// </summary> [JsonProperty("created_time", NullValueHandling = NullValueHandling.Ignore)] public string CreatedTime { get; set; } /// <summary> /// 迭代开始时间,年-月-日 /// </summary> [JsonProperty("end_time", NullValueHandling = NullValueHandling.Ignore)] public string EndTime { get; set; } /// <summary> /// 是否有task /// </summary> [JsonProperty("have_task", NullValueHandling = NullValueHandling.Ignore)] public bool? HaveTask { get; set; } /// <summary> /// 迭代id /// </summary> [JsonProperty("iteration_id", NullValueHandling = NullValueHandling.Ignore)] public int? IterationId { get; set; } /// <summary> /// 迭代标题 /// </summary> [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] public string Name { get; set; } /// <summary> /// 开启的工单数 /// </summary> [JsonProperty("opened_total", NullValueHandling = NullValueHandling.Ignore)] public int? OpenedTotal { get; set; } /// <summary> /// 工作进展 /// </summary> [JsonProperty("progress", NullValueHandling = NullValueHandling.Ignore)] public string Progress { get; set; } /// <summary> /// 工单总数 /// </summary> [JsonProperty("total", NullValueHandling = NullValueHandling.Ignore)] public int? Total { get; set; } /// <summary> /// 迭代更新时间 /// </summary> [JsonProperty("updated_time", NullValueHandling = NullValueHandling.Ignore)] public string UpdatedTime { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ShowIterationV4Response {\n"); sb.Append(" beginTime: ").Append(BeginTime).Append("\n"); sb.Append(" charts: ").Append(Charts).Append("\n"); sb.Append(" closedTotal: ").Append(ClosedTotal).Append("\n"); sb.Append(" createdTime: ").Append(CreatedTime).Append("\n"); sb.Append(" endTime: ").Append(EndTime).Append("\n"); sb.Append(" haveTask: ").Append(HaveTask).Append("\n"); sb.Append(" iterationId: ").Append(IterationId).Append("\n"); sb.Append(" name: ").Append(Name).Append("\n"); sb.Append(" openedTotal: ").Append(OpenedTotal).Append("\n"); sb.Append(" progress: ").Append(Progress).Append("\n"); sb.Append(" total: ").Append(Total).Append("\n"); sb.Append(" updatedTime: ").Append(UpdatedTime).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as ShowIterationV4Response); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(ShowIterationV4Response input) { if (input == null) return false; return ( this.BeginTime == input.BeginTime || (this.BeginTime != null && this.BeginTime.Equals(input.BeginTime)) ) && ( this.Charts == input.Charts || this.Charts != null && input.Charts != null && this.Charts.SequenceEqual(input.Charts) ) && ( this.ClosedTotal == input.ClosedTotal || (this.ClosedTotal != null && this.ClosedTotal.Equals(input.ClosedTotal)) ) && ( this.CreatedTime == input.CreatedTime || (this.CreatedTime != null && this.CreatedTime.Equals(input.CreatedTime)) ) && ( this.EndTime == input.EndTime || (this.EndTime != null && this.EndTime.Equals(input.EndTime)) ) && ( this.HaveTask == input.HaveTask || (this.HaveTask != null && this.HaveTask.Equals(input.HaveTask)) ) && ( this.IterationId == input.IterationId || (this.IterationId != null && this.IterationId.Equals(input.IterationId)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.OpenedTotal == input.OpenedTotal || (this.OpenedTotal != null && this.OpenedTotal.Equals(input.OpenedTotal)) ) && ( this.Progress == input.Progress || (this.Progress != null && this.Progress.Equals(input.Progress)) ) && ( this.Total == input.Total || (this.Total != null && this.Total.Equals(input.Total)) ) && ( this.UpdatedTime == input.UpdatedTime || (this.UpdatedTime != null && this.UpdatedTime.Equals(input.UpdatedTime)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.BeginTime != null) hashCode = hashCode * 59 + this.BeginTime.GetHashCode(); if (this.Charts != null) hashCode = hashCode * 59 + this.Charts.GetHashCode(); if (this.ClosedTotal != null) hashCode = hashCode * 59 + this.ClosedTotal.GetHashCode(); if (this.CreatedTime != null) hashCode = hashCode * 59 + this.CreatedTime.GetHashCode(); if (this.EndTime != null) hashCode = hashCode * 59 + this.EndTime.GetHashCode(); if (this.HaveTask != null) hashCode = hashCode * 59 + this.HaveTask.GetHashCode(); if (this.IterationId != null) hashCode = hashCode * 59 + this.IterationId.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); if (this.OpenedTotal != null) hashCode = hashCode * 59 + this.OpenedTotal.GetHashCode(); if (this.Progress != null) hashCode = hashCode * 59 + this.Progress.GetHashCode(); if (this.Total != null) hashCode = hashCode * 59 + this.Total.GetHashCode(); if (this.UpdatedTime != null) hashCode = hashCode * 59 + this.UpdatedTime.GetHashCode(); return hashCode; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Xamarin.Forms.Core.UnitTests { [TestFixture] public class DragGestureRecognizerTests : BaseTestFixture { [SetUp] public override void Setup() { base.Setup(); Device.PlatformServices = new MockPlatformServices(); Device.SetFlags(new[] { ExperimentalFlags.DragAndDropExperimental }); } [TearDown] public override void TearDown() { base.TearDown(); Device.PlatformServices = null; } [Test] public void PropertySetters() { var dragRec = new DragGestureRecognizer(); Command cmd = new Command(() => { }); var parameter = new Object(); dragRec.CanDrag = true; dragRec.DragStartingCommand = cmd; dragRec.DragStartingCommandParameter = parameter; dragRec.DropCompletedCommand = cmd; dragRec.DropCompletedCommandParameter = parameter; Assert.AreEqual(true, dragRec.CanDrag); Assert.AreEqual(cmd, dragRec.DragStartingCommand); Assert.AreEqual(parameter, dragRec.DragStartingCommandParameter); Assert.AreEqual(cmd, dragRec.DropCompletedCommand); Assert.AreEqual(parameter, dragRec.DropCompletedCommandParameter); } [Test] public void DragStartingCommandFires() { var dragRec = new DragGestureRecognizer(); var parameter = new Object(); object commandExecuted = null; Command cmd = new Command(() => commandExecuted = parameter); dragRec.DragStartingCommand = cmd; dragRec.DragStartingCommandParameter = parameter; dragRec.SendDragStarting(new Label()); Assert.AreEqual(commandExecuted, parameter); } [Test] public void UserSpecifiedTextIsntOverwritten() { var dragRec = new DragGestureRecognizer(); var element = new Label() { Text = "WRONG TEXT" }; dragRec.DragStarting += (_, args) => { args.Data.Text = "Right Text"; }; var returnedArgs = dragRec.SendDragStarting(element); Assert.AreEqual("Right Text", returnedArgs.Data.Text); } [Test] public void UserSpecifiedImageIsntOverwritten() { var dragRec = new DragGestureRecognizer(); var element = new Image() { Source = "http://www.someimage.com" }; FileImageSource fileImageSource = new FileImageSource() { File = "yay.jpg" }; dragRec.DragStarting += (_, args) => { args.Data.Image = fileImageSource; }; var returnedArgs = dragRec.SendDragStarting(element); Assert.AreEqual(fileImageSource, returnedArgs.Data.Image); } [Test] public void DropCompletedCommandFires() { var dragRec = new DragGestureRecognizer(); var parameter = new Object(); object commandExecuted = null; Command cmd = new Command(() => commandExecuted = parameter); dragRec.SendDragStarting(new Label()); dragRec.DropCompletedCommand = cmd; dragRec.DropCompletedCommandParameter = parameter; dragRec.SendDropCompleted(new DropCompletedEventArgs()); Assert.AreEqual(commandExecuted, parameter); } [Test] public void DropCompletedCommandFiresOnce() { int counter = 0; var dragRec = new DragGestureRecognizer(); Command cmd = new Command(() => counter++); dragRec.SendDragStarting(new Label()); dragRec.DropCompletedCommand = cmd; dragRec.SendDropCompleted(new DropCompletedEventArgs()); dragRec.SendDropCompleted(new DropCompletedEventArgs()); dragRec.SendDropCompleted(new DropCompletedEventArgs()); Assert.AreEqual(1, counter); } [TestCase(typeof(Entry), "EntryTest")] [TestCase(typeof(Label), "LabelTest")] [TestCase(typeof(Editor), "EditorTest")] [TestCase(typeof(TimePicker), "01:00:00")] [TestCase(typeof(DatePicker), "12/12/2020 12:00:00 AM")] [TestCase(typeof(CheckBox), "True")] [TestCase(typeof(Switch), "True")] [TestCase(typeof(RadioButton), "True")] public void TextPackageCorrectlyExtractedFromCompatibleElement(Type fieldType, string result) { var dragRec = new DragGestureRecognizer(); var element = (VisualElement)Activator.CreateInstance(fieldType); Assert.IsTrue(element.TrySetValue(result)); var args = dragRec.SendDragStarting(element); Assert.AreEqual(result, args.Data.Text); } [Test] public void HandledTest() { string testString = "test String"; var dragRec = new DragGestureRecognizer(); var element = new Label() { Text = testString }; element.Text = "Text Shouldn't change"; var args = new DragStartingEventArgs(); args.Handled = true; args.Data.Text = "Text Shouldn't change"; dragRec.SendDragStarting(element); Assert.AreNotEqual(args.Data.Text, testString); } } }
using UnityEngine; namespace blaseball.vo { [System.Serializable] public class BBPlayer { public string id; public string name; public float anticapitalism, baseThirst, buoyancy, chasiness, coldness, continuation, divinity, groundFriction, indulgence, laserlikeness, martyrdom, moxie, musclitude, omniscience, overpowerment, patheticism, ruthlessness, shakespearianism, suppression, tenaciousness, thwackability, tragicness, unthwackability, watchfulness, pressurization, cinnamon; public int totalFingers, soul, fate, coffee, blood; public bool deceased, peanutAllergy; public string bat, armor; /// <summary> /// Calculate a player's batter rating. /// A combination of inverse tragicness, inverse patheticism, thwackability /// divinity, moxie, musclitude and martyrdom /// /// Maths by Baron Bliss of SIBR /// </summary> /// <param name="player">Player</param> /// <returns>the raw batting rating, unmodified by items</returns> public static float BatterRating(BBPlayer player) { return Mathf.Pow(1 - player.tragicness, 0.01f) * Mathf.Pow(1 - player.patheticism, 0.05f) * Mathf.Pow(player.thwackability * player.divinity, 0.35f) * Mathf.Pow(player.moxie * player.musclitude, 0.075f) * Mathf.Pow(player.martyrdom, 0.02f); } /// <summary> /// Calculate a player's pitcher rating. /// /// A combination of unthwackability, ruthlessness, overpowerment, /// shakespearianism and coldness /// /// Maths by Baron Bliss of SIBR /// </summary> /// <param name="player">Player</param> /// <returns>the raw pitching rating, unmodified by items</returns> public static float PitcherRating(BBPlayer player) { return Mathf.Pow(player.unthwackability, 0.5f) * Mathf.Pow(player.ruthlessness, 0.4f) * Mathf.Pow(player.overpowerment, 0.15f) * Mathf.Pow(player.shakespearianism, 0.1f) * Mathf.Pow(player.coldness, 0.025f); } /// <summary> /// Calculate a player's defense rating. /// /// A combination of omniecence, tenaciousness, watchfullness, /// anticapitalism and chasiness /// /// Maths by Baron Bliss of SIBR /// </summary> /// <param name="player">Player</param> /// <returns>the raw defense rating, unmodified by items</returns> public static float DefenseRating(BBPlayer player) { return Mathf.Pow(player.omniscience * player.tenaciousness, 0.2f) * Mathf.Pow(player.watchfulness * player.anticapitalism * player.chasiness, 0.1f); } /// <summary> /// Calculate a player's baserunning rating. /// /// A combination of laserlikeness, baseThirst, continuation, /// groundFriction, and indulgence /// /// Maths by Baron Bliss of SIBR /// </summary> /// <param name="player">Player</param> /// <returns>the raw baserunning rating, unmodified by items</returns> public static float BaserunningRating(BBPlayer player) { return Mathf.Pow(player.laserlikeness, 0.5f) * Mathf.Pow(player.baseThirst * player.continuation * player.groundFriction * player.indulgence, 0.1f); } /// <summary> /// Calculate a player's vibes /// /// A combination of pressurization, cinnamon, the phase of the moon and buoyancy /// </summary> /// <param name="player">Player</param> /// <param name="day">The Day; use 1 indexed (database stores 0 index!)</param> /// <returns>The current vibes for the player</returns> /// <todo>Check that the cos function is correct; it'll be in radians here, check it's not degrees</todo> public static float Vibes(BBPlayer player, int day) { return 0.5f * Mathf.Round( (player.pressurization + player.cinnamon) * Mathf.Cos((Mathf.PI * day) / (5 * player.buoyancy + 3f)) - player.pressurization + player.cinnamon); } } }
using System; using System.Collections.Generic; using System.Text; namespace strategy { public interface QuackBehavior { public void Quack(); } public class QuackSound : QuackBehavior { public void Quack() { Console.WriteLine("Quack"); } } public class MuteQuack : QuackBehavior { public void Quack() { Console.WriteLine("<< Silence >>"); } } public class Squeak : QuackBehavior { public void Quack() { Console.WriteLine("Squeak"); } } }
namespace RealArtists.ShipHub.Api.Diagnostics { using System.Collections.Generic; using System.Web.Http.ExceptionHandling; using Filters; using Microsoft.ApplicationInsights; public class ApplicationInsightsExceptionLogger : ExceptionLogger { private TelemetryClient _client = new TelemetryClient(); public override void Log(ExceptionLoggerContext context) { IDictionary<string, string> properties = null; if (context.RequestContext.Principal is ShipHubPrincipal user) { properties = new Dictionary<string, string> { { "Login", user.Login }, { "UserId", user.UserId.ToString() }, { "DebugIdentifier", user.DebugIdentifier }, }; } _client.TrackException(context.Exception, properties); base.Log(context); } } }
using System.Threading.Tasks; using CommunityCatalog.Core.Domain; namespace CommunityCatalog.Core.Gateways.Transactions { public interface IProductUpdateTransaction { ValueTask UpdateProduct(ProductDocument product, ProductContribution productContribution, int baseProductVersion); } }
/* Copyright (C) 2008 Siarhei Novik (snovik@gmail.com) This file is part of QLNet Project https://github.com/amaggiulli/qlnet QLNet is free software: you can redistribute it and/or modify it under the terms of the QLNet license. You should have received a copy of the license along with this program; if not, license is available at <https://github.com/amaggiulli/QLNet/blob/develop/LICENSE>. QLNet is a based on QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ The QuantLib license is available online at http://quantlib.org/license.shtml. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ using System; namespace QLNet { public class GammaDistribution { private double a_; public GammaDistribution(double a) { a_ = a; Utils.QL_REQUIRE(a > 0.0, () => "invalid parameter for gamma distribution"); } public double value(double x) { if (x <= 0.0) return 0.0; double gln = GammaFunction.logValue(a_); if (x < (a_ + 1.0)) { double ap = a_; double del = 1.0 / a_; double sum = del; for (int n = 1; n <= 100; n++) { ap += 1.0; del *= x / ap; sum += del; if (Math.Abs(del) < Math.Abs(sum) * 3.0e-7) return sum * Math.Exp(-x + a_ * Math.Log(x) - gln); } } else { double b = x + 1.0 - a_; double c = double.MaxValue; double d = 1.0 / b; double h = d; for (int n = 1; n <= 100; n++) { double an = -1.0 * n * (n - a_); b += 2.0; d = an * d + b; if (Math.Abs(d) < Const.QL_EPSILON) d = Const.QL_EPSILON; c = b + an / c; if (Math.Abs(c) < Const.QL_EPSILON) c = Const.QL_EPSILON; d = 1.0 / d; double del = d * c; h *= del; if (Math.Abs(del - 1.0) < Const.QL_EPSILON) return h * Math.Exp(-x + a_ * Math.Log(x) - gln); } } Utils.QL_FAIL("too few iterations"); return 0; } } //! Gamma function class /*! This is a function defined by \f[ \Gamma(z) = \int_0^{\infty}t^{z-1}e^{-t}dt \f] The implementation of the algorithm was inspired by "Numerical Recipes in C", 2nd edition, Press, Teukolsky, Vetterling, Flannery, chapter 6 \test the correctness of the returned value is tested by checking it against known good results. */ public static class GammaFunction { const double c1_ = 76.18009172947146; const double c2_ = -86.50532032941677; const double c3_ = 24.01409824083091; const double c4_ = -1.231739572450155; const double c5_ = 0.1208650973866179e-2; const double c6_ = -0.5395239384953e-5; public static double logValue(double x) { Utils.QL_REQUIRE(x > 0.0, () => "positive argument required"); double temp = x + 5.5; temp -= (x + 0.5) * Math.Log(temp); double ser = 1.000000000190015; ser += c1_ / (x + 1.0); ser += c2_ / (x + 2.0); ser += c3_ / (x + 3.0); ser += c4_ / (x + 4.0); ser += c5_ / (x + 5.0); ser += c6_ / (x + 6.0); return -temp + Math.Log(2.5066282746310005 * ser / x); } public static double value(double x) { if (x >= 1.0) { return Math.Exp(logValue(x)); } if (x > -20.0) { return value(x + 1.0) / x; } return -Const.M_PI / (value(-x) * x * Math.Sin(Const.M_PI * x)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. namespace Microsoft.Psi.Visualization.VisualizationObjects { using System; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Runtime.Serialization; using System.Windows.Media; using Microsoft.Psi.Visualization.Collections; using Microsoft.Psi.Visualization.Data; using Microsoft.Psi.Visualization.Navigation; /// <summary> /// Provides a base, abstract class for stream visualization objects that show data from a stream interval. /// </summary> /// <typeparam name="TData">The type of the stream data.</typeparam> public abstract class StreamIntervalVisualizationObject<TData> : StreamVisualizationObject<TData> { private long samplingTicks; private string legendFormat = string.Empty; private TimeSpan viewDuration; private Guid summaryDataConsumerId = Guid.Empty; /// <summary> /// The data read from the stream. /// </summary> private ObservableKeyedCache<DateTime, Message<TData>>.ObservableKeyedView data; /// <summary> /// The interval data summarized from the stream data. /// </summary> private ObservableKeyedCache<DateTime, IntervalData<TData>>.ObservableKeyedView summaryData; /// <summary> /// Gets or sets the data view. /// </summary> [Browsable(false)] [IgnoreDataMember] public ObservableKeyedCache<DateTime, Message<TData>>.ObservableKeyedView Data { get => this.data; protected set { if (this.data != value) { if (this.data != null) { this.data.DetailedCollectionChanged -= this.OnDataDetailedCollectionChanged; } this.Set(nameof(this.Data), ref this.data, value); if (this.data != null) { this.data.DetailedCollectionChanged += this.OnDataDetailedCollectionChanged; this.OnDataCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } else { this.SetCurrentValue(null); } } } } /// <summary> /// Gets or sets the summary data view. /// </summary> [Browsable(false)] [IgnoreDataMember] public ObservableKeyedCache<DateTime, IntervalData<TData>>.ObservableKeyedView SummaryData { get => this.summaryData; protected set { if (this.summaryData != value) { var oldValue = this.summaryData; this.Set(nameof(this.SummaryData), ref this.summaryData, value); this.OnSummaryDataChanged(oldValue, this.summaryData); } } } /// <summary> /// Gets the value of the color to use when displaying in the legend. By default, white. /// </summary> public virtual Color LegendColor => Colors.White; /// <summary> /// Gets the value to display in the live legend. By default a formatted version of the current value is returned. /// </summary> [IgnoreDataMember] [DisplayName("Legend Value")] [Description("The legend value.")] public virtual string LegendValue { get { if (this.CurrentValue.HasValue) { var format = $"{{0:{this.LegendFormat}}}"; return string.Format(format, this.CurrentValue.Value.Data.ToString()); } else { return string.Empty; } } } /// <summary> /// Gets or sets the sampling ticks. /// </summary> [Browsable(false)] [DataMember] public long SamplingTicks { get => this.samplingTicks; set { if (value > 0) { value = 1L << (int)Math.Log(value, 2); } this.Set(nameof(this.SamplingTicks), ref this.samplingTicks, value); } } /// <summary> /// Gets or sets a format specifier string used in displaying the live legend value. /// </summary> [DataMember] [DisplayName("Legend Format")] [Description("The formatting string for the legend.")] public string LegendFormat { get { return this.legendFormat; } set { this.RaisePropertyChanging(nameof(this.LegendValue)); this.Set(nameof(this.LegendFormat), ref this.legendFormat, value); this.RaisePropertyChanged(nameof(this.LegendValue)); } } /// <summary> /// Gets a value indicating whether the visualization object is using summarization. /// </summary> protected bool IsUsingSummarization => this.StreamBinding.SummarizerType != null; /// <inheritdoc/> protected override void OnCursorModeChanged(object sender, CursorModeChangedEventArgs cursorModeChangedEventArgs) { // If we changed from or to live mode, and we're currently bound to a datasource, then refresh the data or summaries if (this.IsBound && cursorModeChangedEventArgs.OriginalValue != cursorModeChangedEventArgs.NewValue) { if ((cursorModeChangedEventArgs.OriginalValue == CursorMode.Live) || (cursorModeChangedEventArgs.NewValue == CursorMode.Live)) { this.RefreshData(); } } base.OnCursorModeChanged(sender, cursorModeChangedEventArgs); } /// <inheritdoc /> protected override void OnStreamBound() { base.OnStreamBound(); // Register as a summary data consumer if (this.IsUsingSummarization) { if (this.summaryDataConsumerId != Guid.Empty) { throw new InvalidOperationException("An attempt was made to register as a summary data consumer while already having an existing summary data consumer id."); } this.summaryDataConsumerId = DataManager.Instance.RegisterSummaryDataConsumer(this.StreamSource); } this.Navigator.ViewRange.RangeChanged += this.OnViewRangeChanged; this.OnViewRangeChanged( this.Navigator.ViewRange, new NavigatorTimeRangeChangedEventArgs(this.Navigator.ViewRange.StartTime, this.Navigator.ViewRange.StartTime, this.Navigator.ViewRange.EndTime, this.Navigator.ViewRange.EndTime)); } /// <inheritdoc /> protected override void OnStreamUnbound() { base.OnStreamUnbound(); // Unregister as a summary data consumer if (this.IsUsingSummarization) { if (this.summaryDataConsumerId == Guid.Empty) { throw new InvalidOperationException("An attempt was made to unregister as a summary data consumer without having a valid summary data consumer id."); } DataManager.Instance.UnregisterSummaryDataConsumer(this.summaryDataConsumerId); this.summaryDataConsumerId = Guid.Empty; } this.Navigator.ViewRange.RangeChanged -= this.OnViewRangeChanged; this.Data = null; this.SummaryData = null; } /// <inheritdoc/> protected override void OnPropertyChanging(object sender, PropertyChangingEventArgs e) { base.OnPropertyChanging(sender, e); if (e.PropertyName == nameof(this.CurrentValue)) { this.RaisePropertyChanging(nameof(this.LegendValue)); } } /// <inheritdoc/> protected override void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(this.CurrentValue)) { this.RaisePropertyChanged(nameof(this.LegendValue)); } base.OnPropertyChanged(sender, e); } /// <summary> /// Invoked when the <see cref="StreamIntervalVisualizationObject{TData}.SummaryData"/> property changes. /// </summary> /// <param name="oldValue">The old summary data value.</param> /// <param name="newValue">The new summary data value.</param> protected virtual void OnSummaryDataChanged( ObservableKeyedCache<DateTime, IntervalData<TData>>.ObservableKeyedView oldValue, ObservableKeyedCache<DateTime, IntervalData<TData>>.ObservableKeyedView newValue) { if (oldValue != null) { oldValue.DetailedCollectionChanged -= this.OnSummaryDataDetailedCollectionChanged; } if (newValue != null) { newValue.DetailedCollectionChanged += this.OnSummaryDataDetailedCollectionChanged; } this.OnSummaryDataCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } /// <summary> /// Called when data collection contents have changed. /// </summary> /// <param name="e">Collection changed event arguments.</param> protected virtual void OnDataCollectionChanged(NotifyCollectionChangedEventArgs e) { // see if we are still active if (this.Container == null) { return; } if (this.Navigator.CursorMode == CursorMode.Live) { var last = this.Data.LastOrDefault(); if (last != default) { this.SetCurrentValue(last); } } } /// <summary> /// Invoked when the <see cref="StreamIntervalVisualizationObject{TData}.SummaryData"/> collection changes. /// </summary> /// <param name="e">Collection changed event arguments.</param> protected virtual void OnSummaryDataCollectionChanged(NotifyCollectionChangedEventArgs e) { // see if we are still active if (this.Container == null) { return; } if (this.Navigator.IsCursorModePlayback) { IntervalData<TData> last = this.SummaryData.LastOrDefault(); if (last != default) { this.SetCurrentValue(Message.Create(last.Value, last.OriginatingTime, last.EndTime, 0, 0)); } } } /// <inheritdoc /> protected override void OnCursorChanged(object sender, NavigatorTimeChangedEventArgs e) { DateTime currentTime = e.NewTime; if (this.SummaryData != null) { int index = this.GetIndexForTime(currentTime, this.SummaryData?.Count ?? 0, (idx) => this.SummaryData[idx].OriginatingTime); if (index != -1) { var interval = this.SummaryData[index]; this.SetCurrentValue(Message.Create(interval.Value, interval.OriginatingTime, interval.EndTime, 0, 0)); } else { this.SetCurrentValue(null); } } else { int index = this.GetIndexForTime(currentTime, this.Data?.Count ?? 0, (idx) => this.Data[idx].OriginatingTime); if (index != -1) { this.SetCurrentValue(this.Data[index]); } else { this.SetCurrentValue(null); } } base.OnCursorChanged(sender, e); } /// <inheritdoc/> protected override void OnPanelPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(this.Panel.Width)) { if (this.StreamBinding?.SummarizerType != null) { this.SamplingTicks = (long)(this.viewDuration.Ticks / this.Panel.Width); this.RefreshData(); } } base.OnPanelPropertyChanged(sender, e); } private void OnViewRangeChanged(object sender, NavigatorTimeRangeChangedEventArgs e) { this.RefreshData(); } private void RefreshData() { // Check that we're actually bound to a store if (this.IsBound) { if (this.Navigator.CursorMode == CursorMode.Live) { if (this.viewDuration != this.Navigator.ViewRange.Duration) { this.viewDuration = this.Navigator.ViewRange.Duration; if (this.IsUsingSummarization) { // If performing summarization, recompute the sampling tick interval (i.e. summarization interval) // whenever the view range duration has changed. this.SamplingTicks = (long)(this.viewDuration.Ticks / this.Panel.Width); this.SummaryData = DataManager.Instance.ReadSummary<TData>( this.StreamSource, TimeSpan.FromTicks(this.SamplingTicks), last => last - this.viewDuration); } else { // Not summarizing, so read data directly from the stream this.Data = DataManager.Instance.ReadStream<TData>(this.StreamSource, last => last - this.viewDuration); } } } else { this.viewDuration = this.Navigator.ViewRange.Duration; if (this.IsUsingSummarization) { // If performing summarization, recompute the sampling tick interval (i.e. summarization interval) // whenever the view range duration has changed. this.SamplingTicks = (long)(this.viewDuration.Ticks / this.Panel.Width); var startTime = this.Navigator.ViewRange.StartTime; var endTime = this.Navigator.ViewRange.EndTime; // Attempt to read a little extra data outside the view range so that the end // points appear to connect to the next/previous values. This is flawed as we // are just guessing how much to extend the time interval by. What we really // need is for the DataManager to give us everything in the requested time // interval plus the next/previous data point just outside the interval. var extra = TimeSpan.FromMilliseconds(100); this.SummaryData = DataManager.Instance.ReadSummary<TData>( this.StreamSource, startTime > DateTime.MinValue + extra ? startTime - extra : startTime, endTime < DateTime.MaxValue - extra ? endTime + extra : endTime, TimeSpan.FromTicks(this.SamplingTicks)); } else { // Not summarizing, so read data directly from the stream - note that end time is exclusive, so adding one tick to ensure any message at EndTime is included this.Data = DataManager.Instance.ReadStream<TData>( this.StreamSource, this.Navigator.ViewRange.StartTime, this.Navigator.ViewRange.EndTime.AddTicks(1)); } } } else { this.Data = null; this.SummaryData = null; } } private void OnDataDetailedCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { this.OnDataCollectionChanged(e); } private void OnSummaryDataDetailedCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { this.OnSummaryDataCollectionChanged(e); } } }
// 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.Runtime.InteropServices; using Xunit; namespace Windows.UI.Xaml.Tests { public class ThicknessTests { [Fact] public void Ctor_Default() { var thickness = new Thickness(); Assert.Equal(0, thickness.Left); Assert.Equal(0, thickness.Top); Assert.Equal(0, thickness.Right); Assert.Equal(0, thickness.Bottom); } public static IEnumerable<object[]> Values_TestData() { yield return new object[] { -1 }; yield return new object[] { 0 }; yield return new object[] { 1 }; yield return new object[] { double.MaxValue }; yield return new object[] { double.NaN }; yield return new object[] { double.PositiveInfinity }; yield return new object[] { double.NegativeInfinity }; } [Theory] [MemberData(nameof(Values_TestData))] public void Ctor_Default(double uniformLength) { var thickness = new Thickness(uniformLength); Assert.Equal(uniformLength, thickness.Left); Assert.Equal(uniformLength, thickness.Top); Assert.Equal(uniformLength, thickness.Right); Assert.Equal(uniformLength, thickness.Bottom); } [Theory] [InlineData(-1, -2, -3, -4)] [InlineData(0, 0, 0, 0)] [InlineData(1, 2, 3, 4)] [InlineData(double.NaN, double.NaN, double.NaN, double.NaN)] [InlineData(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity)] [InlineData(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity)] public void Ctor_Left_Top_Right_Bottom(double left, double top, double right, double bottom) { var thickness = new Thickness(left, top, right, bottom); Assert.Equal(left, thickness.Left); Assert.Equal(top, thickness.Top); Assert.Equal(right, thickness.Right); Assert.Equal(bottom, thickness.Bottom); } [Theory] [MemberData(nameof(Values_TestData))] public void Left_Set_GetReturnsExpected(double value) { var thickness = new Thickness { Left = value }; Assert.Equal(value, thickness.Left); } [Theory] [MemberData(nameof(Values_TestData))] public void Top_Set_GetReturnsExpected(double value) { var thickness = new Thickness { Top = value }; Assert.Equal(value, thickness.Top); } [Theory] [MemberData(nameof(Values_TestData))] public void Right_Set_GetReturnsExpected(double value) { var thickness = new Thickness { Right = value }; Assert.Equal(value, thickness.Right); } [Theory] [MemberData(nameof(Values_TestData))] public void Bottom_Set_GetReturnsExpected(double value) { var cornerRadius = new Thickness { Bottom = value }; Assert.Equal(value, cornerRadius.Bottom); } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { new Thickness(1, 2, 3, 4), new Thickness(1, 2, 3, 4), true }; yield return new object[] { new Thickness(1, 2, 3, 4), new Thickness(2, 2, 3, 4), false }; yield return new object[] { new Thickness(1, 2, 3, 4), new Thickness(1, 3, 3, 4), false }; yield return new object[] { new Thickness(1, 2, 3, 4), new Thickness(1, 2, 4, 4), false }; yield return new object[] { new Thickness(1, 2, 3, 4), new Thickness(1, 2, 3, 5), false }; yield return new object[] { new Thickness(1, 2, 3, 4), new object(), false }; yield return new object[] { new Thickness(1, 2, 3, 4), null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals_Object_ReturnsExpected(Thickness thickness, object other, bool expected) { Assert.Equal(expected, thickness.Equals(other)); if (other is Thickness otherThickness) { Assert.Equal(expected, thickness.Equals(otherThickness)); Assert.Equal(expected, thickness == otherThickness); Assert.Equal(!expected, thickness != otherThickness); Assert.Equal(expected, thickness.GetHashCode().Equals(otherThickness.GetHashCode())); } } [Fact] public void ToString_Invoke_ReturnsExpected() { var thickness = new Thickness(1, 2.2, 3, 4); Assert.Equal("1,2.2,3,4", thickness.ToString()); } [Fact] public void ToString_NaN_ReturnsAuto() { Thickness thickness = new FakeThickness { Left = double.NaN, Top = double.NaN, Right = double.NaN, Bottom = double.NaN }.ToActual(); Assert.Equal("Auto,Auto,Auto,Auto", thickness.ToString()); } public struct FakeThickness { public double Left; public double Top; public double Right; public double Bottom; public Thickness ToActual() { ThicknessWrapper wrapper = default(ThicknessWrapper); wrapper.Fake = this; return wrapper.Actual; } } [StructLayout(LayoutKind.Explicit)] public struct ThicknessWrapper { [FieldOffset(0)] public Thickness Actual; [FieldOffset(0)] public FakeThickness Fake; } } }
using Termine.Promises.Generics; namespace TestConsumePromise.Collections { public class NewCollectionRequest: GenericRequest { public string CollectionName { get; set; } public int Visibility { get; set; } } }
using Microsoft.Extensions.DependencyInjection; using Moq; using System; using Xunit; namespace RT.Comb.AspNetCore.Tests { public sealed class PostgresSqlCombProviderServiceCollectionExtensionsTests { [Fact] public void AddPostgreSqlCombGuidWithSqlDateTime_ShouldAddPostgreSqlProviderWithDefaultStrategies() { // Arrange var services = new ServiceCollection(); // Act services.AddPostgreSqlCombGuidWithSqlDateTime(); // Assert var serviceProvider = services.BuildServiceProvider(); var comb = serviceProvider.GetService<ICombProvider>(); var sqlCombProvider = comb as PostgreSqlCombProvider; Assert.NotNull(sqlCombProvider); Assert.IsType<SqlDateTimeStrategy>(TestUtils.GetCurrentDateTimeStrategy(sqlCombProvider)); } [Fact] public void AddPostgreSqlCombGuidWithSqlDateTime_CustomStrategies_CreateShouldInvokeCustomStrategies() { // Arrange var services = new ServiceCollection(); // custom timestamp and guid strategies var customTimestampProviderMock = new Mock<TimestampProvider>(); customTimestampProviderMock.Setup(p => p.Invoke()).Returns(DateTime.Now); var customGuidProviderMock = new Mock<GuidProvider>(); customGuidProviderMock.Setup(p => p.Invoke()).Returns(Guid.NewGuid()); services.AddPostgreSqlCombGuidWithSqlDateTime(customTimestampProviderMock.Object, customGuidProviderMock.Object); var serviceProvider = services.BuildServiceProvider(); var comb = serviceProvider.GetService<ICombProvider>(); // Act var _ = comb.Create(); // Assert customTimestampProviderMock.Verify(p => p.Invoke(), Times.Once); customGuidProviderMock.Verify(p => p.Invoke(), Times.Once); } [Fact] public void AddPostgreSqlCombGuidWithUnixDateTime_ShouldAddPostgreSqlProviderWithDefaultStrategies() { // Arrange var services = new ServiceCollection(); // Act services.AddPostgreSqlCombGuidWithUnixDateTime(); // Assert var serviceProvider = services.BuildServiceProvider(); var comb = serviceProvider.GetService<ICombProvider>(); var sqlCombProvider = comb as PostgreSqlCombProvider; Assert.NotNull(sqlCombProvider); Assert.IsType<UnixDateTimeStrategy>(TestUtils.GetCurrentDateTimeStrategy(sqlCombProvider)); } [Fact] public void AddPostgreSqlCombGuidWithUnixDateTime_CustomStrategies_CreateShouldInvokeCustomStrategies() { // Arrange var services = new ServiceCollection(); // custom timestamp and guid strategies var customTimestampProviderMock = new Mock<TimestampProvider>(); customTimestampProviderMock.Setup(p => p.Invoke()).Returns(DateTime.Now); var customGuidProviderMock = new Mock<GuidProvider>(); customGuidProviderMock.Setup(p => p.Invoke()).Returns(Guid.NewGuid()); services.AddPostgreSqlCombGuidWithUnixDateTime(customTimestampProviderMock.Object, customGuidProviderMock.Object); var serviceProvider = services.BuildServiceProvider(); var comb = serviceProvider.GetService<ICombProvider>(); // Act var _ = comb.Create(); // Assert customTimestampProviderMock.Verify(p => p.Invoke(), Times.Once); customGuidProviderMock.Verify(p => p.Invoke(), Times.Once); } } }
using System; using System.Collections.Generic; using System.Text; namespace XF_Monettelli.CodeFontIcons { static class MonettelliFontIcons { public const string icon_brand_monettelliuikit = "\ue800"; public const string icon_fly_menu = "\ue801"; public const string icon_fly_rocket_outline = "\ue802"; public const string icon_fly_view_dashboard_outline = "\ue803"; public const string icon_fly_xamarin_outline = "\ue804"; public const string icon_fly_ballot_outline = "\ue805"; public const string icon_fly_animation_outline = "\ue806"; public const string icon_fly_palette_outline = "\ue807"; public const string icon_fly_file_document_outline = "\ue808"; } }
using FluentAssertions; using PartialResponseRequest.Filters.Serializers; using PartialResponseRequest.Filters.TokenReaders.Tokens; using System.Collections.Generic; using Xunit; namespace PartialResponseRequest.Tests { public class FilterSerializerTests { [Fact] public void SerializesFilterTokensCorrectly() { var serializer = new FiltersQuerySerializer(); var result = serializer.Serialize(new List<FilterToken>() { new FilterToken("sum", new List<OperatorToken>() { new OperatorToken("gt", "5"), new OperatorToken("lt", "10") }) }); result.Should().Be("sum(gt:5,lt:10)"); } } }
using System; namespace OOPEx { public class Truck : Vehicle { public Truck(double fuelQ, double fuelCons) : base(fuelQ, fuelCons) { } public override double FuelConsumption { get => base.FuelConsumption; protected set => base.FuelConsumption = value + 1.6; } public override void Refuel(double fuel) { this.FuelQuantity += fuel * 0.95; } } }
using System; using System.Activities.Expressions; using System.Activities.Presentation.Expressions; using System.Activities.Presentation.Internal.PropertyEditing; using System.Activities.Presentation.Model; using System.Activities.Presentation.View; using System.Activities.XamlIntegration; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime; using System.Runtime.Versioning; using System.Text; using Microsoft.Activities.Presentation; using Microsoft.VisualBasic.Activities; namespace System.Activities.Presentation { internal static class ExpressionHelper { internal static string GetExpressionString(Activity expression) { return ExpressionHelper.GetExpressionString(expression, null as ParserContext); } internal static string GetExpressionString(Activity expression, ModelItem owner) { ParserContext context = new ParserContext(owner); return ExpressionHelper.GetExpressionString(expression, context); } internal static string GetExpressionString(Activity expression, ParserContext context) { string expressionString = null; if (expression != null) { Type expressionType = expression.GetType(); Type expressionArgumentType = expressionType.IsGenericType ? expressionType.GetGenericArguments()[0] : typeof(object); bool isLiteral = expressionType.IsGenericType ? Type.Equals(typeof(Literal<>), expressionType.GetGenericTypeDefinition()) : false; //handle ITextExpression if (expression is ITextExpression) { ITextExpression textExpression = expression as ITextExpression; expressionString = textExpression.ExpressionText; } //handle Literal Expression else if (isLiteral) { TypeConverter converter = XamlUtilities.GetConverter(expressionArgumentType); if (converter != null && converter.CanConvertTo(context, typeof(string))) { PropertyInfo literalValueProperty = expressionType.GetProperty("Value"); Fx.Assert(literalValueProperty != null && literalValueProperty.GetGetMethod() != null, "Literal<T> must have the Value property with a public get accessor."); object literalValue = literalValueProperty.GetValue(expression, null); string convertedString = null; if (literalValue != null) { try { convertedString = converter.ConvertToString(context, literalValue); } catch (ArgumentException) { convertedString = literalValue.ToString(); } } expressionString = expressionArgumentType == typeof(string) ? ("\"" + convertedString + "\"") : convertedString; } } else if (expressionType.IsGenericType && (expressionType.GetGenericTypeDefinition() == typeof(VariableValue<>) || expressionType.GetGenericTypeDefinition() == typeof(VariableReference<>))) { PropertyInfo variableProperty = expression.GetType().GetProperty("Variable"); Variable variable = variableProperty.GetValue(expression, null) as Variable; if (variable != null) { expressionString = variable.Name; } } } return expressionString; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The conversion to an expression might fail due to invalid user input. Propagating exceptions might lead to VS crash.")] [SuppressMessage("Reliability", "Reliability108:IsFatalRule", Justification = "The conversion to an expression might fail due to invalid user input. Propagating exceptions might lead to VS crash.")] internal static ActivityWithResult TryCreateLiteral(Type type, string expressionText, ParserContext context) { //try easy way first - look if there is a type conversion which supports conversion between expression type and string TypeConverter literalValueConverter = null; bool isQuotedString = false; if (CanTypeBeSerializedAsLiteral(type)) { bool shouldBeQuoted = typeof(string) == type; //whether string begins and ends with quotes '"'. also, if there are //more quotes within than those begining and ending ones, do not bother with literal - assume this is an expression. isQuotedString = shouldBeQuoted && expressionText.StartsWith("\"", StringComparison.CurrentCulture) && expressionText.EndsWith("\"", StringComparison.CurrentCulture) && expressionText.IndexOf("\"", 1, StringComparison.CurrentCulture) == expressionText.Length - 1; //if expression is a string, we must ensure it is quoted, in case of other types - just get the converter if ((shouldBeQuoted && isQuotedString) || !shouldBeQuoted) { literalValueConverter = TypeDescriptor.GetConverter(type); } } //if there is converter - try to convert if (null != literalValueConverter && literalValueConverter.CanConvertFrom(context, typeof(string))) { try { var valueToConvert = isQuotedString ? expressionText.Substring(1, expressionText.Length - 2) : expressionText; var converterValue = literalValueConverter.ConvertFrom(context, CultureInfo.CurrentCulture, valueToConvert); //ok, succeeded - create literal of given type var concreteExpType = typeof(Literal<>).MakeGenericType(type); return (ActivityWithResult)Activator.CreateInstance(concreteExpType, converterValue); } //conversion failed - do nothing, let VB compiler take care of the expression catch { } } return null; } internal static bool CanTypeBeSerializedAsLiteral(Type type) { //type must be set and cannot be object if (null == type || typeof(object) == type) { return false; } return type.IsPrimitive || type == typeof(string) || type == typeof(TimeSpan) || type == typeof(DateTime); } // Test whether this activity is Expression internal static bool IsExpression(this Activity activity) { return activity is ActivityWithResult; } internal static bool IsGenericLocationExpressionType(ActivityWithResult expression) { Type expressionType = expression.ResultType; return expressionType.IsGenericType && typeof(Location<>) == expressionType.GetGenericTypeDefinition(); } internal static bool TryMorphExpression(ActivityWithResult originalExpression, bool isLocation, Type targetType, EditingContext context, out ActivityWithResult morphedExpression) { bool succeeded = false; morphedExpression = null; if (originalExpression != null) { Type resultType = originalExpression.ResultType; if ((isLocation) && (ExpressionHelper.IsGenericLocationExpressionType(originalExpression) && (targetType == resultType.GetGenericArguments()[0])) || (!isLocation) && (resultType == targetType)) { //no need to morph succeeded = true; morphedExpression = originalExpression; } else { Type expressionType = originalExpression.GetType(); if (expressionType.IsGenericType) { expressionType = expressionType.GetGenericTypeDefinition(); } ExpressionMorphHelperAttribute morphHelperAttribute = ExtensibilityAccessor.GetAttribute<ExpressionMorphHelperAttribute>(expressionType); if (morphHelperAttribute != null) { ExpressionMorphHelper morphHelper = Activator.CreateInstance(morphHelperAttribute.ExpressionMorphHelperType) as ExpressionMorphHelper; if (morphHelper != null) { succeeded = morphHelper.TryMorphExpression(originalExpression, isLocation, targetType, context, out morphedExpression); if (succeeded && morphedExpression != null) { string editorName = ExpressionActivityEditor.GetExpressionActivityEditor(originalExpression); if (!string.IsNullOrWhiteSpace(editorName)) { ExpressionActivityEditor.SetExpressionActivityEditor(morphedExpression, editorName); } } } } } } else { succeeded = true; } return succeeded; } // this method may has side effect, it may modify model. internal static bool TryInferReturnType(ActivityWithResult expression, EditingContext context, out Type returnType) { bool succeeded = false; returnType = null; Type expressionType = expression.GetType(); if (expressionType.IsGenericType) { expressionType = expressionType.GetGenericTypeDefinition(); ExpressionMorphHelperAttribute morphHelperAttribute = ExtensibilityAccessor.GetAttribute<ExpressionMorphHelperAttribute>(expressionType); if (morphHelperAttribute != null) { ExpressionMorphHelper morphHelper = Activator.CreateInstance(morphHelperAttribute.ExpressionMorphHelperType) as ExpressionMorphHelper; if (morphHelper != null) { succeeded = morphHelper.TryInferReturnType(expression, context, out returnType); } } } return succeeded; } internal static string GetRootEditorSetting(ModelTreeManager modelTreeManager, FrameworkName targetFramework) { return ExpressionSettingHelper.GetRootEditorSetting(modelTreeManager, targetFramework); } } }
using System; using System.Reflection; namespace SampSharp.Core.Natives.NativeObjects { /// <summary> /// Provides information about a native which can be consumed by a proxy factory IL generator. /// </summary> public class NativeIlGenContext { private MethodInfo _baseMethod; /// <summary> /// Gets or sets the name of the native to be called. /// </summary> public string NativeName { get; set; } /// <summary> /// Gets or sets the base method of the proxy type to by overridden. /// </summary> public MethodInfo BaseMethod { get => _baseMethod; set => _baseMethod = value; } /// <summary> /// Gets or sets the parameters of the native. /// </summary> public NativeIlGenParam[] Parameters { get; set; } /// <summary> /// Gets or sets the fields generated for the proxy. /// </summary> public FieldInfo[] ProxyGeneratedFields { get; set; } /// <summary> /// Gets or sets the base method parameter types. /// </summary> public Type[] MethodParameterTypes { get; set; } /// <summary> /// Gets or sets the method attributes to be used to override the base method implementation. /// </summary> public MethodAttributes MethodOverrideAttributes { get; set; } } }
namespace DotNetBungieAPI.Generated.Models.Destiny.Definitions; public class DestinyItemTooltipNotification { [JsonPropertyName("displayString")] public string? DisplayString { get; set; } [JsonPropertyName("displayStyle")] public string? DisplayStyle { get; set; } }
using System; using System.Collections.Generic; using Comformation.IntrinsicFunctions; namespace Comformation.AppSync.GraphQLSchema { /// <summary> /// AWS::AppSync::GraphQLSchema /// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appsync-graphqlschema.html /// </summary> public class GraphQLSchemaResource : ResourceBase { public class GraphQLSchemaProperties { /// <summary> /// Definition /// The text representation of a GraphQL schema in SDL format. /// For more information about using the Ref function, see Ref. /// Required: No /// Type: String /// Update requires: No interruption /// </summary> public Union<string, IntrinsicFunction> Definition { get; set; } /// <summary> /// DefinitionS3Location /// The location of a GraphQL schema file in an Amazon S3 bucket. Use this if you want to provision with /// the schema living in Amazon S3 rather than embedding it in your CloudFormation template. /// Required: No /// Type: String /// Update requires: No interruption /// </summary> public Union<string, IntrinsicFunction> DefinitionS3Location { get; set; } /// <summary> /// ApiId /// The AWS AppSync GraphQL API identifier to which you want to apply this schema. /// Required: Yes /// Type: String /// Update requires: Replacement /// </summary> public Union<string, IntrinsicFunction> ApiId { get; set; } } public string Type { get; } = "AWS::AppSync::GraphQLSchema"; public GraphQLSchemaProperties Properties { get; } = new GraphQLSchemaProperties(); } }
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace akset.data { public class User: IdentityUser { public string Ad { get; set; } public string Soyad { get; set; } public string RoleId { get; set; } public string Ip { get; set; } public DateTime Tarih { get; set; } public DateTime? DogumTarihi { get; set; } public virtual Role Role { get; set; } public string sifre { get; set; } public string cinsiyet { get; set; } public string adres { get; set; } public int Sehir { get; set; } public int ilce { get; set; } public string adrestelefon { get; set; } public string smskod { get; set; } public int? GroupId { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } public virtual ICollection<Product> Products { get; set; } public virtual ICollection<Address> Addresss { get; set; } public virtual Group Group { get; set; } public virtual ICollection<Order> Orders { get; set; } public virtual ICollection<Komisyon> Komisyons { get; set; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using SharpMusicLibraryUpdater.App.Services; using SharpMusicLibraryUpdater.App.Models; using iTunesSearch.Library; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; using System.Text.RegularExpressions; using SharpMusicLibraryUpdater.App.ViewModels; using System.IO; using System.Text; namespace SharpMusicLibraryUpdater.Tests { [TestClass] public class ViewModelTests { [TestMethod] public void NoSettings_EmptyArtistList() { var vm = new ArtistViewModel(new MusicLibraryReader(), new iTunesSearchManager(), new SettingsSerializer(Path.GetRandomFileName()) ); Assert.IsTrue(!vm.Artists.Any()); } [TestMethod] public void ReadCorruptedSettingsFile_EmptyArtistsList() { var vm = new ArtistViewModel(new MusicLibraryReader(), new iTunesSearchManager(), new SettingsSerializer(Path.GetTempFileName()) ); Assert.IsTrue(!vm.Artists.Any()); } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace PluginWebRequestOkta.DataContracts { public class ObjectResponseWrapper { [JsonProperty("results")] public List<ObjectResponse> Results { get; set; } [JsonProperty("paging")] public PagingResponse Paging { get; set; } } public class ObjectResponse { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("properties")] public Dictionary<string, object> Properties { get; set; } } public class PropertyResponseWrapper { [JsonProperty("results")] public List<PropertyResponse> Results { get; set; } [JsonProperty("paging")] public PagingResponse Paging { get; set; } } public class PropertyResponse { [JsonProperty("name")] public string Id { get; set; } [JsonProperty("label")] public string Name { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("hasUniqueValue")] public bool IsKey { get; set; } [JsonProperty("calculated")] public bool Calculated { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("modificationMetadata")] public ModificationMetaData ModificationMetaData { get; set; } } public class PagingResponse { [JsonProperty("next")] public NextResponse Next { get; set; } } public class NextResponse { [JsonProperty("after")] public string After { get; set; } [JsonProperty("link")] public string Link { get; set; } } }