content
stringlengths
23
1.05M
@using ChameleonStore.Web @using ChameleonStore.Web.Models @using ChameleonStore.Models @using ChameleonStore.Web.Pages.Orders @using ChameleonStore.Common.Orders.ViewModels @using ChameleonStore.Web.Pages.Products @using ChameleonStore.Common.Products.ViewModels @using ChameleonStore.Common.Areas.Admin.Users.ViewModels @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AltBuild.LinkedPath.Parser { /// <summary> /// 属性のキーと値を複数保持(カンマ区切り= ',') /// 例1: class='text-success fw-bold',disabled /// </summary> public class PathAttributeCollection : List<PathAttribute> { /// <summary> /// 接頭辞 /// </summary> public string Prefix { get; } /// <summary> /// 接尾辞 /// </summary> public string Suffix { get; } public bool IsExist(string key) { var format = Find(o => o.Key == "format"); if (format != null) { if (format.Line != null && format.Line.Contains(key)) return true; } return TryGetValue(key, out string optionValue); } public bool Include(string key, string value) { var index = base.FindIndex(o => o.Key == key); if (index >= 0) { base.RemoveAt(index); return false; } else { base.Add(new PathAttribute(key, value)); return true; } } public bool TryGetFormat(out string format) { // Get format only string if (Count == 1 && this[0].Type == PathKeyValueType.Key) { format = this[0].Key; return true; } // Get format value string return TryGetValue("format", out format); } /// <summary> /// 指定のキーを取得 /// </summary> /// <param name="keys"></param> /// <returns></returns> public PathAttribute GetExists(IEnumerable<string> keys) => this.FirstOrDefault(o => keys.Contains(o.Key)); public bool IsExist(string key, string value) => TryGetValue(key, out string optionValue) && optionValue.IndexOf(value) >= 0; public bool TryGetEnumFlags<T>(string key, out T enumValue) where T: struct, Enum { int target = default; if (TryGetValue(key, out string value)) { foreach (var targetName in value.Split('|', StringSplitOptions.RemoveEmptyEntries)) { if (Enum.TryParse(targetName.Trim(), out T atValue)) { dynamic dynValue = atValue; int intValue = (int)dynValue; target |= (int)dynValue; } } enumValue = (T)Enum.ToObject(typeof(T), target); return true; } else { enumValue = default; return false; } } public T? GetEnum<T>(string key, T defaultValue = default) where T : struct, Enum { if (TryGetValue(key, out string value)) if (Enum.TryParse(value, out T enumValue)) return enumValue; else return defaultValue; return null; } public bool TryGetEnum<T>(string key, out T value) where T: struct, Enum { T? results = GetEnum<T>(key); value = results ?? default; return (results != null); } public bool TryGetValue(string key, out string value) { // 指定のキーを抽出 var results = Find(o => o.Key == key); if (results == null) { value = null; return false; } else { value = results.Line; return true; } } /// <summary> /// 指定のキーの値を取得する /// </summary> /// <param name="key"></param> /// <returns></returns> public string this[string key] => Find(o => o.Key == key)?.Line; public StringBuilder ToStringBuilder(StringBuilder builder) { if (builder == null) builder = new StringBuilder(); if (Count > 0) { builder.Append(':'); for (int i = 0; i < Count; i++) { if (i > 0) builder.Append(','); builder.Append(this[i].ToString()); } } return builder; } public override string ToString() => ToStringBuilder(null).ToString(); public string ToString(PathKeyValueType keyValueType) { StringBuilder bild = new (); foreach (var kvItem in this) { if (kvItem.Type == keyValueType) { if (bild.Length > 0) bild.Append(','); bild.Append(kvItem); } } return bild.ToString(); } public PathAttributeCollection Add(string line) { // KeyValue を追加する InductHelper.CreateKeyValues(line, (key, value, bString) => { // 結果 List<string> classItems = new List<string>(); // 既存値を分割 PathAttribute pathAttribute = Find(o => o.Key == key); if (pathAttribute == null) base.Add((pathAttribute = new PathAttribute(key, value, bString))); else pathAttribute.AddValue(value); }); // 自身を返す return this; } public PathAttributeCollection() { } public PathAttributeCollection(string line, string prefix = null, string suffix = null) { // 元情報 Prefix = prefix; Suffix = suffix; // Create keyValues Add(line); } public PathAttributeCollection(ChunkPartAttributes attributes) { foreach (var atPart in attributes) { if (atPart is ChunkPartName partName) { if (partName.TryGetDescendants(out ChunkPartOperator partOperator)) { // ABC='123' if (partOperator.TryGetDescendants(out ChunkPartValue partValue)) AddAttribute(partName.FullName, partValue.Value); continue; } AddAttribute(partName.FullName, null); } else if (atPart is ChunkPartValue partValue) { AddAttribute("format", partValue.Line.ToString()); } } void AddAttribute(string name, object? value) { Add(new PathAttribute( name, value?.ToString(), (value?.GetType() == typeof(string)))); } } public static PathAttributeCollection Parse(string line) => new PathAttributeCollection(line); } }
using EFT; using FilesChecker; using Haru.Modules.Patches; using Haru.Modules.Providers; namespace Haru.Modules { /// <summary> /// Main application /// </summary> public class Program { /// <summary> /// Entry point /// </summary> public static void Main() { var types = TypeProvider.Instance; var patches = PatchProvider.Instance; // add types types.Add("EFT", typeof(AbstractGame).Assembly.GetTypes()); types.Add("FILESCHECKER", typeof(ICheckResult).Assembly.GetTypes()); // load patches patches.Add<BattlEyePatch>(); patches.Add<VerifyMultiplePatch>(); patches.Add<VerifySinglePatch>(); patches.Add<CertificatePatch>(); patches.Add<TextureRequestPatch>(); patches.Add<WebSocketPatch>(); patches.EnableAll(); } } }
using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace SYN.ApiCore.Middleware { public class ExceptionHandleMiddleware { private readonly RequestDelegate _next; private readonly ILogger<ExceptionHandleMiddleware> _logger; public ExceptionHandleMiddleware(RequestDelegate next, ILogger<ExceptionHandleMiddleware> logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception e) { try { _logger.LogWarning(e.ToString()); } catch (Exception) { // Catch日志操作异常,以便于不影响主逻辑 } await HandleExceptionAsync(context, context.Response.StatusCode, e.Message); } finally { var statusCode = context.Response.StatusCode; var msg = string.Empty; switch (statusCode) { case 401: msg = "未授权"; break; case 404: msg = "未找到服务"; break; case 502: msg = "请求错误"; break; default: break; } if (statusCode != 200) { msg = "未知错误"; } if (!string.IsNullOrEmpty(msg)) { await HandleExceptionAsync(context, statusCode, msg); } } } private Task HandleExceptionAsync(HttpContext context, int statusCode, string msg) { var data = new {code = statusCode.ToString(), is_success = false, msg = msg}; var result = JsonConvert.SerializeObject(new {data = data}); context.Response.ContentType = "application/json;charset=utf-8"; return context.Response.WriteAsync(result); } } }
using System; using System.Collections.Generic; using System.Text; using MO.Common.Content; using MO.Common.Lang; namespace MObj.Windows.Schedule { public class FScheduleJobs : FObjects<FScheduleJob> { public FScheduleJobs() { } } }
using System; namespace EDSDKWrapper.Framework.Enums { public enum LiveViewDepthOfFieldPreview : uint { OFF = 0x00000000, ON = 0x00000001, } }
/* https://www.codewars.com/kata/57a1d5ef7cb1f3db590002af/csharp 7 kyu Fibonacci Create function fib that returns n'th element of Fibonacci sequence (classic programming task). */ using System; namespace CodeWars { public class Fibonacci { public static int fib(int n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); // return n > 1 ? fib(n - 1) + fib(n - 2) : n; } } }
namespace Be.Vlaanderen.Basisregisters.Shaperon { using GeoAPI.Geometries; using GeoAPI.IO; using NetTopologySuite.IO; public class WellKnownBinaryWriter { private readonly WKBWriter _wkbWriter; public WellKnownBinaryWriter() => _wkbWriter = new WKBWriter(ByteOrder.LittleEndian, true) { HandleOrdinates = Ordinates.XYZM }; public byte[] Write(IGeometry geometry) => _wkbWriter.Write(geometry); } }
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas { using Newtonsoft.Json; using Newtonsoft.Json.Converters; /// <summary>Describes the storage placement for primitive properties.</summary> [JsonConverter(typeof(StringEnumConverter), true)] // camelCase:true public enum StorageKind { /// <summary>The property defines a sparse column.</summary> /// <remarks> /// Columns marked <see cref="Sparse" /> consume no space in the row when not present. When /// present they appear in an unordered linked list at the end of the row. Access time for /// <see cref="Sparse" /> columns is proportional to the number of <see cref="Sparse" /> columns in the /// row. /// </remarks> Sparse = 0, /// <summary>The property is a fixed-length, space-reserved column.</summary> /// <remarks> /// The column will consume 1 null-bit, and its byte-width regardless of whether the value is /// present in the row. /// </remarks> Fixed, /// <summary>The property is a variable-length column.</summary> /// <remarks> /// The column will consume 1 null-bit regardless of whether the value is present. When the value is /// present it will also consume a variable number of bytes to encode the length preceding the actual /// value. /// <para> /// When a <em>long</em> value is marked <see cref="Variable" /> then a null-bit is reserved and /// the value is optionally encoded as <see cref="Variable" /> if small enough to fit, otherwise the /// null-bit is set and the value is encoded as <see cref="Sparse" />. /// </para> /// </remarks> Variable, } }
using System.Data.Odbc; using System.Collections.Generic; using System.Data; namespace Aquiris.Tools.XLS { public class XLSParser : XLSConnector{ public string Sheet {set{m_sheet = "["+value + "$]";}} private string m_sheet; public XLSParser(string p_datasource, string p_sheet = null):base(p_datasource){ Sheet = p_sheet; } public DataTable Parse(){ return ParseQuery("SELECT * FROM "+m_sheet+""); } private DataTable ParseQuery(string p_selectQuery){ DataTable result = new DataTable(); OdbcDataAdapter adapter = new OdbcDataAdapter(p_selectQuery, m_connection); adapter.Fill(result); return result; } } }
public static class Lighting { public static void RecalculateNaturalLight(ChunkData chunk) { for(int i =0; i<VoxelData.chunkWidth; i++) { for(int j =0; j<VoxelData.chunkWidth; j++) { NaturalLight(chunk, i, j, VoxelData.chunkHeight - 1); } } } public static void NaturalLight(ChunkData chunk, int x, int z, int startY) { if(startY > VoxelData.chunkHeight - 1) { startY = VoxelData.chunkHeight - 1; } //check if light has hit an opaque or translucent block bool lightObstructed = false; for(int y = startY; y > -1; y--) { VoxelState voxel = chunk.map[x, y, z]; if (lightObstructed) voxel.light = 0; else if (voxel.properties.opacity > 0) { voxel.light = 0; lightObstructed = true; } else voxel.light = 15; } } }
namespace XenForms.Core.Reflection { public interface IXenCodeCompiler { bool FromFiles(int names, string[] fileNames, out byte[] data); bool FromFile(string fileName, out byte[] data); bool FromSource(string code, out byte[] data); } }
using System; using Http.chunk_ext_name; using Http.chunk_ext_val; using JetBrains.Annotations; using Txt.ABNF; using Txt.Core; namespace Http.chunk_ext { public sealed class ChunkExtensionLexerFactory : RuleLexerFactory<ChunkExtension> { static ChunkExtensionLexerFactory() { Default = new ChunkExtensionLexerFactory( ChunkExtensionNameLexerFactory.Default.Singleton(), ChunkExtensionValueLexerFactory.Default.Singleton()); } public ChunkExtensionLexerFactory( [NotNull] ILexerFactory<ChunkExtensionName> chunkExtensionName, [NotNull] ILexerFactory<ChunkExtensionValue> chunkExtensionValue) { if (chunkExtensionName == null) { throw new ArgumentNullException(nameof(chunkExtensionName)); } if (chunkExtensionValue == null) { throw new ArgumentNullException(nameof(chunkExtensionValue)); } ChunkExtensionName = chunkExtensionName; ChunkExtensionValue = chunkExtensionValue; } [NotNull] public static ChunkExtensionLexerFactory Default { get; } [NotNull] public ILexerFactory<ChunkExtensionName> ChunkExtensionName { get; set; } [NotNull] public ILexerFactory<ChunkExtensionValue> ChunkExtensionValue { get; set; } public override ILexer<ChunkExtension> Create() { var innerLexer = Repetition.Create( Concatenation.Create( Terminal.Create(@";", StringComparer.Ordinal), ChunkExtensionName.Create(), Option.Create( Concatenation.Create( Terminal.Create(@"=", StringComparer.Ordinal), ChunkExtensionValue.Create()))), 0, int.MaxValue); return new ChunkExtensionLexer(innerLexer); } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Localization; namespace Schematic.Core.Mvc { [Route("{culture}/portal")] [Authorize] public class PortalController : Controller { [HttpGet] public IActionResult Portal() { return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using Correspondence.Memory; using System.Threading.Tasks; namespace Correspondence.UnitTest { public class AsyncTest { protected AsyncMemoryStorageStrategy _memory; private Community _community; protected void InitializeAsyncTest() { _memory = new AsyncMemoryStorageStrategy(); } protected Community Community { get { return _community; } set { _community = value; } } protected async Task QuiesceAllAsync() { await _community.QuiesceAsync(); } } }
using System.Collections.Generic; using UnityEngine; using TMPro; namespace DSC.UI { public class DSC_UI_TextGroupController : UIGroupController<TextMeshProUGUI> { #region Data protected struct TextData { public Color m_hDefaultColor; } #endregion #region Variable #region Variable - Inspector #pragma warning disable 0649 [SerializeField] protected int m_nGroupID; [SerializeField] protected List<TextMeshProUGUI> m_lstText; #pragma warning restore 0649 #endregion #region Variable - Property public override int groupID { get { return m_nGroupID; } } public override UIType groupType { get { return UIType.Text; } } protected override List<TextMeshProUGUI> componentList { get { return m_lstText; } } #endregion protected Dictionary<TextMeshProUGUI, TextData> m_dicTextData = new Dictionary<TextMeshProUGUI, TextData>(); #endregion #region Main public virtual void SetText(int nIndex, string sText) { if (!TryGetBehaviourComponent(nIndex, out var hText)) return; hText.SetText(sText); } public virtual void SetTextColor(int nIndex, Color hColor) { if (!TryGetBehaviourComponent(nIndex, out var hText)) return; if (!m_dicTextData.ContainsKey(hText)) { m_dicTextData.Add(hText, new TextData { m_hDefaultColor = hText.color }); } hText.color = hColor; } public virtual void ResetTextColorToDefault(int nIndex) { if (!TryGetBehaviourComponent(nIndex, out var hText)) return; if (!m_dicTextData.ContainsKey(hText)) return; hText.color = m_dicTextData[hText].m_hDefaultColor; } public virtual TextAlignmentOptions GetTextAlign(int nIndex) { if (!TryGetBehaviourComponent(nIndex, out var hText)) return TextAlignmentOptions.Center; return hText.alignment; } public virtual void SetTextAlign(int nIndex, TextAlignmentOptions eAlign) { if (!TryGetBehaviourComponent(nIndex, out var hText)) return; hText.alignment = eAlign; } #endregion } }
using EventUtils; using System.Collections; using UnityEngine; namespace Interaction { public class InteractableObject : MonoBehaviour { public UnityBoolEvent onFocused; public UnityInteractorEvent onInteract; private bool isFocused = false; public virtual void SetFocus(bool value) { if (isFocused == value) return; isFocused = value; onFocused.Invoke(isFocused); } public virtual void Interact(InteractionInputProvider provider) { onInteract.Invoke(provider); } } }
using UnityEngine; using UnityEngine.Events; using System.Collections; using System.Collections.Generic; using uStableObject.Data; namespace uStableObject { public abstract class GameEventListenerBase<T> : MonoBehaviour, IGameEventListener<T> { [SerializeField] protected BoolVar _filter; public abstract GameEventBase<T> Event { get; } public abstract UnityEvent<T> Response { get; } protected virtual void OnEnable() { this.Event.Register(this); } private void OnDisable() { this.Event.Unregister(this); } public virtual void OnEventRaised(T param) { if (this._filter == null || this._filter.Value) { this.Response.Invoke(param); } } } public abstract class GameEventListenerBase<T1, T2> : MonoBehaviour, IGameEventListener<T1, T2> { [SerializeField] BoolVar _filter; public abstract GameEventBase<T1, T2> Event { get; } public abstract UnityEvent<T1, T2> Response { get; } private void OnEnable() { this.Event.Register(this); } private void OnDisable() { this.Event.Unregister(this); } public void OnEventRaised(T1 param1, T2 param2) { if (this._filter == null || this._filter.Value) { this.Response.Invoke(param1, param2); } } } }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Sample.Application { public interface IDistributedWeatherService { Task<IEnumerable<WeatherForecast>> FetchAsync(CancellationToken cancellationToken); } }
using GrazeDocs.LivePreview; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; namespace GrazeDocs { public partial class Startup { public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddRouting(); services.AddSignalR(); services.AddHostedService<DocumentationWatcherService>(); services.AddHostedService<DocumentCreationService>(); services.AddSingleton(provider => { var configuration = provider.GetService<GrazeDocsOptions>(); var graze = new graze.Core(new graze.Core.Parameters(configuration.ThemeFolder, configuration.PublishFolder, true, null, null, false, configuration.ConfigurationFile, configuration.AssetsFolder, null, 4, configuration.GrazeBinFolder)); return graze; }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env, GrazeDocsOptions options) { app.UseMiddleware<LivePreviewMiddleware>(); var fileOptions = new FileServerOptions() { EnableDirectoryBrowsing = true, FileProvider = new PhysicalFileProvider(options.PublishFolder), }; app.UseFileServer(fileOptions); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapHub<LivePreviewHub>("/.livepreview"); endpoints.MapDefaultControllerRoute(); }); } } }
namespace VaporStore.DataProcessor.DTOs { using System; using System.ComponentModel.DataAnnotations; public class PurchaseDto { [Required] public string Title { get; set; } [Required] public string Type { get; set; } [RegularExpression(@"^(?<productKey>[A-Z\d]{4}-[A-Z\d]{4}-[A-Z\d]{4})$")] [Required] public string ProductKey { get; set; } public DateTime Date { get; set; } [RegularExpression(@"^(?<groups>[\d]{4} [\d]{4} [\d]{4} [\d]{4})$")] [Required] public string Card { get; set; } } }
namespace Hoard.HW { internal class DeviceInfo { public int VendorId { get; } public int ProductId { get; } public string Name { get; } public DeviceInfo(int vendorId, int productId, string name) { VendorId = vendorId; ProductId = productId; Name = name; } } }
using System; namespace WPWebSockets.Server { interface IConnectionDetails { Int64 connectionID { get; set; } ConnectionType ConnectionType { get; } } }
namespace Virgin.MSGraph.Configuration { public class MicrosoftGraphConfiguration { public string TenantId { get; set; } public string AppId { get; set; } public string ClientSecret { get; set; } public string B2cExtensionAppClientId { get; set; } public string SignInType { get; set; } } }
using System.Numerics; using InfectedRose.Builder.Behaviors.External; using InfectedRose.Database; namespace InfectedRose.Builder.Behaviors { [Behavior(Template.AirMovement)] public class AirMovementBehaviorBase : BehaviorBase { [Parameter("goto_target")] public bool GotoTarget { get; set; } [Parameter("gravity_scale")] public float GravityScale { get; set; } [Parameter("ground_action")] public BehaviorBase GroundAction { get; set; } [Parameter("hit_action")] public BehaviorBase HitAction { get; set; } [Parameter("hit_action_enemy")] public BehaviorBase HitActionEnemy { get; set; } [Parameter("timeout_action")] public BehaviorBase TimeoutAction { get; set; } [Parameter("timeout_ms")] public uint TimeoutMs { get; set; } public Vector3 Velocity { get; set; } protected override void Load(AccessDatabase database) { Velocity = new Vector3 { X = GetParameter<float>(database, "x_velocity"), Y = GetParameter<float>(database, "y_velocity"), Z = GetParameter<float>(database, "z_velocity"), }; } protected override void ApplyChanges(AccessDatabase database) { SetParameter(database, "x_velocity", Velocity.X); SetParameter(database, "y_velocity", Velocity.Y); SetParameter(database, "z_velocity", Velocity.Z); } public override void Export(BehaviorXml details) { details.SetParameter("x_velocity", Velocity.X); details.SetParameter("y_velocity", Velocity.Y); details.SetParameter("z_velocity", Velocity.Z); } } }
using GenHTTP.Engine; using GenHTTP.Modules.Controllers; using GenHTTP.Modules.IO; using GenHTTP.Modules.Layouting; using GenHTTP.Modules.Practices; using GenHTTP.Modules.Websites; using Project.Controllers; using Project.Themes; namespace Project { public static class Program { public static int Main(string[] args) { var controller = Controller.From<WebsiteController>(); var resources = Resources.From(ResourceTree.FromAssembly("Static")); var app = Layout.Create() .Add("static", resources) .Fallback(controller); var website = Website.Create() .Content(app) .Theme(new ProjectTheme()); return Host.Create() .Handler(website) #if DEBUG .Development() #endif .Defaults() .Console() .Run(); } } }
using CoCo.Analyser.Classifications.CSharp; using CoCo.Test.Common; using NUnit.Framework; namespace CoCo.Test.CSharpIdentifiers.Declarations { internal class Locals : CSharpIdentifierTests { [Test] public void LocalTest() { GetContext(@"Declarations\Locals\SimpleVariable.cs").GetClassifications().AssertContains( CSharpNames.LocalVariableName.ClassifyAt(151, 6), CSharpNames.LocalVariableName.ClassifyAt(226, 9), CSharpNames.LocalVariableName.ClassifyAt(237, 9)); } [Test] public void LocalTest_ForControlVariable() { GetContext(@"Declarations\Locals\ForControlVariable.cs").GetClassifications().AssertContains( CSharpNames.LocalVariableName.ClassifyAt(160, 5), CSharpNames.LocalVariableName.ClassifyAt(171, 5), CSharpNames.LocalVariableName.ClassifyAt(183, 5)); } [Test] public void LocalTest_ForeachControlVariable() { GetContext(@"Declarations\Locals\ForeachControlVariable.cs").GetClassifications().AssertContains( CSharpNames.LocalVariableName.ClassifyAt(168, 4)); } [Test] public void LocalTest_CatchVariable() { GetContext(@"Declarations\Locals\CatchVariable.cs").GetClassifications().AssertContains( CSharpNames.LocalVariableName.ClassifyAt(256, 9)); } [Test] public void LocalTest_UsingVariable() { GetContext(@"Declarations\Locals\UsingVariable.cs").GetClassifications().AssertContains( CSharpNames.LocalVariableName.ClassifyAt(157, 6)); } [Test] public void LocalTest_RangeVariable() { GetContext(@"Declarations\Locals\RangeVariable.cs").GetClassifications().AssertContains( CSharpNames.RangeVariableName.ClassifyAt(186, 4), CSharpNames.RangeVariableName.ClassifyAt(242, 5), CSharpNames.RangeVariableName.ClassifyAt(250, 4), CSharpNames.RangeVariableName.ClassifyAt(292, 4)); } [Test] public void LocalTest_DynamicVariable() { GetContext(@"Declarations\Locals\DynamicVariable.cs").GetClassifications().AssertContains( CSharpNames.LocalVariableName.ClassifyAt(156, 5)); } } }
using AdoNetCore.AseClient.Interface; namespace AdoNetCore.AseClient { /// <summary> /// Manages a pool of identical connections. /// </summary> public sealed class AseConnectionPool { private readonly IConnectionPool _pool; internal AseConnectionPool(IConnectionPool pool) { _pool = pool; } /// <summary> /// The number of connections in the pool. /// </summary> public int Size => _pool.PoolSize; /// <summary> /// The number of connections available in the pool. /// </summary> public int Available => _pool.Available; } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace FlexWork.Models { public class WorkspaceFacility { [ForeignKey("WorkspaceId")] public virtual Workspace Workspace { get; set; } public Guid WorkspaceId { get; set; } [ForeignKey("FacilityId")] public virtual Facility Facility { get; set; } public Guid FacilityId { get; set; } } }
using Net.FreeORM.Framework.Base; using System; using Net.FreeORM.Test_Odbc.Source.DL; namespace Net.FreeORM.Test_Odbc.Source.BO { public class RejectedOrders : BaseBO { private string _OBJID; public string OBJID { set { _OBJID = value; OnPropertyChanged("OBJID"); } get { return _OBJID; } } private int _OrderId; public int OrderId { set { _OrderId = value; OnPropertyChanged("OrderId"); } get { return _OrderId; } } private int _RejectedByUser; public int RejectedByUser { set { _RejectedByUser = value; OnPropertyChanged("RejectedByUser"); } get { return _RejectedByUser; } } private DateTime _RejectedDate; public DateTime RejectedDate { set { _RejectedDate = value; OnPropertyChanged("RejectedDate"); } get { return _RejectedDate; } } private string _RejectReason; public string RejectReason { set { _RejectReason = value; OnPropertyChanged("RejectReason"); } get { return _RejectReason; } } public override string GetTableName() { return "RejectedOrders"; } public override string GetIdColumn() { return "OBJID"; } internal int Insert() { try { using(RejectedOrdersDL _rejectedordersdlDL = new RejectedOrdersDL()) { return _rejectedordersdlDL.Insert(this); } } catch { throw; } } internal int InsertAndGetId() { try { using(RejectedOrdersDL _rejectedordersdlDL = new RejectedOrdersDL()) { return _rejectedordersdlDL.InsertAndGetId(this); } } catch { throw; } } internal int Update() { try { using(RejectedOrdersDL _rejectedordersdlDL = new RejectedOrdersDL()) { return _rejectedordersdlDL.Update(this); } } catch { throw; } } internal int Delete() { try { using(RejectedOrdersDL _rejectedordersdlDL = new RejectedOrdersDL()) { return _rejectedordersdlDL.Delete(this); } } catch { throw; } } } }
/*------------------------------------------------------------------------------ <auto-generated> This code was generated from a template. Manual changes to this file may cause unexpected behavior in your application. Manual changes to this file will be overwritten if the code is regenerated. </auto-generated> ------------------------------------------------------------------------------*/ using System.Web.Http; using ODataV4 = Microsoft.AspNet.OData; using Ez.Entities.Models; namespace Ez.Web { /// <summary></summary> public static class ODataRegistrations { /// <summary></summary> public static void Register(ODataV4.Builder.ODataModelBuilder builder4) { ; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace AssemblyDefender.Common.Cryptography { /// <summary> /// Crypto stream support only one operation at a time. Read or Write but not both. Strong encryption level. /// </summary> public class StrongCryptoStream : Stream { #region Fields private const int DefaultBlockSize = 4096; private int _blockSize; private byte[] _buffer; private int _key; private int _bufferIndex; private int _bufferLength; private Stream _stream; private StrongCryptoStreamMode _mode; #endregion #region Ctors public StrongCryptoStream(Stream stream) : this(stream, StrongCryptoUtils.DefaultKey) { } public StrongCryptoStream( Stream stream, int key, StrongCryptoStreamMode mode = StrongCryptoStreamMode.Read, int blockSize = DefaultBlockSize) { if (stream == null) throw new ArgumentNullException("stream"); _stream = stream; _key = key; _mode = mode; _blockSize = (blockSize > 0 ? blockSize : DefaultBlockSize); _buffer = new byte[_blockSize]; switch (_mode) { case StrongCryptoStreamMode.Read: { if (!_stream.CanRead) { throw new ArgumentException(SR.StreamReadNotSupported); } } break; case StrongCryptoStreamMode.Write: { if (!_stream.CanWrite) { throw new ArgumentException(SR.StreamWriteNotSupported); } } break; default: throw new NotImplementedException(); } } #endregion #region Properties public override bool CanRead { get { return _mode == StrongCryptoStreamMode.Read; } } public override bool CanWrite { get { return _mode == StrongCryptoStreamMode.Write; } } public override bool CanSeek { get { return _mode == StrongCryptoStreamMode.Read && _stream.CanSeek; } } public override bool CanTimeout { get { return _stream.CanTimeout; } } public override long Length { get { return _stream.Length; } } public override long Position { get { return _stream.Position - _bufferLength + _bufferIndex; } set { if (!CanSeek) { throw new IOException(SR.StreamSeekNotSupported); } if (value < 0) { throw new IOException(SR.StreamReadOutOfBound); } long position = (value / _blockSize) * _blockSize; _bufferIndex = (int)(value - position); _bufferLength = 0; _stream.Position = position; } } public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } public StrongCryptoStreamMode Mode { get { return _mode; } } public int BlockSize { get { return _blockSize; } } #endregion #region Methods public override int Read(byte[] buffer, int offset, int count) { if (!CanRead) { throw new IOException(SR.StreamReadNotSupported); } if (_bufferLength < _blockSize) { if (_bufferLength == 0) { int readLen = _stream.Read(_buffer, 0, _blockSize); if (readLen == 0) return 0; _bufferLength = readLen; StrongCryptoUtils.Decrypt(_buffer, _key, 0, _bufferLength); } if (_bufferIndex >= _bufferLength) return 0; } int readCount = 0; while (count > 0) { if (_bufferIndex == _bufferLength) { _bufferIndex = 0; _bufferLength = _stream.Read(_buffer, 0, _blockSize); if (_bufferLength == 0) break; StrongCryptoUtils.Decrypt(_buffer, _key, 0, _bufferLength); } int size = _bufferLength - _bufferIndex; if (size > count) size = count; Buffer.BlockCopy(_buffer, _bufferIndex, buffer, offset, size); count -= size; offset += size; readCount += size; _bufferIndex += size; } return readCount; } public override void Write(byte[] buffer, int offset, int count) { if (!CanWrite) { throw new IOException(SR.StreamWriteNotSupported); } while (count > 0) { if (_bufferIndex == _blockSize) { StrongCryptoUtils.Encrypt(_buffer, _key, 0, _bufferIndex); _stream.Write(_buffer, 0, _bufferIndex); _bufferIndex = 0; } int size = _blockSize - _bufferIndex; if (size > count) size = count; Buffer.BlockCopy(buffer, offset, _buffer, _bufferIndex, size); count -= size; offset += size; _bufferIndex += size; } } public override long Seek(long offset, SeekOrigin origin) { switch (origin) { case SeekOrigin.Begin: { Position = offset; } break; case SeekOrigin.Current: { Position += offset; } break; case SeekOrigin.End: { Position = Length + offset; } break; default: throw new ArgumentException("InvalidSeekOrigin"); } return Position; } public override void SetLength(long value) { if (!CanWrite) { throw new IOException(SR.StreamWriteNotSupported); } _stream.SetLength(value); } public override void Flush() { } protected override void Dispose(bool disposing) { try { if (disposing) { switch (_mode) { case StrongCryptoStreamMode.Write: { if (_bufferIndex > 0) { StrongCryptoUtils.Encrypt(_buffer, _key, 0, _bufferIndex); _stream.Write(_buffer, 0, _bufferIndex); _bufferIndex = 0; } } break; } _stream.Close(); } _buffer = null; _stream = null; } finally { base.Dispose(disposing); } } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ArrowPointer : MonoBehaviour { public Transform[] arrows = new Transform[4]; [HideInInspector] public Trainer trainer; [HideInInspector] public int row, col; public void Start() { trainer = FindObjectOfType<Trainer>(); } public void ChangeDirections() { for (int i = 0; i < 4; ++i) { if (trainer.pq[row, col, i].Count() > 0) { int direction = trainer.pq[row, col, i].Peek().direction; arrows[i].rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y, 90.0f * direction); } else arrows[i].GetComponent<SpriteRenderer>().enabled = false; } } }
using System; using System.Collections.Generic; using System.Reflection; using CodeCampServer.Core; using CodeCampServer.Core.Common; using CodeCampServer.DependencyResolution; using CodeCampServer.Infrastructure.NHibernate; using CodeCampServer.Infrastructure.NHibernate.DataAccess; using CodeCampServer.UnitTests; using NHibernate; using NUnit.Framework; using StructureMap; namespace CodeCampServer.IntegrationTests.Infrastructure.DataAccess { [TestFixture] public abstract class IntegrationTestBase : TestBase { private readonly IDictionary<Type, Object> injectedInstances = new Dictionary<Type, Object>(); private IUnitOfWork _unitOfWork; [TestFixtureSetUp] public virtual void FixtureSetup() { DependencyRegistrar.EnsureDependenciesRegistered(); SessionBuilder.GetDefault = () => null; } [SetUp] public virtual void Setup() { injectedInstances.Clear(); ObjectFactory.Inject(typeof (IUnitOfWork), UnitOfWork); } protected virtual ISession GetSession() { return new SessionBuilder().GetSession(); } protected virtual void CommitChanges() { new SessionBuilder().GetSession().Flush(); } protected IUnitOfWork UnitOfWork { get { if(_unitOfWork == null) { _unitOfWork = new UnitOfWork(new SessionBuilder()); } return _unitOfWork; } } protected TPluginType GetInstance<TPluginType>() { ExplicitArgsExpression expression = ObjectFactory.With(_unitOfWork); injectedInstances.Keys.ForEach(type => { expression = expression.With(type, injectedInstances[type]); }); return expression.GetInstance<TPluginType>(); } /// <summary> /// Checks for equality and that all properties' values are equal. /// </summary> /// <param name="obj1"></param> /// <param name="obj2"></param> protected static void AssertObjectsMatch(object obj1, object obj2) { Assert.AreNotSame(obj1, obj2); Assert.AreEqual(obj1, obj2); PropertyInfo[] infos = obj1.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (var info in infos) { object value1 = info.GetValue(obj1, null); object value2 = info.GetValue(obj2, null); Assert.AreEqual(value1, value2, string.Format("Property {0} doesn't match", info.Name)); } } } }
@page @model FytSoa.Web.Pages.FytAdmin.Cms.ArticleTopModel @{ ViewData["Title"] = "文章点击排行"; Layout = AdminLayout.Pjax(HttpContext); } <div id="container"> <div class="list-wall"> <div class="layui-form list-search"> <div class="layui-inline"> <input class="layui-input" id="key" autocomplete="off" placeholder="请输入关键字查询"> </div> <div class="layui-inline"> <select id="attr" lay-search=""> <option value="">全部</option> <option value="IsTop">推荐</option> <option value="IsHot">热点</option> <option value="IsScroll">滚动</option> <option value="IsSlide">幻灯</option> <option value="IsComment">是否评论</option> <option value="IsWap">发布移动端</option> <option value="IsLink">转向链接</option> </select> </div> <div class="layui-inline" style="width:100px;"> <input type="checkbox" checked="checked" name="close" lay-filter="switch" lay-skin="switch" lay-text="已审核|未审核"> </div> <button type="button" class="layui-btn layui-btn-sm" data-type="toolSearch"><i class="layui-icon layui-icon-search"></i> 搜索</button> </div> <table class="layui-hide" id="tablist" lay-filter="tool"></table> </div> <script type="text/html" id="switchTpl"> <input type="checkbox" name="status" value="{{d.id}}" lay-skin="switch" lay-text="已审核|未审核" lay-filter="statusedit" {{ d.audit==1?'checked':''}}> </script> <script> layui.config({ base: '/themes/js/modules/' }).use(['table', 'layer', 'jquery', 'common', 'form'], function () { var table = layui.table, layer = layui.layer, $ = layui.jquery, os = layui.common, form = layui.form; form.render(); table.render({ elem: '#tablist', headers: os.getToken(), url: '/api/article/getpages', cols: [ [ { type: 'checkbox', fixed: 'left' }, { field: 'title', title: '标题', fixed: 'left' }, { field: 'hits', width: 100, title: '总点击量' }, { field: 'monthHits', width: 100, title: '月点击量' }, { field: 'weedHits', width: 100, title: '周点击量' }, { field: 'weedHits', width: 100, title: '日点击量' }, { field: 'dayHits', width: 100, title: '点击量' }, { field: 'lastHitDate', width: 200, title: '最后点击时间', sort: true } ] ], page: true, id: 'tables', where: { guid: '1', types: -1 } }); var type = 0, active = { reload: function () { table.reload('tables', { page: { curr: 1 }, where: { guid: '1', where: $("#attr").val(), key: $('#key').val(), types: type }, done: function () { } }); }, toolSearch: function () { active.reload(); } }; $('.list-search .layui-btn').on('click', function () { var type = $(this).data('type'); active[type] ? active[type].call(this) : ''; }); }); </script> </div>
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; namespace LegacyEnterpriseWebApp.Controllers { [RoutePrefix("api/reports")] public class ReportsController : ApiController { [HttpPost] [Route("{name}")] public Task<HttpResponseMessage> Post(string name) { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(Guid.NewGuid().ToString()); return Task.FromResult(response); } } }
//----------------------------------------------------------------------------- // Life.cs // // AddictionSoftware //----------------------------------------------------------------------------- using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Audio; namespace Halcyon { class ExtraLife : Powerup { // Animation public Animation animLife; // Velocity private Vector2 lifeVelocity; // Collection Animation private Animation playerExtraLife; // Constructor public ExtraLife(Texture2D lifeTexture) : base(lifeTexture) { animLife = new Animation(); playerExtraLife = new Animation(); powerSound = "audio/lol"; lifeVelocity = new Vector2(0f, 5f); } public override void Update(GameTime gameTime) { animLife.Position += lifeVelocity; if (animLife.Position.Y > (Game.current.ScreenManager.GraphicsDevice.Viewport.Height + animLife.FrameHeight)) animLife.Active = false; if (animLife.Active) { if (animLife.CollisionCheck(Game.current.player.playerSprite)) { // Player has picked up the power-up // Activate shield playerExtraLife.Initialize(Game.current.content.Load<Texture2D>("Player/life"), Game.current.player.playerSprite.Position, 128, 128, 16, 45, Color.White, 1f, false); // Give player an extra life Game.current.player.PlayerLives++; animLife.Active = false; // Sound Effect lifeEffect = new Effect( Game.current.content.Load<SoundEffect>( "Sound/life" ) ); lifeEffect.Play(); } } playerExtraLife.Position = Game.current.player.playerSprite.Position; playerExtraLife.Update(gameTime); base.Update(gameTime); } public override void Draw(SpriteBatch spriteBatch) { playerExtraLife.Draw(spriteBatch); base.Draw(spriteBatch); } // Create and initialize the power up public override void CreatePower(Vector2 position) { animLife.Initialize(powerTexture, position, 128, 128, 16, 32, Color.White, 0.7f, true); powerList.Add(animLife); } } }
using System; using Octo.Core.Cqrs; using PushNotifications.Domain.AggregateRoots; using PushNotifications.Domain.Commands; using PushNotifications.Services; namespace PushNotifications.Domain.CommandHandlers { public class SendPushNotificationCommandHandler : ICommandHandler<SendPushNotificationCommand> { private readonly IDomainRepository<PushNotification> _domainRepository; private readonly IPushNotificationService _pushNotificationService; public SendPushNotificationCommandHandler( IDomainRepository<PushNotification> domainRepository, IPushNotificationService pushNotificationService) { _domainRepository = domainRepository; _pushNotificationService = pushNotificationService; } public void Handle(SendPushNotificationCommand command) { if (command == null) throw new ArgumentNullException("command"); var pushNotification = _domainRepository.GetById(command.PushNotificationId); var paymentId = pushNotification.PaymentId; var url = _pushNotificationService.GetUrlFor(paymentId, pushNotification.Url); pushNotification.SetUrlTo(url); _domainRepository.Save(pushNotification); string response; if (_pushNotificationService.TrySend(url, out response)) { pushNotification.Succeed(response); _domainRepository.Save(pushNotification); } else { // description only? // NotSucceed? } // todo } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using Livet; using Livet.Commands; using Livet.Messaging; using Livet.Messaging.IO; using Livet.EventListeners; using Livet.Messaging.Windows; using ProgressiveTweet.Models; namespace ProgressiveTweet.ViewModels { public class AuthenticationViewModel : ViewModel { private Authentication Source { get; set; } public string Pin { get { return Source.Pin; } set { Source.Pin = value; AuthenticateCommand.RaiseCanExecuteChanged(); } } public bool IsAuthenticating { get { return _isAuthenticating; } set { _isAuthenticating = value; AuthenticateCommand.RaiseCanExecuteChanged(); } } private bool _isAuthenticating; public AuthenticationViewModel() { Source = new Authentication(); } public void Initialize() { var listener = new PropertyChangedEventListener(Source, (sender, e) => RaisePropertyChanged(e.PropertyName)); this.CompositeDisposable.Add(listener); Task.Run(() => { Source.CreateSession(); System.Diagnostics.Process.Start(Source.CurrentSession.AuthorizeUri.AbsoluteUri); }); } #region AuthenticateCommand private ViewModelCommand _AuthenticateCommand; public ViewModelCommand AuthenticateCommand { get { if (_AuthenticateCommand == null) { _AuthenticateCommand = new ViewModelCommand(Authenticate, CanAuthenticate); } return _AuthenticateCommand; } } public bool CanAuthenticate() { return !string.IsNullOrWhiteSpace(Pin) && !IsAuthenticating; } public void Authenticate() { IsAuthenticating = true; Task.Run(() => { Source.GenerateToken(); if (Source.IsTokenGenerated) { Model.Instance.CurrentToken = Source.GeneratedToken; Messenger.Raise(new WindowActionMessage("Close")); } else { Messenger.Raise(new InformationMessage() { MessageKey = "Information", Text = "認証できませんでした。\n再試行してください。", Image = System.Windows.MessageBoxImage.Error }); } IsAuthenticating = false; }); } #endregion } }
using System; using FiveChecks.Applic.Common; using LanguageExt; using Microsoft.Toolkit.Uwp.Notifications; namespace FiveChecks.Applic.ToastTemplates { public class ActionDismissToastContentInfo : Record<ActionDismissToastContentInfo> { public BindableString Greeting { get; } public string Title { get; } public string CompanyName { get; } public string ContentSection1 { get; } public string ContentSection2 { get; } public Option<string> ContentSection3 { get; } public string Action { get; } public string GroupName { get; } public string ActionButtonContent { get; } public string NotNowButtonContent { get; } public string NotNowAction { get; } public ToastActivationType ActionActivationType { get; } public ActionDismissToastContentInfo(BindableString greeting, string title, string contentSection1, string contentSection2, string action, ToastActivationType actionActivationType, string actionButtonContent, string notNowButtonContent, string notNowAction, string groupName, Option<string> contentSection3, string companyName) { Greeting = greeting; Title = title; ContentSection1 = contentSection1; ContentSection2 = contentSection2; Action = action; ActionButtonContent = actionButtonContent; NotNowButtonContent = notNowButtonContent; NotNowAction = notNowAction; GroupName = groupName; ContentSection3 = contentSection3; CompanyName = companyName; ActionActivationType = actionActivationType; } } }
using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebApiCore.Extensions { public static class IResultExtensionsExtensions { public static IResult ContentStatus(this IResultExtensions resultExtensions, string content, string contentType = System.Net.Mime.MediaTypeNames.Application.Json, System.Text.Encoding? contentEncoding = null, int statusCode = 200) { return new ContentStatusResult(content, contentType, contentEncoding, statusCode); } } public class ContentStatusResult : IResult { private readonly string content; private readonly string contentType; private readonly Encoding contentEncoding; private readonly int statusCode; public ContentStatusResult(string content, string contentType = System.Net.Mime.MediaTypeNames.Application.Json, System.Text.Encoding? contentEncoding = null, int statusCode = 200) { this.content = content; this.contentType = contentType; this.contentEncoding = contentEncoding ?? Encoding.UTF8; this.statusCode = statusCode; } public Task ExecuteAsync(HttpContext httpContext) { httpContext.Response.StatusCode = statusCode; httpContext.Response.ContentType = contentType; httpContext.Response.ContentLength = contentEncoding.GetByteCount(content); return httpContext.Response.WriteAsync(content, contentEncoding); } } }
using System; namespace TtxFromTS { /// <summary> /// Exit codes used by the application. /// </summary> public enum ExitCodes { Success = 0, InvalidArgs = 1, InvalidService = 2, InvalidPID = 3, TSError = 4, Unspecified = 5, InvalidServiceID = 6, TeletextPIDNotFound = 7 } }
namespace HomeAPI.Backend.Options { public class HueOptions { public string BridgeIP { get; set; } public int BridgePort { get; set; } public string UserKey { get; set; } public HueOptions() { } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using ReactiveApp; using ReactiveApp.App; using Splat; using TestApp.Services; using TestApp.ViewModels; namespace TestApp { public class TestApp : ReactiveApplication { public override void Initialize() { base.Initialize(); //Register this.RegisterStartup<MainViewModel>(); Locator.CurrentMutable.Register<ISampleDataService>(c => new SampleDataService()); Locator.CurrentMutable.Register<MainViewModel>(c => new MainViewModel(c.GetService<ISampleDataService>())); } } }
using FCommerce.Core.Connection; namespace FCommerce.Core.Command { public interface ICommand { int? Execute(IConnection connection); } }
using UnityEngine; using System.Collections; public class CameraRotate : MonoBehaviour { public GameObject rotationpoint; void Start() { Time.timeScale = 1; } // Update is called once per frame void Update() { gameObject.transform.Rotate(new Vector3(0, -1f, 0) * 10.0f * Time.deltaTime); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace AdventOfCode.Y2019.Day25; [ProblemName("Cryostasis")] class Solution : Solver { public object PartOne(string input) { var securityRoom = "== Security Checkpoint =="; var icm = new IntCodeMachine(input); var description = icm.Run().ToAscii(); VisitRooms(securityRoom, icm, description, args => { foreach (var item in args.items) { if (item != "infinite loop") { var takeCmd = "take " + item; var clone = icm.Clone(); clone.Run(takeCmd); if (!clone.Halted() && Inventory(clone).Contains(item)) { icm.Run(takeCmd); } } } return null; }); var door = VisitRooms(securityRoom, icm, description, args => args.room == securityRoom ? args.doors.Single(door => door != ReverseDir(args.doorTaken)) : null); Random r = new Random(); void TakeOrDrop(string cmd, List<string> from, List<string> to) { var i = r.Next(from.Count); var item = from[i]; from.RemoveAt(i); to.Add(item); icm.Run(cmd + " " + item); } var inventory = Inventory(icm).ToList(); var floor = new List<string>(); while (true) { var output = icm.Run(door).ToAscii(); if (output.Contains("heavier")) { TakeOrDrop("take", floor, inventory); } else if (output.Contains("lighter")) { TakeOrDrop("drop", inventory, floor); } else { return long.Parse(Regex.Match(output, @"\d+").Value); } } } List<string> directions = new List<string>() { "south", "east", "west", "north" }; string ReverseDir(string direction) => directions[3 - directions.IndexOf(direction)]; string VisitRooms( string securityRoom, IntCodeMachine icm, string description, Func<(IEnumerable<string> items, string room, string doorTaken, IEnumerable<string> doors), string> callback ) { var roomsSeen = new HashSet<string>(); string DFS(string description, string doorTaken) { var room = description.Split("\n").Single(x => x.Contains("==")); var listing = GetListItems(description).ToHashSet(); var doors = listing.Intersect(directions); var items = listing.Except(doors); if (!roomsSeen.Contains(room)) { roomsSeen.Add(room); var res = callback((items, room, doorTaken, doors)); if (res != null) { return res; } if (room != securityRoom) { foreach (var door in doors) { res = DFS(icm.Run(door).ToAscii(), door); if (res != null) { return res; } icm.Run(ReverseDir(door)); } } } return null; } return DFS(description, null); } IEnumerable<string> Inventory(IntCodeMachine icm) => GetListItems(icm.Run("inv").ToAscii()); IEnumerable<string> GetListItems(string description) => from line in description.Split("\n") where line.StartsWith("- ") select line.Substring(2); }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MiniMapManager : MonoBehaviour { public GameObject seedPrefab; public Canvas canvas; public Image mapImage; public Transform koroksParent; public Transform mapSeedParent; public long currentNumberOfKoroks; public long totalNumberOfKoroks; public Text completionText; public Text completionText2; // Use this for initialization void Start () { /* foreach (Transform korok in koroksParent) { if (korok.GetComponent(typeof(KorokBehaviour)) != null && korok.GetComponent<KorokBehaviour>().isFound) { DisplayKorok(korok.GetComponent<KorokBehaviour>().xID, korok.GetComponent<KorokBehaviour>().yID); } } UpdateCompletion();*/ } public void DisplayKorok(int tilex, int tiley) { float xF = tilex / Mathf.Pow(2, MapGeneratorOSM.instance.zoomLevel); float yF = tiley / Mathf.Pow(2, MapGeneratorOSM.instance.zoomLevel); Vector2 sizeDelta = mapImage.GetComponent<RectTransform>().sizeDelta; Vector2 canvasScale = new Vector2(canvas.transform.localScale.x, canvas.transform.localScale.y); Vector2 imageSize = new Vector2(sizeDelta.x * canvasScale.x, sizeDelta.y * canvasScale.y); float positionX = xF * imageSize.x; float positionY = yF * imageSize.y; GameObject seed = Instantiate(seedPrefab, Vector3.zero, Quaternion.identity); seed.transform.SetParent(mapSeedParent, false); } public void UpdateCompletion() { float completion = currentNumberOfKoroks / totalNumberOfKoroks; string completionString = completion.ToString() + "/100%"; completionText.text = completionString; completionText2.text = completionString; } // Update is called once per frame void Update () { } }
using GateMQ.Db.Converters; namespace GateMQ.Db.Drivers.SqlServer { public class SqlServerGateDbConverter : AdoNetGateDbConverter { public override string GenerateLastInsertIdQuery() { return "SELECT SCOPE_IDENTITY();"; } public override string GeneratePagingClause(int limit, long offset) { return $" OFFSET {offset} ROWS FETCH FIRST {limit} ROWS ONLY"; } public override string ConvertAggregateAverage(string convertedArgument, AdoNetGateDbConverted command) { return $"AVG(CAST({convertedArgument} AS float))"; } } }
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia.Controls.Utils; using Xunit; namespace Avalonia.Controls.UnitTests { public class GridLayoutTests { private const double Inf = double.PositiveInfinity; [Theory] [InlineData("100, 200, 300", 0d, 0d, new[] { 0d, 0d, 0d })] [InlineData("100, 200, 300", 800d, 600d, new[] { 100d, 200d, 300d })] [InlineData("100, 200, 300", 600d, 600d, new[] { 100d, 200d, 300d })] [InlineData("100, 200, 300", 400d, 400d, new[] { 100d, 200d, 100d })] public void MeasureArrange_AllPixelLength_Correct(string length, double containerLength, double expectedDesiredLength, IList<double> expectedLengthList) { TestRowDefinitionsOnly(length, containerLength, expectedDesiredLength, expectedLengthList); } [Theory] [InlineData("*,2*,3*", 0d, 0d, new[] { 0d, 0d, 0d })] [InlineData("*,2*,3*", 600d, 0d, new[] { 100d, 200d, 300d })] public void MeasureArrange_AllStarLength_Correct(string length, double containerLength, double expectedDesiredLength, IList<double> expectedLengthList) { TestRowDefinitionsOnly(length, containerLength, expectedDesiredLength, expectedLengthList); } [Theory] [InlineData("100,2*,3*", 0d, 0d, new[] { 0d, 0d, 0d })] [InlineData("100,2*,3*", 600d, 100d, new[] { 100d, 200d, 300d })] [InlineData("100,2*,3*", 100d, 100d, new[] { 100d, 0d, 0d })] [InlineData("100,2*,3*", 50d, 50d, new[] { 50d, 0d, 0d })] public void MeasureArrange_MixStarPixelLength_Correct(string length, double containerLength, double expectedDesiredLength, IList<double> expectedLengthList) { TestRowDefinitionsOnly(length, containerLength, expectedDesiredLength, expectedLengthList); } [Theory] [InlineData("100,200,Auto", 0d, 0d, new[] { 0d, 0d, 0d })] [InlineData("100,200,Auto", 600d, 300d, new[] { 100d, 200d, 0d })] [InlineData("100,200,Auto", 300d, 300d, new[] { 100d, 200d, 0d })] [InlineData("100,200,Auto", 200d, 200d, new[] { 100d, 100d, 0d })] [InlineData("100,200,Auto", 100d, 100d, new[] { 100d, 0d, 0d })] [InlineData("100,200,Auto", 50d, 50d, new[] { 50d, 0d, 0d })] public void MeasureArrange_MixAutoPixelLength_Correct(string length, double containerLength, double expectedDesiredLength, IList<double> expectedLengthList) { TestRowDefinitionsOnly(length, containerLength, expectedDesiredLength, expectedLengthList); } [Theory] [InlineData("*,2*,Auto", 0d, 0d, new[] { 0d, 0d, 0d })] [InlineData("*,2*,Auto", 600d, 0d, new[] { 200d, 400d, 0d })] public void MeasureArrange_MixAutoStarLength_Correct(string length, double containerLength, double expectedDesiredLength, IList<double> expectedLengthList) { TestRowDefinitionsOnly(length, containerLength, expectedDesiredLength, expectedLengthList); } [Theory] [InlineData("*,200,Auto", 0d, 0d, new[] { 0d, 0d, 0d })] [InlineData("*,200,Auto", 600d, 200d, new[] { 400d, 200d, 0d })] [InlineData("*,200,Auto", 200d, 200d, new[] { 0d, 200d, 0d })] [InlineData("*,200,Auto", 100d, 100d, new[] { 0d, 100d, 0d })] public void MeasureArrange_MixAutoStarPixelLength_Correct(string length, double containerLength, double expectedDesiredLength, IList<double> expectedLengthList) { TestRowDefinitionsOnly(length, containerLength, expectedDesiredLength, expectedLengthList); } [SuppressMessage("ReSharper", "ParameterOnlyUsedForPreconditionCheck.Local")] private static void TestRowDefinitionsOnly(string length, double containerLength, double expectedDesiredLength, IList<double> expectedLengthList) { // Arrange var layout = new GridLayout(new RowDefinitions(length)); // Measure - Action & Assert var measure = layout.Measure(containerLength); Assert.Equal(expectedDesiredLength, measure.DesiredLength); Assert.Equal(expectedLengthList, measure.LengthList); // Arrange - Action & Assert var arrange = layout.Arrange(containerLength, measure); Assert.Equal(expectedLengthList, arrange.LengthList); } [Theory] [InlineData("100, 200, 300", 600d, new[] { 100d, 200d, 300d }, new[] { 100d, 200d, 300d })] [InlineData("*,2*,3*", 0d, new[] { Inf, Inf, Inf }, new[] { 0d, 0d, 0d })] [InlineData("100,2*,3*", 100d, new[] { 100d, Inf, Inf }, new[] { 100d, 0d, 0d })] [InlineData("100,200,Auto", 300d, new[] { 100d, 200d, 0d }, new[] { 100d, 200d, 0d })] [InlineData("*,2*,Auto", 0d, new[] { Inf, Inf, 0d }, new[] { 0d, 0d, 0d })] [InlineData("*,200,Auto", 200d, new[] { Inf, 200d, 0d }, new[] { 0d, 200d, 0d })] public void MeasureArrange_InfiniteMeasure_Correct(string length, double expectedDesiredLength, IList<double> expectedMeasureList, IList<double> expectedArrangeList) { // Arrange var layout = new GridLayout(new RowDefinitions(length)); // Measure - Action & Assert var measure = layout.Measure(Inf); Assert.Equal(expectedDesiredLength, measure.DesiredLength); Assert.Equal(expectedMeasureList, measure.LengthList); // Arrange - Action & Assert var arrange = layout.Arrange(measure.DesiredLength, measure); Assert.Equal(expectedArrangeList, arrange.LengthList); } [Theory] [InlineData("Auto,*,*", new[] { 100d, 100d, 100d }, 600d, 300d, new[] { 100d, 250d, 250d })] public void MeasureArrange_ChildHasSize_Correct(string length, IList<double> childLengthList, double containerLength, double expectedDesiredLength, IList<double> expectedLengthList) { // Arrange var lengthList = new ColumnDefinitions(length); var layout = new GridLayout(lengthList); layout.AppendMeasureConventions( Enumerable.Range(0, lengthList.Count).ToDictionary(x => x, x => (x, 1)), x => childLengthList[x]); // Measure - Action & Assert var measure = layout.Measure(containerLength); Assert.Equal(expectedDesiredLength, measure.DesiredLength); Assert.Equal(expectedLengthList, measure.LengthList); // Arrange - Action & Assert var arrange = layout.Arrange(containerLength, measure); Assert.Equal(expectedLengthList, arrange.LengthList); } [Theory] [InlineData(Inf, 250d, new[] { 100d, Inf, Inf }, new[] { 100d, 50d, 100d })] [InlineData(400d, 250d, new[] { 100d, 100d, 200d }, new[] { 100d, 100d, 200d })] [InlineData(325d, 250d, new[] { 100d, 75d, 150d }, new[] { 100d, 75d, 150d })] [InlineData(250d, 250d, new[] { 100d, 50d, 100d }, new[] { 100d, 50d, 100d })] [InlineData(160d, 160d, new[] { 100d, 20d, 40d }, new[] { 100d, 20d, 40d })] public void MeasureArrange_ChildHasSizeAndHasMultiSpan_Correct( double containerLength, double expectedDesiredLength, IList<double> expectedMeasureLengthList, IList<double> expectedArrangeLengthList) { var length = "100,*,2*"; var childLengthList = new[] { 150d, 150d, 150d }; var spans = new[] { 1, 2, 1 }; // Arrange var lengthList = new ColumnDefinitions(length); var layout = new GridLayout(lengthList); layout.AppendMeasureConventions( Enumerable.Range(0, lengthList.Count).ToDictionary(x => x, x => (x, spans[x])), x => childLengthList[x]); // Measure - Action & Assert var measure = layout.Measure(containerLength); Assert.Equal(expectedDesiredLength, measure.DesiredLength); Assert.Equal(expectedMeasureLengthList, measure.LengthList); // Arrange - Action & Assert var arrange = layout.Arrange( double.IsInfinity(containerLength) ? measure.DesiredLength : containerLength, measure); Assert.Equal(expectedArrangeLengthList, arrange.LengthList); } } }
using System; using System.Collections.Generic; using System.Text; namespace monstruos.hl.compiler.shared.Language { public abstract class MetaObject { public enum MetaType { Interface, Class, Property, Method, Field, Struct, Enum } public string Name { get; set; } public abstract MetaType Type { get; } } }
namespace SFM.Importer.Configuration { public class AppSettings { public string Token { get; internal set; } public string Folder { get; set; } public string UploadAPI { get; set; } public int UploadThreads { get; set; } } }
using Dapper; using FxConsoleApp.Utils; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; namespace FxConsoleApp.ORM { public class DapperSqlHelper { public static List<T> GetList<T>(string query, object param = null) { using (var conn = ConfigUtil.GetOwnCon()) { return conn.Query<T>(query, param).ToList(); } } public static DataTable GetDateTable(string sql, object param = null) { using (var conn = ConfigUtil.GetOwnCon()) { var dt = new DataTable(); var reader = conn.ExecuteReader(sql); dt.Load(reader); return dt; } } public static DataSet GetDataSet(string sql, params SqlParameter[] sqlParameters) { var ds = new DataSet(); using (var conn = ConfigUtil.GetOwnCon()) { var cmd = new SqlCommand(sql, conn); if (sqlParameters != null) { foreach (var parameter in sqlParameters) { cmd.Parameters.Add(parameter); } } var da = new SqlDataAdapter(cmd); da.Fill(ds); } return ds; } public static int Execute(string sql, object param = null) { using (var conn = ConfigUtil.GetOwnCon()) { return conn.Execute(sql, param); } } } }
#region Using directives using System; using System.Configuration; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Xml.Xsl; using log4net; using Commanigy.Iquomi.Data; using Commanigy.Iquomi.Ui; #endregion namespace Commanigy.Iquomi.Web { /// <summary> /// /// </summary> public partial class PackageItemCreatePage : Commanigy.Iquomi.Web.WebPage { private DbService service; private DbPackage package_; protected override void OnInit(EventArgs e) { base.OnInit(e); package_ = DbPackage.DbRead(GetInt32("Package.Id"), Profile.AuthorId, Profile.LanguageId); service = DbService.DbRead(package_.ServiceId, Profile.AuthorId, Profile.LanguageId); } protected void Page_Load(object sender, System.EventArgs e) { UcPackageTab.Package = package_; UcPackageTab.Service = service; } protected void btnCreate_Click(object sender, System.EventArgs e) { if (!this.IsValid) { return; } DbPackageItem it = new DbPackageItem(); it.PackageId = package_.Id; if (PackageItem.Upload.PostedFile != null) { log.Debug("File was posted with a size of " + PackageItem.Upload.PostedFile.ContentLength); it.Name = System.IO.Path.GetFileName(PackageItem.Upload.PostedFile.FileName); it.Size = PackageItem.Upload.PostedFile.ContentLength; it.Type = PackageItem.Upload.PostedFile.ContentType; byte[] file = new byte[PackageItem.Upload.PostedFile.ContentLength]; PackageItem.Upload.PostedFile.InputStream.Read(file, 0, file.Length); it.Data = file; } else { it.Name = PackageItem.Name; it.Size = PackageItem.Size; it.Type = PackageItem.Type; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { System.IO.StreamWriter sw = new System.IO.StreamWriter(ms); sw.Write(PackageItem.Data); sw.Close(); it.Data = ms.ToArray(); } } log.Debug("Creating package_item with package_id: " + it.PackageId); it.DbCreate(); if (it.Id > 0) { this.Redirect("package.items.aspx", new object[] { package_.Id }); } } } }
using System; using System.Collections.Immutable; namespace ExRam.Gremlinq.Core { public interface IGremlinQueryAdmin { IGremlinQuery<object> ConfigureSteps(Func<IImmutableList<Step>, IImmutableList<Step>> configurator); TTargetQuery ChangeQueryType<TTargetQuery>() where TTargetQuery : IGremlinQuery; IImmutableList<Step> Steps { get; } IGremlinQueryEnvironment Environment { get; } } }
using Microsoft.EntityFrameworkCore; using MultiDataSourceGenericRepository.Interfaces; using MultiDataSourceGenericRepository.Models; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace MultiDataSourceGenericRepository.Repositories { public class RepositoryBase<T> : IRepositoryBase<T> where T : EntityBase { private DbContext _dbContext; private DbSet<T> _dbSet; public RepositoryBase(DbContext dbContext) { _dbContext = dbContext; _dbSet = _dbContext.Set<T>(); } public virtual T GetById(int id) { return _dbSet.Find(id); } public virtual T GetOne(Expression<Func<T, bool>> predicate) { return _dbSet.SingleOrDefault(predicate); } public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> predicate) { return _dbSet.Where(predicate); } public virtual IEnumerable<T> GetAll() { return _dbSet.ToList(); } public virtual void Add(T entity) { _dbSet.Add(entity); Commit(); } public virtual void Update(T entity) { _dbSet.Attach(entity); _dbContext.Entry(entity).State = EntityState.Modified; Commit(); } public virtual void Delete(T entity) { _dbSet.Remove(entity); Commit(); } protected virtual void Commit() { _dbContext.SaveChanges(); } } }
using System; using WeatherAPI.NET.Entities; namespace Sample.Extending { public class CustomAstronomyResponseEntity : AstronomyResponseEntity { private readonly string _message = "I'm a message from a custom entity!"; /// <summary> /// Does something custom. /// </summary> public void DoSomethingCustom() { Console.WriteLine(_message); } } }
using UnityEngine; namespace Asteroids { public interface IWeaponBehaviour { WeaponType Type { get; } void DoMovement(MovementController movementController); } }
using Aquality.Selenium.Core.Localization; using Aquality.Selenium.Core.Logging; using System; using System.Diagnostics; using System.Linq; namespace Aquality.WinAppDriver.Utilities { /// <summary> /// Implementation of <see cref="IProcessManager"/> /// </summary> public class ProcessManager : IProcessManager { private readonly ILocalizedLogger localizedLogger; public ProcessManager(ILocalizedLogger localizedLogger) { this.localizedLogger = localizedLogger; } public bool IsExecutableRunning(string name) { var pureName = GetPureExecutableName(name); return IsProcessRunning(pureName); } public bool IsProcessRunning(string name) { return Process.GetProcessesByName(name).Any(); } public bool TryToStopExecutables(string name) { var pureName = GetPureExecutableName(name); return TryToStopProcesses(pureName); } public bool TryToStopProcesses(string name) { localizedLogger.Info("loc.processes.stop", name); var processes = Process.GetProcessesByName(name); var result = processes.Any(); if (!result) { localizedLogger.Warn("loc.processes.notfound", name); } foreach (var process in processes) { try { process.Kill(); process.WaitForExit(); process.Dispose(); } catch (SystemException e) { Logger.Instance.Warn(e.Message); result = false; } } return result; } private static string GetPureExecutableName(string executableName) { return executableName.Replace(".exe", string.Empty); } public Process Start(string fileName) { localizedLogger.Info("loc.processes.start", fileName); return Process.Start(fileName); } } }
using System; using SolidWorks.Interop.sldworks; using System.Threading.Tasks; namespace AngelSix.SolidDna { /// <summary> /// Represents a SolidWorks Taskpane /// </summary> public class Taskpane : SolidDnaObject<ITaskpaneView> { #region Constructor /// <summary> /// Default constructor /// </summary> public Taskpane(ITaskpaneView taskpane) : base(taskpane) { } #endregion #region Public Methods /// <summary> /// Adds a control (Windows <see cref="System.Windows.Forms.UserControl"/>) to the taskpane /// that has been exposed to COM and has a given ProgId /// </summary> /// <typeparam name="T">The type of UserControl being created</typeparam> /// <param name="progId">The [ProgId()] attribute value adorned on the UserControl class</param> /// <param name="licenseKey">The license key (for specific SolidWorks add-in types)</param> /// <returns></returns> public async Task<T> AddControl<T>(string progId, string licenseKey) { // Wrap any error creating the taskpane in a SolidDna exception return SolidDnaErrors.Wrap<T>(() => { // Attempt to create the taskpane return (T)mBaseObject.AddControl(progId, licenseKey); }, SolidDnaErrorTypeCode.SolidWorksTaskpane, SolidDnaErrorCode.SolidWorksTaskpaneAddControlError, await Localization.GetStringAsync("ErrorSolidWorksTaskpaneAddControlError")); } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class MenuScript : MonoBehaviour { public Text txtFin; public Text txtRecord; private void Start() { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; if (staticValues.winner == 0) { txtFin.text = "YOU LOSE"; txtFin.color = Color.red; txtFin.enabled = true; } else if (staticValues.winner == 1) { txtFin.text = "YOU WIN"; txtFin.color = Color.green; txtFin.enabled = true; } else { txtFin.enabled = false; } if (PlayerPrefs.HasKey("record")) { txtRecord.text = "RECORD: " + PlayerPrefs.GetFloat("record").ToString("n2"); } else { txtRecord.text = " RECORD: NO TIME"; } } public void ButtonPlay() { SceneManager.LoadScene(1); } public void ButtonExtra() { SceneManager.LoadScene(2); } }
using System.ComponentModel.DataAnnotations; using System; namespace WavelengthTheGame.Entities { public class PlayerEntity : BaseEntity, IPlayerEntity { [Required] public string Name {get;set;} public bool IsOwner {get;set;} public bool IsController {get;set;} public DateTime LastAction {get;set;} } }
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HttpListener.Model.HycCharge.Response { /// <summary> /// 用户执行结果 /// </summary> /// <typeparam name="T">结果数据体,根据业务类型确定</typeparam> public class HycSearchTaskResultResponse { /// <summary> /// 错误码,1为成功,500为错误,101用户未鉴权 /// </summary> public HycResultCode code { get; set; } /// <summary> /// 描述信息 /// </summary> public string description { get; set; } /// <summary> /// 任务执行状态 /// </summary> [JsonConverter(typeof(StringEnumConverter))] public HycOperationStatus operationStatus { get; set; } /// <summary> /// 结果 /// </summary> public HycTaskResultData data { get; set; } } public class HycTaskResultData { public HycTaskResultRow[] rows { get; set; } public int total { get; set; } } public class HycTaskResultRow { public string devImei { get; set; } public int devType { get; set; } public string stationName { get; set; } public string mchName { get; set; } public int logStatus { get; set; } public string addDate { get; set; } public object onenetDevId { get; set; } public string online { get; set; } public HycPlug[] plugs { get; set; } } public class HycPlug { public string plugNum { get; set; } public int plugStatus { get; set; } } }
using System; using KillrVideo.Models.Shared; namespace KillrVideo.Models.YouTube { /// <summary> /// The request ViewModel for adding a new YouTube video. /// </summary> [Serializable] public class AddYouTubeVideoViewModel : IAddVideoViewModel { /// <summary> /// The name/title of the video. /// </summary> public string Name { get; set; } /// <summary> /// The description for the video. /// </summary> public string Description { get; set; } /// <summary> /// The Id for the YouTube video (can be found in the URL for the video as v=XXXXXX). /// </summary> public string YouTubeVideoId { get; set; } /// <summary> /// Any tags for the video, as a comma-delimited string. /// </summary> public string Tags { get; set; } } }
using System; using MonoTouch.UIKit; using BigTed; using MonoTouch.Foundation; using System.Collections.Generic; using System.Drawing; using System.Linq; namespace XamarinStore { public class ShippingAddressViewController : UITableViewController { User user; public event EventHandler ShippingComplete; public readonly TextEntryView FirstNameField; public readonly TextEntryView LastNameField; public readonly TextEntryView PhoneNumberField; public readonly TextEntryView AddressField; public readonly TextEntryView Address2Field; public readonly TextEntryView CityField; public readonly AutoCompleteTextEntry StateField; public readonly TextEntryView PostalField; public readonly AutoCompleteTextEntry CountryField; BottomButtonView BottomView; List<UITableViewCell> Cells = new List<UITableViewCell> (); public ShippingAddressViewController (User user) { this.Title = "Shipping"; //This hides the back button text when you leave this View Controller this.NavigationItem.BackBarButtonItem = new UIBarButtonItem ("", UIBarButtonItemStyle.Plain, handler: null); this.user = user; TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None; Cells.Add (new CustomViewCell (FirstNameField = new TextEntryView { PlaceHolder = "First Name", Value = user.FirstName, })); Cells.Add (new CustomViewCell (LastNameField = new TextEntryView { PlaceHolder = "Last Name", Value = user.LastName, })); Cells.Add (new CustomViewCell (PhoneNumberField = new TextEntryView { PlaceHolder = "Phone Number", Value = user.Phone, KeyboardType = UIKeyboardType.NumberPad, })); Cells.Add (new CustomViewCell (AddressField = new TextEntryView { PlaceHolder = "Address", Value = user.Address, AutocapitalizationType = UITextAutocapitalizationType.Words, })); Cells.Add (new CustomViewCell (Address2Field = new TextEntryView { PlaceHolder = "Address", Value = user.Address2, AutocapitalizationType = UITextAutocapitalizationType.Words, })); Cells.Add (new CustomViewCell (CityField = new TextEntryView { PlaceHolder = "City", Value = user.City, AutocapitalizationType = UITextAutocapitalizationType.Words, })); Cells.Add (new CustomViewCell (PostalField = new TextEntryView { PlaceHolder = "Postal Code", Value = user.ZipCode, KeyboardType = UIKeyboardType.NumbersAndPunctuation, })); Cells.Add (new CustomViewCell (CountryField = new AutoCompleteTextEntry { PlaceHolder = "Country", Title = "Select your Country", Value = user.Country, ValueChanged = (v) => GetStates (), PresenterView = this, })); Cells.Add (new CustomViewCell (StateField = new AutoCompleteTextEntry { PlaceHolder = "State", Value = user.State, Title = "Select your state", PresenterView = this, })); GetCountries (); GetStates (); TableView.Source = new ShippingAddressPageSource { Cells = Cells }; TableView.TableFooterView = new UIView (new RectangleF (0, 0, 0, BottomButtonView.Height)); TableView.ReloadData (); View.AddSubview (BottomView = new BottomButtonView () { ButtonText = "Place Order", ButtonTapped = PlaceOrder, }); } public async void PlaceOrder() { user.FirstName = FirstNameField.Value; user.LastName = LastNameField.Value; user.Address = AddressField.Value; user.Address2 = Address2Field.Value; user.City = CityField.Value; user.Country = await WebService.Shared.GetCountryCode(CountryField.Value); user.Phone = PhoneNumberField.Value; user.State = StateField.Value; user.ZipCode = PostalField.Value; var isValid = await user.IsInformationValid (); if (!isValid.Item1) { new UIAlertView ("Error", isValid.Item2, null, "Ok").Show (); return; } if (ShippingComplete != null) ShippingComplete (this, EventArgs.Empty); } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); } async void GetCountries () { var countries = await WebService.Shared.GetCountries (); CountryField.Items = countries.Select (x => x.Name); } async void GetStates () { var states = await WebService.Shared.GetStates (CountryField.Value); StateField.Items = states; } public override void ViewDidLayoutSubviews () { base.ViewDidLayoutSubviews (); var bound = View.Bounds; bound.Y = bound.Bottom - BottomButtonView.Height; bound.Height = BottomButtonView.Height; BottomView.Frame = bound; } public class ShippingAddressPageSource : UITableViewSource { public List<UITableViewCell> Cells = new List<UITableViewCell> (); public ShippingAddressPageSource () { } public override int RowsInSection (UITableView tableview, int section) { return Cells.Count; } public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath) { return Cells [indexPath.Row]; } public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { return Cells [indexPath.Row].Frame.Height; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { if (Cells [indexPath.Row] is StringSelectionCell) ((StringSelectionCell)Cells [indexPath.Row]).Tap (); tableView.DeselectRow (indexPath, true); } } } }
using System.Linq; using Microsoft.EntityFrameworkCore; using tcs_service.Models; using tcs_service.Repos.Base; using tcs_service.Repos.Interfaces; namespace tcs_service.Repos { ///<summary>Repo for the SessionReason Table</summary> public class SessionReasonRepo : BaseRepo<SessionReason>, ISessionReasonRepo { ///<summary>SessionRepo Constructor</summary> public SessionReasonRepo (DbContextOptions options) : base (options) { } } }
///////////////////////////////////////////////// // //PEIMEN Frame System || GeneralObjMove branch // //creat by PEIKnifer[.CN] // //Frame for SimpleObjMove // //Create On 2019 4 4 // //Last Update in 2019 4 4 16:17:09 // ///////////////////////////////////////////////// using PEIKTS; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace PEIKBF_CPU { [RequireComponent(typeof(AudioPoolManager))] public abstract class AudioCPUOrigin : PEIKnifer { protected GameObject InstanceAudio(GameObject ins,string type,Vector3 position,Quaternion rotation) { try { return AudioPoolManager.Ins.Instance(ins, type, position, rotation); } catch { PEIKDE.LogError("ACO", "Audio Instance Error With Type --> "+type); return null; } } } }
/* http://www.cgsoso.com/forum-211-1.html CG搜搜 Unity3d 每日Unity3d插件免费更新 更有VIP资源! CGSOSO 主打游戏开发,影视设计等CG资源素材。 插件如若商用,请务必官网购买! daily assets update for try. U should buy the asset from home store if u use it in your project! */ using System.Collections; namespace UnityEngine.UI.Tweens { internal interface ITweenValue { void TweenValue(float floatPercentage); bool ignoreTimeScale { get; } float duration { get; } TweenEasing easing { get; } bool ValidTarget(); void Finished(); } }
using System.Reflection; using Lime.Protocol.Serialization; namespace Lime.Messaging { public static class DocumentTypeResolverExtensions { /// <summary> /// Registers all documents in the Lime.Messaging assembly. /// </summary> /// <param name="documentTypeResolver"></param> /// <returns></returns> public static IDocumentTypeResolver WithMessagingDocuments(this IDocumentTypeResolver documentTypeResolver) { documentTypeResolver.RegisterAssemblyDocuments(typeof(DocumentTypeResolverExtensions).GetTypeInfo().Assembly); return documentTypeResolver; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyScript : MonoBehaviour { Rigidbody[] rbs; Animator anim; ShooterController shooter; public bool aimed; void Start() { shooter = FindObjectOfType<ShooterController>(); anim = GetComponent<Animator>(); rbs = GetComponentsInChildren<Rigidbody>(); Ragdoll(false, transform); } public void Ragdoll(bool state, Transform point) { anim.enabled = !state; foreach (Rigidbody rb in rbs) { rb.isKinematic = !state; } if(state == true) { point.GetComponent<Rigidbody>().AddForce(shooter.transform.forward * 30, ForceMode.Impulse); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Shouldly; using Skyward.Popcorn; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace PopcornNetStandardTest { [TestClass] public class MultipleProjectionTests { #region Test Helper Classes const string TestName = "Name"; const string TestEmail = "Email@Domain.Tld"; #region Original Data Types class User { public Guid Id { get; } = Guid.NewGuid(); public string Name { get; set; } = TestName; public string Email { get; set; } = TestEmail; } class UserRelationship { public User Owner { get; set; } public User Child { get; set; } } class UserCollection { public List<User> Users1 { get; set; } public List<User> Users2 { get; set; } } #endregion #region Projections class UserFullProjection { public string Name { get; set; } public string Email { get; set; } } class UserWithNameProjection { public string Name { get; set; } } class UserWithEmailProjection { public string Email { get; set; } } class UserRelationshipNameProjection { public UserWithNameProjection Owner { get; set; } public UserWithNameProjection Child { get; set; } } class UserRelationshipEmailProjection { public UserWithEmailProjection Owner { get; set; } public UserWithEmailProjection Child { get; set; } } class UserRelationshipMixedProjection { public UserWithNameProjection Owner { get; set; } public UserWithEmailProjection Child { get; set; } } class UserCollectionProjection { public List<UserWithNameProjection> Users1 { get; set; } public List<UserWithEmailProjection> Users2 { get; set; } } class ExpandFromClass { public string Field1 { get; set; } public int Field2 { get; set; } } [ExpandFrom(typeof(ExpandFromClass), "[Field1,Field2]")] class ExpandFromClassProjection { public string Field1 { get; set; } public int Field2 { get; set; } } #endregion #endregion Expander _expander; [TestInitialize] public void SetupExpanderRegistry() { _expander = new Expander(); var config = new PopcornConfiguration(_expander); config.Map<UserRelationship, UserRelationship>(config:builder => { builder.AlternativeMap<UserRelationshipNameProjection>(); builder.AlternativeMap<UserRelationshipEmailProjection>(); builder.AlternativeMap<UserRelationshipMixedProjection>(); }); config.Map<User, UserFullProjection>(config: builder => { builder.AlternativeMap<UserWithNameProjection>(); builder.AlternativeMap<UserWithEmailProjection>(); }); config.Map<UserCollection, UserCollectionProjection>(); } /// <summary> /// Sanity test that default behavior still works with alternative maps /// </summary> [TestMethod] public void MapDefault() { var relationship = new UserRelationship { Owner = new User(), Child = new User() }; var relationshipProjected = _expander.Expand(relationship, null, includes:"[Owner]") as UserRelationship; relationshipProjected.ShouldNotBeNull(); relationshipProjected.Owner.ShouldNotBeNull(); relationshipProjected.Owner.Name.ShouldBe(TestName); relationshipProjected.Owner.Email.ShouldBe(TestEmail); relationshipProjected.Child.ShouldBeNull(); } /// <summary> /// Make sure we can map to alternative 1 as needed /// </summary> [TestMethod] public void MapNames() { var relationship = new UserRelationship { Owner = new User(), Child = new User() }; var relationshipProjected = _expander.Expand<UserRelationshipNameProjection>(relationship); relationshipProjected.ShouldNotBeNull(); relationshipProjected.Owner.ShouldNotBeNull(); relationshipProjected.Owner.Name.ShouldBe(TestName); relationshipProjected.Child.ShouldNotBeNull(); relationshipProjected.Child.Name.ShouldBe(TestName); } /// <summary> /// Make sure we can map to alternative 2 as needed /// </summary> [TestMethod] public void MapEmails() { var relationship = new UserRelationship { Owner = new User(), Child = new User() }; var relationshipProjected = _expander.Expand<UserRelationshipEmailProjection>(relationship); relationshipProjected.ShouldNotBeNull(); relationshipProjected.Owner.ShouldNotBeNull(); relationshipProjected.Owner.Email.ShouldBe(TestEmail); relationshipProjected.Child.ShouldNotBeNull(); relationshipProjected.Child.Email.ShouldBe(TestEmail); } /// <summary> /// Make sure we can map to a combination of alternatives 1 and 2 at the same time /// </summary> [TestMethod] public void MapMixed() { var relationship = new UserRelationship { Owner = new User(), Child = new User() }; var relationshipProjected = _expander.Expand<UserRelationshipMixedProjection>(relationship); relationshipProjected.ShouldNotBeNull(); relationshipProjected.Owner.ShouldNotBeNull(); relationshipProjected.Owner.Name.ShouldBe(TestName); relationshipProjected.Child.ShouldNotBeNull(); relationshipProjected.Child.Email.ShouldBe(TestEmail); } /// <summary> /// And make sure that alternatives apply acceptably to collections as well. /// </summary> [TestMethod] public void MapCollection() { var collection = new UserCollection { Users1 = new List<User> { new User(), new User(), }, Users2 = new List<User> { new User(), new User(), } }; var collectionProjected = _expander.Expand<UserCollectionProjection>(collection); collectionProjected.ShouldNotBeNull(); collectionProjected.Users1.ShouldNotBeNull(); collectionProjected.Users1.Count.ShouldBe(2); collectionProjected.Users1.All(u => u.Name == TestName).ShouldBeTrue(); collectionProjected.Users2.ShouldNotBeNull(); collectionProjected.Users2.Count.ShouldBe(2); collectionProjected.Users2.All(u => u.Email == TestEmail).ShouldBeTrue(); } [TestMethod] public void ExpandFromProof() { var expander = new Expander(); var config = new PopcornConfiguration(expander); config.ScanAssemblyForMapping(this.GetType().GetTypeInfo().Assembly); ExpandFromClass testObject = new ExpandFromClass { Field1 = "field1", Field2 = 2 }; var result = (ExpandFromClassProjection)expander.Expand(testObject, null); Assert.AreEqual(testObject.Field1, result.Field1); Assert.AreEqual(testObject.Field2, result.Field2); } } }
namespace LaunchPad2.Controls { public enum CueMoveMode { Normal, LeftGrip, RightGrip, LeadIn } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using FileExplorer.WPF.BaseControls; namespace FileExplorer.WPF.UserControls { public class BreadcrumbExpander : DropDownList { #region Constructor static BreadcrumbExpander() { DefaultStyleKeyProperty.OverrideMetadata(typeof(BreadcrumbExpander), new FrameworkPropertyMetadata(typeof(BreadcrumbExpander))); } #endregion #region Methods #endregion #region Data #endregion #region Public Properties //public static readonly DependencyProperty BreadcrumbTreeProperty = // DependencyProperty.Register("BreadcrumbTree", typeof(BreadcrumbTree), typeof(BreadcrumbTree)); //public BreadcrumbTree BreadcrumbTree //{ // get { return (BreadcrumbTree)GetValue(BreadcrumbTreeProperty); } // set { SetValue(BreadcrumbTreeProperty, value); } //} #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Text; using System.Threading.Tasks; using CitizenFX.Core; using CitizenFX.Core.Native; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using static CitizenFX.Core.Native.API; namespace FxWebAdmin { public class BaseServer : BaseScript { private readonly Dictionary<string, List<Tuple<Func<IDictionary<string, object>, string>, string>>> m_pluginOutlets = new Dictionary<string, List<Tuple<Func<IDictionary<string, object>, string>, string>>>(); private readonly Dictionary<string, Tuple<Func<IDictionary<string, object>, string>, string>> m_pluginPages = new Dictionary<string, Tuple<Func<IDictionary<string, object>, string>, string>>(); public static BaseServer Self { get; private set; } public IEnumerable<Player> ExternalPlayers => Players.ToArray(); // ToArray so that it doesn't break if used async public HttpContext CurrentContext { get; private set; } public BaseServer() { Tick += FirstTick; Self = this; Exports.Add("registerPluginOutlet", new Action<string, CallbackDelegate>(this.RegisterPluginOutlet)); Exports.Add("registerPluginPage", new Action<string, CallbackDelegate>(this.RegisterPluginPage)); Exports.Add("isInRole", new Func<string, bool>(this.IsInRole)); Exports.Add("getPluginUrl", new Func<string, IDictionary<string, object>, string>(this.GetPluginUrl)); } private string GetPluginUrl(string name, IDictionary<string, object> attributes = null) { var attrs = attributes ?? new Dictionary<string, object>(); attrs["name"] = name; var linkGenerator = CurrentContext.RequestServices.GetService<LinkGenerator>(); return linkGenerator.GetPathByAction(CurrentContext, "Page", "Plugin", attrs); } private bool IsInRole(string role) { return CurrentContext?.User?.IsInRole(role) ?? false; } private void RegisterPluginOutlet(string name, CallbackDelegate callback) { var resourceName = GetInvokingResource(); if (!m_pluginOutlets.TryGetValue(name, out var list)) { list = new List<Tuple<Func<IDictionary<string, object>, string>, string>>(); m_pluginOutlets[name] = list; } list.Add( Tuple.Create<Func<IDictionary<string, object>, string>, string>( attributes => callback.Invoke(attributes)?.ToString() ?? "", resourceName ) ); } private void RegisterPluginPage(string name, CallbackDelegate callback) { var resourceName = GetInvokingResource(); m_pluginPages[$"{name}"] = Tuple.Create<Func<IDictionary<string, object>, string>, string>( attributes => { var invokeResult = callback.Invoke(attributes); string s; if (invokeResult is Task<object> t) { // TODO: lol blocking? s = (t.Result)?.ToString() ?? ""; } else { s = invokeResult?.ToString() ?? ""; } return s; }, resourceName ); } [EventHandler("onResourceStop")] public void OnResourceStop(string resourceName) { foreach (var outlet in m_pluginOutlets.Values) { foreach (var entry in outlet.ToArray()) { if (entry.Item2 == resourceName) { outlet.Remove(entry); } } } } private async Task FirstTick() { Tick -= FirstTick; Environment.SetEnvironmentVariable("MONO_MANAGED_WATCHER", "disabled"); // screw TLS certs especially as they require manually deploying a root list.. really? ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; var host = new WebHostBuilder() .ConfigureServices(services => { services.AddSingleton<IServer, HttpServer>(); services.AddSingleton<ConsoleLog>(); }) .ConfigureLogging(l => { //l.SetMinimumLevel(LogLevel.Trace); //l.AddConsole(); }) .UseContentRoot(GetResourcePath(GetCurrentResourceName())) .UseStartup<Startup>() .Build(); host.Start(); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // try downloading maxmind var geoLitePath = Path.Combine(Startup.RootPath, "GeoLite2-Country.mmdb"); if (!File.Exists(geoLitePath)) { await Task.Run(async () => { try { var httpClient = new HttpClient(); var httpResponse = await httpClient.GetAsync("https://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.tar.gz", HttpCompletionOption.ResponseHeadersRead); if (httpResponse.IsSuccessStatusCode) { using (var stream = await httpResponse.Content.ReadAsStreamAsync()) { using (var reader = SharpCompress.Readers.ReaderFactory.Open(stream)) { while (reader.MoveToNextEntry()) { if (reader.Entry.Key.EndsWith(".mmdb")) { using (var file = File.Open(geoLitePath, FileMode.Create, FileAccess.Write)) { reader.WriteEntryTo(file); Debug.WriteLine($"Saved GeoLite2-Country to {geoLitePath}."); break; } } } } } } } catch {} }); } } internal async Task<string> RunPluginController(string name, IDictionary<string, object> attributes, HttpContext context) { if (m_pluginPages.TryGetValue(name, out var page)) { return await HttpServer.QueueTick(() => { CurrentContext = context; var s = page.Item1(attributes); CurrentContext = null; return s; }); } return ""; } internal async Task<string> RunPluginOutlet(string name, IDictionary<string, object> attributes, HttpContext context) { if (m_pluginOutlets.TryGetValue(name, out var outletList)) { return await HttpServer.QueueTick(() => { CurrentContext = context; var s = string.Join("", outletList.Select(cb => cb.Item1(attributes))); CurrentContext = null; return s; }); } return ""; } } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using SalesOrderMVP.Commands; namespace SalesOrderMVP.Controllers { public class LayoutController : IDisposable { private readonly Action<FrameworkElement> ChangeView; private readonly FrameworkElement GridView; private readonly FrameworkElement ItemView; private readonly CommandBinding BindingGrid; private readonly CommandBinding BindingItem; public LayoutController( Action<FrameworkElement> changeView, FrameworkElement gridView, FrameworkElement itemView, DataGrid dataGrid) { this.ChangeView = changeView; this.GridView = gridView; this.ItemView = itemView; dataGrid.MouseDoubleClick += (s, ea) => SwitchToItem(null, null); var bindings = App.Current.MainWindow.CommandBindings; bindings.Add(BindingGrid = new CommandBinding(GlobalCommands.ShowGridView, SwitchToGrid)); bindings.Add(BindingItem = new CommandBinding(GlobalCommands.ShowItemView, SwitchToItem)); } private void SwitchToGrid(object sender, ExecutedRoutedEventArgs ea) { ChangeView(GridView); } private void SwitchToItem(object sender, ExecutedRoutedEventArgs ea) { ChangeView(ItemView); } public void Dispose() { App.Current.MainWindow.CommandBindings.Remove(BindingGrid); App.Current.MainWindow.CommandBindings.Remove(BindingItem); } } }
using System.Collections.Generic; namespace MedicalExaminer.API.Models.v1.Locations { /// <inheritdoc /> /// <summary> /// Response object for a list of locations. /// </summary> public class GetLocationsResponse : ResponseBase { /// <summary> /// List of Locations. /// </summary> public IEnumerable<LocationItem> Locations { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using NUnit.Framework; namespace ServiceStack.Text.Tests { public class Module { public Module() { ExtendedData = new Dictionary<string, object>(); } public string Name { get; set; } public string Version { get; set; } public IDictionary<string, object> ExtendedData { get; set; } } public class StackFrame { public StackFrame() { ExtendedData = new Dictionary<string, object>(); Parameters = new Collection<Parameter>(); } public string FileName { get; set; } public int LineNumber { get; set; } public int Column { get; set; } public IDictionary<string, object> ExtendedData { get; set; } public string Type { get; set; } public string Namespace { get; set; } public Module Module { get; set; } public string Method { get; set; } public ICollection<Parameter> Parameters { get; set; } } public class Parameter { public Parameter() { ExtendedData = new Dictionary<string, object>(); } public string Name { get; set; } public string Type { get; set; } public IDictionary<string, object> ExtendedData { get; set; } } public class Error { public Error() { ExtendedData = new Dictionary<string, object>(); Tags = new HashSet<string>(); StackTrace = new Collection<StackFrame>(); } public string Id { get; set; } public string Message { get; set; } public string Type { get; set; } public Module Module { get; set; } public string Description { get; set; } public DateTime OccurrenceDate { get; set; } public string Code { get; set; } public IDictionary<string, object> ExtendedData { get; set; } public HashSet<string> Tags { get; set; } public Error Inner { get; set; } public ICollection<StackFrame> StackTrace { get; set; } public string Contact { get; set; } public string Notes { get; set; } } [TestFixture] public class CyclicalDependencyTests : TestBase { [Test] public void Can_serialize_Error() { var dto = new Error { Id = "Id", Message = "Message", Type = "Type", Description = "Description", OccurrenceDate = new DateTime(2012, 01, 01), Code = "Code", ExtendedData = new Dictionary<string, object> { { "Key", "Value" } }, Tags = new HashSet<string> { "C#", "ruby" }, Inner = new Error { Id = "Id2", Message = "Message2", ExtendedData = new Dictionary<string, object> { { "InnerKey", "InnerValue" } }, Module = new Module { Name = "Name", Version = "v1.0" }, StackTrace = new Collection<StackFrame> { new StackFrame { Column = 1, Module = new Module { Name = "StackTrace.Name", Version = "StackTrace.v1.0" }, ExtendedData = new Dictionary<string, object> { { "StackTraceKey", "StackTraceValue" } }, FileName = "FileName", Type = "Type", LineNumber = 1, Method = "Method", Namespace = "Namespace", Parameters = new Collection<Parameter> { new Parameter { Name = "Parameter", Type = "ParameterType" }, } } } }, Contact = "Contact", Notes = "Notes", }; var from = Serialize(dto, includeXml: false); Console.WriteLine(from.Dump()); Assert.That(from.Id, Is.EqualTo(dto.Id)); Assert.That(from.Message, Is.EqualTo(dto.Message)); Assert.That(from.Type, Is.EqualTo(dto.Type)); Assert.That(from.Description, Is.EqualTo(dto.Description)); Assert.That(from.OccurrenceDate, Is.EqualTo(dto.OccurrenceDate)); Assert.That(from.Code, Is.EqualTo(dto.Code)); Assert.That(from.Inner.Id, Is.EqualTo(dto.Inner.Id)); Assert.That(from.Inner.Message, Is.EqualTo(dto.Inner.Message)); Assert.That(from.Inner.ExtendedData["InnerKey"], Is.EqualTo(dto.Inner.ExtendedData["InnerKey"])); Assert.That(from.Inner.Module.Name, Is.EqualTo(dto.Inner.Module.Name)); Assert.That(from.Inner.Module.Version, Is.EqualTo(dto.Inner.Module.Version)); var actualStack = from.Inner.StackTrace.First(); var expectedStack = dto.Inner.StackTrace.First(); Assert.That(actualStack.Column, Is.EqualTo(expectedStack.Column)); Assert.That(actualStack.FileName, Is.EqualTo(expectedStack.FileName)); Assert.That(actualStack.Type, Is.EqualTo(expectedStack.Type)); Assert.That(actualStack.LineNumber, Is.EqualTo(expectedStack.LineNumber)); Assert.That(actualStack.Method, Is.EqualTo(expectedStack.Method)); Assert.That(from.Contact, Is.EqualTo(dto.Contact)); Assert.That(from.Notes, Is.EqualTo(dto.Notes)); } class person { public string name { get; set; } public person teacher { get; set; } } [Test] public void Can_limit_cyclical_dependencies() { using (JsConfig.With(new Config { MaxDepth = 4 })) { var p = new person(); p.teacher = new person { name = "sam", teacher = p }; p.name = "bob"; p.PrintDump(); p.ToJsv().Print(); p.ToJson().Print(); } } class Node { public string Name { get; set; } [IgnoreDataMember] public Node Parent { get; set; } public List<Node> Children { get; set; } } [Test] public void Ignore_Cyclical_dependencies() { JsConfig<Node>.OnDeserializedFn = (node) => { node.Children.Each(child => child.Parent = node); return node; }; var parent = new Node { Name = "Parent", }; parent.Children = new List<Node> { new Node { Name = "Child", Parent = parent }, }; var json = parent.ToJson(); Assert.That(json, Is.EqualTo("{\"Name\":\"Parent\",\"Children\":[{\"Name\":\"Child\"}]}")); var fromJson = json.FromJson<Node>(); Assert.That(fromJson.Children[0].Parent, Is.EqualTo(fromJson)); JsConfig<Node>.OnDeserializedFn = null; JsConfig.Reset(); } public class ReflectionType { public string Name { get; set; } = "A"; public Type Type { get; set; } public MethodInfo MethodInfo { get; set; } public PropertyInfo PropertyInfo { get; set; } public FieldInfo FieldInfo; public MemberInfo MemberInfo { get; set; } public void Method() {} } [Test] public void Can_serialize_POCO_with_Type() { var dto = new ReflectionType { Type = typeof(ReflectionType), MethodInfo = typeof(ReflectionType).GetMethod(nameof(ReflectionType.Method)), PropertyInfo = typeof(ReflectionType).GetProperty(nameof(ReflectionType.PropertyInfo)), FieldInfo = typeof(ReflectionType).GetPublicFields().FirstOrDefault(), MemberInfo = typeof(ReflectionType).GetMembers().FirstOrDefault(), }; dto.Name.Print(); dto.ToJson().Print(); dto.ToJsv().Print(); dto.PrintDump(); } } }
// *********************************************************************** // Assembly : XLabs.Forms.Droid // Author : XLabs Team // Created : 12-27-2015 // // Last Modified By : XLabs Team // Last Modified On : 01-04-2016 // *********************************************************************** // <copyright file="HybridWebViewRenderer.cs" company="XLabs Team"> // Copyright (c) XLabs Team. All rights reserved. // </copyright> // <summary> // This project is licensed under the Apache 2.0 license // https://github.com/XLabs/Xamarin-Forms-Labs/blob/master/LICENSE // // XLabs is a open source project that aims to provide a powerfull and cross // platform set of controls tailored to work with Xamarin Forms. // </summary> // *********************************************************************** // using System; using Android.Runtime; using Android.Views; using Android.Webkit; using Java.Interop; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using XLabs.Forms.Controls; using Object = Java.Lang.Object; using WebView = Android.Webkit.WebView; [assembly: ExportRenderer(typeof(HybridWebView), typeof(HybridWebViewRenderer))] namespace XLabs.Forms.Controls { /// <summary> /// Class HybridWebViewRenderer. /// </summary> public partial class HybridWebViewRenderer : ViewRenderer<HybridWebView, HybridWebViewRenderer.NativeWebView> { /// <summary> /// Allows one to override the Webview Client class without a custom renderer. /// </summary> public static Func<HybridWebViewRenderer,Client> GetWebViewClientDelegate; /// <summary> /// Allows one to override the Chrome Client class without a custom renderer. /// </summary> public static Func<HybridWebViewRenderer, ChromeClient> GetWebChromeClientDelegate; /// <summary> /// Gets the desired size of the view. /// </summary> /// <param name="widthConstraint">Width constraint.</param> /// <param name="heightConstraint">Height constraint.</param> /// <returns>The desired size.</returns> /// <remarks>We need to override this method and set the request height to 0. Otherwise on view refresh /// we will get incorrect view height and might lose the ability to scroll the webview /// completely.</remarks> public override SizeRequest GetDesiredSize(int widthConstraint, int heightConstraint) { var sizeRequest = base.GetDesiredSize(widthConstraint, heightConstraint); sizeRequest.Request = new Size(sizeRequest.Request.Width, 0); return sizeRequest; //return new SizeRequest(Size.Zero, Size.Zero); } /// <summary> /// Called when [element changed]. /// </summary> /// <param name="e">The e.</param> protected override void OnElementChanged(ElementChangedEventArgs<HybridWebView> e) { base.OnElementChanged (e); if (this.Control == null && e.NewElement != null) { var webView = new NativeWebView(this, e.NewElement.AndroidAdditionalTouchCallback); webView.Settings.JavaScriptEnabled = true; webView.Settings.DomStorageEnabled = true; //Turn off hardware rendering webView.SetLayerType(e.NewElement.AndroidHardwareRendering? LayerType.Hardware : LayerType.Software, null); //Set the background color to transparent to fix an issue where the //the picture would fail to draw webView.SetBackgroundColor(Color.Transparent.ToAndroid()); webView.SetWebViewClient(this.GetWebViewClient()); webView.SetWebChromeClient(this.GetWebChromeClient()); webView.AddJavascriptInterface(new Xamarin(this), "Xamarin"); this.SetNativeControl(webView); webView.LayoutParameters = new LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent); } this.Unbind(e.OldElement); this.Bind(); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (disposing && this.Element != null) { if (this.Control != null) { this.Control.StopLoading(); } Unbind(this.Element); } base.Dispose(disposing); } /// <summary> /// Gets <see cref="Client"/> for the web view. /// </summary> /// <returns><see cref="Client"/></returns> protected virtual Client GetWebViewClient() { var d = GetWebViewClientDelegate; return d != null ? d(this) : new Client(this); } /// <summary> /// Gets <see cref="ChromeClient"/> for the web view. /// </summary> /// <returns><see cref="ChromeClient"/></returns> protected virtual ChromeClient GetWebChromeClient() { var d = GetWebChromeClientDelegate; return d != null ? d(this) : new ChromeClient(); } partial void HandleCleanup() { if (Control == null) return; Control.SetWebViewClient (null); Control.SetWebChromeClient (null); Control.RemoveJavascriptInterface ("Xamarin"); } private void OnPageFinished() { if (this.Element == null) return; this.Inject(NativeFunction); this.Inject(GetFuncScript()); this.Element.OnLoadFinished(this, EventArgs.Empty); } /// <summary> /// Injects the specified script. /// </summary> /// <param name="script">The script.</param> partial void Inject(string script) { if (Control != null) { this.Control.LoadUrl(string.Format("javascript: {0}", script)); } } /// <summary> /// Loads the specified URI. /// </summary> /// <param name="uri">The URI.</param> partial void Load(Uri uri) { if (uri != null && Control != null) { this.Control.LoadUrl(uri.AbsoluteUri); } } /// <summary> /// Loads from content. /// </summary> /// <param name="sender">The sender.</param> /// <param name="contentFullName">Full name of the content.</param> partial void LoadFromContent(object sender, HybridWebView.LoadContentEventArgs contentArgs) { var baseUri = new Uri(contentArgs.BaseUri ?? "file:///android_asset/"); this.Element.Uri = new Uri(baseUri, contentArgs.Content); } /// <summary> /// Loads the content. /// </summary> /// <param name="sender">The sender.</param> /// <param name="content">Full name of the content.</param> partial void LoadContent(object sender, HybridWebView.LoadContentEventArgs contentArgs) { if (Control != null) { var baseUri = contentArgs.BaseUri ?? "file:///android_asset/"; this.Control.LoadDataWithBaseURL(baseUri, contentArgs.Content, "text/html", "UTF-8", null); } } /// <summary> /// Loads from string. /// </summary> /// <param name="html">The HTML.</param> partial void LoadFromString(string html) { if (Control != null) { this.Control.LoadData(html, "text/html", "UTF-8"); } } /// <summary> /// Class Client. /// </summary> public class Client : WebViewClient { /// <summary> /// The web hybrid /// </summary> protected readonly WeakReference<HybridWebViewRenderer> WebHybrid; /// <summary> /// Initializes a new instance of the <see cref="Client"/> class. /// </summary> /// <param name="webHybrid">The web hybrid.</param> public Client(HybridWebViewRenderer webHybrid) { this.WebHybrid = new WeakReference<HybridWebViewRenderer>(webHybrid); } /// <summary> /// Notify the host application that a page has finished loading. /// </summary> /// <param name="view">The WebView that is initiating the callback.</param> /// <param name="url">The url of the page.</param> /// <since version="Added in API level 1" /> /// <remarks><para tool="javadoc-to-mdoc">Notify the host application that a page has finished loading. This method /// is called only for main frame. When onPageFinished() is called, the /// rendering picture may not be updated yet. To get the notification for the /// new Picture, use <c><see cref="M:Android.Webkit.WebView.IPictureListener.OnNewPicture(Android.Webkit.WebView, Android.Graphics.Picture)" /></c>.</para> /// <para tool="javadoc-to-mdoc"> /// <format type="text/html"> /// <a href="http://developer.android.com/reference/android/webkit/WebViewClient.html#onPageFinished(android.webkit.WebView, java.lang.String)" target="_blank">[Android Documentation]</a> /// </format> /// </para></remarks> public override void OnPageFinished(WebView view, string url) { base.OnPageFinished(view, url); HybridWebViewRenderer hybrid; if (this.WebHybrid != null && this.WebHybrid.TryGetTarget(out hybrid)) { hybrid.OnPageFinished(); } } } /// <summary> /// Java callback class for JavaScript. /// </summary> public class Xamarin : Object { /// <summary> /// The web hybrid. /// </summary> private readonly WeakReference<HybridWebViewRenderer> webHybrid; /// <summary> /// Initializes a new instance of the <see cref="Xamarin"/> class. /// </summary> /// <param name="webHybrid">The web hybrid.</param> public Xamarin(HybridWebViewRenderer webHybrid) { this.webHybrid = new WeakReference<HybridWebViewRenderer>(webHybrid); } /// <summary> /// Calls the specified function. /// </summary> /// <param name="message">The message.</param> [JavascriptInterface] [Export("call")] public void Call(string message) { HybridWebViewRenderer hybrid; HybridWebView webView; if (this.webHybrid != null && this.webHybrid.TryGetTarget(out hybrid) && ((webView = hybrid.Element) != null)) { webView.MessageReceived(message); } } } /// <summary> /// Class ChromeClient. /// </summary> public class ChromeClient : WebChromeClient { /// <summary> /// Overrides the geolocation prompt and accepts the permission. /// </summary> /// <param name="origin">Origin of the prompt.</param> /// <param name="callback">Permission callback.</param> /// <remarks>Always grant permission since the app itself requires location /// permission and the user has therefore already granted it.</remarks> public override void OnGeolocationPermissionsShowPrompt(string origin, GeolocationPermissions.ICallback callback) { callback.Invoke(origin, true, false); } } /// <summary> /// Class NativeWebView. /// </summary> public class NativeWebView : WebView { /// <summary> /// The detector /// </summary> private readonly GestureDetector detector; /// <summary> /// Detector switch /// </summary> private readonly bool enableDetector; /// <summary> /// Initializes a new instance of the <see cref="NativeWebView"/> class. /// </summary> /// <param name="renderer">The renderer.</param> public NativeWebView(HybridWebViewRenderer renderer, bool enableAdditionalTouchDetector) : base(renderer.Context) { enableDetector = enableAdditionalTouchDetector; if (enableDetector) { var listener = new MyGestureListener(renderer); this.detector = new GestureDetector(this.Context, listener); } } /// <summary> /// This is an Android specific constructor that sometimes needs to be called by the underlying /// Xamarin ACW environment. /// </summary> /// <param name="ptr"></param> /// <param name="handle"></param> public NativeWebView(IntPtr ptr, JniHandleOwnership handle) : base(ptr, handle) { } /// <summary> /// Implement this method to handle touch screen motion events. /// </summary> /// <param name="e">The motion event.</param> /// <returns>To be added.</returns> /// <since version="Added in API level 1" /> /// <remarks><para tool="javadoc-to-mdoc">Implement this method to handle touch screen motion events.</para> /// <para tool="javadoc-to-mdoc"> /// <format type="text/html"> /// <a href="http://developer.android.com/reference/android/view/View.html#onTouchEvent(android.view.MotionEvent)" target="_blank">[Android Documentation]</a> /// </format> /// </para></remarks> public override bool OnTouchEvent(MotionEvent e) { if (enableDetector) { this.detector.OnTouchEvent(e); } return base.OnTouchEvent(e); } /// <summary> /// Class MyGestureListener. /// </summary> private class MyGestureListener : GestureDetector.SimpleOnGestureListener { /// <summary> /// The swip e_ mi n_ distance /// </summary> private const int SWIPE_MIN_DISTANCE = 120; /// <summary> /// The swip e_ ma x_ of f_ path /// </summary> private const int SWIPE_MAX_OFF_PATH = 200; /// <summary> /// The swip e_ threshol d_ velocity /// </summary> private const int SWIPE_THRESHOLD_VELOCITY = 200; /// <summary> /// The web hybrid /// </summary> private readonly WeakReference<HybridWebViewRenderer> webHybrid; /// <summary> /// Initializes a new instance of the <see cref="MyGestureListener"/> class. /// </summary> /// <param name="renderer">The renderer.</param> public MyGestureListener(HybridWebViewRenderer renderer) { this.webHybrid = new WeakReference<HybridWebViewRenderer>(renderer); } // public override void OnLongPress(MotionEvent e) // { // Console.WriteLine("OnLongPress"); // base.OnLongPress(e); // } // // public override bool OnDoubleTap(MotionEvent e) // { // Console.WriteLine("OnDoubleTap"); // return base.OnDoubleTap(e); // } // // public override bool OnDoubleTapEvent(MotionEvent e) // { // Console.WriteLine("OnDoubleTapEvent"); // return base.OnDoubleTapEvent(e); // } // // public override bool OnSingleTapUp(MotionEvent e) // { // Console.WriteLine("OnSingleTapUp"); // return base.OnSingleTapUp(e); // } // // public override bool OnDown(MotionEvent e) // { // Console.WriteLine("OnDown"); // return base.OnDown(e); // } /// <summary> /// Called when [fling]. /// </summary> /// <param name="e1">The e1.</param> /// <param name="e2">The e2.</param> /// <param name="velocityX">The velocity x.</param> /// <param name="velocityY">The velocity y.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public override bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { HybridWebViewRenderer hybrid; if (this.webHybrid.TryGetTarget(out hybrid) && Math.Abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { if(e1.GetX() - e2.GetX() > SWIPE_MIN_DISTANCE) { hybrid.Element.OnLeftSwipe(this, EventArgs.Empty); } else if (e2.GetX() - e1.GetX() > SWIPE_MIN_DISTANCE) { hybrid.Element.OnRightSwipe(this, EventArgs.Empty); } } return base.OnFling(e1, e2, velocityX, velocityY); } // public override bool OnScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) // { // Console.WriteLine("OnScroll"); // return base.OnScroll(e1, e2, distanceX, distanceY); // } // // public override void OnShowPress(MotionEvent e) // { // Console.WriteLine("OnShowPress"); // base.OnShowPress(e); // } // // public override bool OnSingleTapConfirmed(MotionEvent e) // { // Console.WriteLine("OnSingleTapConfirmed"); // return base.OnSingleTapConfirmed(e); // } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataTables.AspNetCore.Mvc { /// <summary> /// Represents a global grid button /// </summary> class GridButtonOptions { /// <summary> /// Define which button type the button should be based on /// </summary> public string Extend { get; set; } /// <summary> /// The text to show in the button /// </summary> public string Text { get; set; } /// <summary> /// Action to take when the button is activated. /// </summary> public string Action { get; set; } } }
using System.Threading.Tasks; using PuppeteerExtraSharp.Plugins.ExtraStealth.Evasions; using Xunit; namespace Extra.Tests.StealthPluginTests.EvasionsTests { public class ChromeSciTest : BrowserDefault { [Fact] public async Task ShouldWork() { var plugin = new ChromeSci(); var page = await LaunchAndGetPage(plugin); await page.GoToAsync("https://google.com"); var sci = await page.EvaluateFunctionAsync(@"() => { const { timing } = window.performance const csi = window.chrome.csi() return { csi: { exists: window.chrome && 'csi' in window.chrome, toString: chrome.csi.toString() }, dataOK: { onloadT: csi.onloadT === timing.domContentLoadedEventEnd, startE: csi.startE === timing.navigationStart, pageT: Number.isInteger(csi.pageT), tran: Number.isInteger(csi.tran) } } }"); Assert.True(sci["csi"].Value<bool>("exists")); Assert.Equal("function () { [native code] }", sci["csi"]["toString"]); Assert.True(sci["dataOK"].Value<bool>("onloadT")); Assert.True(sci["dataOK"].Value<bool>("pageT")); Assert.True(sci["dataOK"].Value<bool>("startE")); Assert.True(sci["dataOK"].Value<bool>("tran")); } } }
namespace Microsoft.Research.SpeechWriter.Core.Data { /// <summary> /// The type of the tile. /// </summary> public enum TileType { /// <summary> /// A normal tile that by default is surrounded by spaces. /// </summary> Normal, /// <summary> /// A prefix tile that attaches to the next tile without a space. /// </summary> Prefix, /// <summary> /// A suffix tile that attaches to the previous tile without a space. /// </summary> Suffix, /// <summary> /// An infix tile that attaches to both the previous and next tile without a space. /// </summary> Infix, /// <summary> /// A suggestion suffix tile that will attach itself to the previous word if selected. /// </summary> Extension, /// <summary> /// A special command tile. /// </summary> Command } }
using UnityEngine; using UnityEditor; public partial class PostFXStack { partial void ApplySceneViewState(); #if UNITY_EDITOR partial void ApplySceneViewState() { if(camera.cameraType == CameraType.SceneView && !SceneView.currentDrawingSceneView.sceneViewState.showImageEffects) { settings = null; } } #endif }
using NUnit.Framework; namespace Blog.UI.Tests.Pages.PostPage { public static class PostPageAsserter { public static void AssertPostAdded(this PostPage page) { Assert.IsTrue(page.PostAdded.Displayed); } public static void AssertErrorMessage(this PostPage page, string text) { Assert.IsTrue(page.ErrorMessage.Displayed); StringAssert.Contains(text, page.ErrorMessage.Text); } public static void AssertPostPageIsLoaded(this PostPage page, string text) { Assert.AreEqual(text, page.Heading.Text); } } }
using NUnit.Framework; namespace Nest.Tests.Unit.QueryParsers.Queries { [TestFixture] public class FilteredQueryTests : ParseQueryTestsBase { [Test] public void Filtered_Deserializes() { var q = this.SerializeThenDeserialize( f=>f.Filtered, f=>f.Filtered(fq=>fq .Filter(ff=>Filter1) .Query(qq=>Query1) ) ); AssertIsTermFilter(q.Filter, Filter1); AssertIsTermQuery(q.Query, Query1); } } }
[Equals] public class WithoutGenericParameter : GenericClass<GenericClassBaseClass> { public int Z { get; set; } public static bool operator ==(WithoutGenericParameter left, WithoutGenericParameter right) => Operator.Weave(); public static bool operator !=(WithoutGenericParameter left, WithoutGenericParameter right) => Operator.Weave(); }
using System.Collections.Generic; using Basic.Ast; namespace Basic { public class AttributeInstance { private readonly object obj; public AttributeInstance(ITypeDefinition type) { Parameters = new Dictionary<string, Expression>(); } public AttributeInstance(object obj) { this.obj = obj; AttributeType = TypeManager.ResolveType(obj.GetType().FullName); } public ITypeDefinition AttributeType { get; private set; } public bool IsCompiled { get { return obj != null; } } public Dictionary<string, Expression> Parameters { get; private set; } public object GetObject() { return obj; } } }
using System.Collections.Generic; using UnityEngine; // Manages every instatiated platform in the scene - used for: // controlling platforms speed // instantiating platforms at a given frequency // destroying platforms // Also manages the object pool for the the platforms and blockades public class PlatformManager : MonoBehaviour { #pragma warning disable 649 [SerializeField] ObjectPooler platformObjectPooler, blockadesObjectPooler; // The frequency in which platforms are spawned [SerializeField] float spawnTime; // The min / max Y values at which the platform can spawn at; [SerializeField] float minYSpawn, maxYSpawn; // the platforms max move speed [SerializeField] float obstacleSpeed; #pragma warning restore 649 // Spawn Timer - used to count down the the spawnTime public float spawnTimer; // boolean used to toogle when a new platform is instantiated bool spawnPlatforms; // Getter and Setter for spawnPlatforms boolean public bool SpawnPlatform { get { return spawnPlatforms; } set { spawnPlatforms = value; } } // Getter and Setter for spawnTime public float SpawnTime { get { return spawnTime; } set { spawnTime = value; } } // Getter and Setter for obstacleSpeed public float ObstacleSpeed { get { return obstacleSpeed; } set { obstacleSpeed = value; } } //number of blocks to disable public int numBlocks; // Start is called before the first frame update void Start() { } bool spawnSwitch; // Update is called once per frame public void Update() { spawnTimer -= Time.deltaTime; if (spawnPlatforms) { if (spawnTimer <= 0) { if (!spawnSwitch) { GameObject platformGameObject = platformObjectPooler.RetreivePooledObject(); platformGameObject.transform.position = new Vector2(17f, Random.Range(minYSpawn, maxYSpawn)); platformGameObject.transform.rotation = Quaternion.identity; platformGameObject.GetComponent<Platform>().PlatformSpeed = obstacleSpeed; platformGameObject.gameObject.SetActive(true); spawnSwitch = true; } else { GameObject blockadeGameObject = blockadesObjectPooler.RetreivePooledObject(); blockadeGameObject.transform.position = new Vector2(17f, 0); blockadeGameObject.transform.rotation = Quaternion.identity; blockadeGameObject.GetComponent<Blockade>().NumberOfBlocksToEnable = numBlocks; blockadeGameObject.GetComponent<Blockade>().BlockadeSpeed = obstacleSpeed; blockadeGameObject.gameObject.SetActive(true); spawnSwitch = false; } spawnTimer = spawnTime; } } } // increases the speed of all obstacles in the scene public void IncreaseSpeedOfAllObstacles(float speedIncrease) { obstacleSpeed += speedIncrease; foreach(GameObject p in platformObjectPooler.objectsToPool) { p.GetComponent<Platform>().PlatformSpeed = ObstacleSpeed; } foreach (GameObject b in blockadesObjectPooler.objectsToPool) { b.GetComponent<Blockade>().BlockadeSpeed = ObstacleSpeed; } } }
//----------------------------------------------------------------------------- // FILE: Service.cs // CONTRIBUTOR: Marcus Bowyer // COPYRIGHT: Copyright (c) 2005-2022 by neonFORGE LLC. All rights reserved. using System.Threading.Tasks; using System.Net; using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using Neon.Service; using Neon.Common; using Neon.Kube; using Prometheus; using Prometheus.DotNetRuntime; namespace NeonSsoSessionProxy { /// <summary> /// Implements the <b>neon-sso-session-proxy</b> service. /// </summary> public class NeonSsoSessionProxyService : NeonService { // class fields private IWebHost webHost; /// <summary> /// Session cookie name. /// </summary> public const string SessionCookieName = ".NeonKUBE.SsoProxy.Session.Cookie"; /// <summary> /// Constructor. /// </summary> /// <param name="name">The service name.</param> public NeonSsoSessionProxyService(string name) : base(name, version: KubeVersions.NeonKube) { } /// <inheritdoc/> protected override void Dispose(bool disposing) { base.Dispose(disposing); // Dispose web host if it's still running. if (webHost != null) { webHost.Dispose(); webHost = null; } } /// <inheritdoc/> protected async override Task<int> OnRunAsync() { await SetStatusAsync(NeonServiceStatus.Starting); // Start the web service. webHost = new WebHostBuilder() .UseStartup<Startup>() .UseKestrel(options => options.Listen(IPAddress.Any, 80)) .ConfigureServices(services => services.AddSingleton(typeof(NeonSsoSessionProxyService), this)) .UseStaticWebAssets() .Build(); _ = webHost.RunAsync(); Log.LogInfo($"Listening on {IPAddress.Any}:80"); // Indicate that the service is ready for business. await SetStatusAsync(NeonServiceStatus.Running); // Wait for the process terminator to signal that the service is stopping. await Terminator.StopEvent.WaitAsync(); // Return the exit code specified by the configuration. return await Task.FromResult(0); } } }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using NUnit.Framework; using StreamRC.Gambling.Cards; namespace Gambling.Tests { /// <summary> /// tests assumptions about card data /// </summary> [TestFixture] public class CardTests { IEnumerable<Tuple<Card, byte>> Codes { get { yield return new Tuple<Card, byte>(new Card(CardRank.Deuce, CardSuit.Clubs), 0); yield return new Tuple<Card, byte>(new Card(CardRank.Deuce, CardSuit.Diamonds), 1); yield return new Tuple<Card, byte>(new Card(CardRank.Deuce, CardSuit.Hearts), 2); yield return new Tuple<Card, byte>(new Card(CardRank.Deuce, CardSuit.Spades), 3); yield return new Tuple<Card, byte>(new Card(CardRank.Trey, CardSuit.Clubs), 4); yield return new Tuple<Card, byte>(new Card(CardRank.Trey, CardSuit.Diamonds), 5); yield return new Tuple<Card, byte>(new Card(CardRank.Trey, CardSuit.Hearts), 6); yield return new Tuple<Card, byte>(new Card(CardRank.Trey, CardSuit.Spades), 7); yield return new Tuple<Card, byte>(new Card(CardRank.Four, CardSuit.Clubs), 8); yield return new Tuple<Card, byte>(new Card(CardRank.Four, CardSuit.Diamonds), 9); yield return new Tuple<Card, byte>(new Card(CardRank.Four, CardSuit.Hearts), 10); yield return new Tuple<Card, byte>(new Card(CardRank.Four, CardSuit.Spades), 11); yield return new Tuple<Card, byte>(new Card(CardRank.Five, CardSuit.Clubs), 12); yield return new Tuple<Card, byte>(new Card(CardRank.Five, CardSuit.Diamonds), 13); yield return new Tuple<Card, byte>(new Card(CardRank.Five, CardSuit.Hearts), 14); yield return new Tuple<Card, byte>(new Card(CardRank.Five, CardSuit.Spades), 15); yield return new Tuple<Card, byte>(new Card(CardRank.Six, CardSuit.Clubs), 16); yield return new Tuple<Card, byte>(new Card(CardRank.Six, CardSuit.Diamonds), 17); yield return new Tuple<Card, byte>(new Card(CardRank.Six, CardSuit.Hearts), 18); yield return new Tuple<Card, byte>(new Card(CardRank.Six, CardSuit.Spades), 19); yield return new Tuple<Card, byte>(new Card(CardRank.Seven, CardSuit.Clubs), 20); yield return new Tuple<Card, byte>(new Card(CardRank.Seven, CardSuit.Diamonds), 21); yield return new Tuple<Card, byte>(new Card(CardRank.Seven, CardSuit.Hearts), 22); yield return new Tuple<Card, byte>(new Card(CardRank.Seven, CardSuit.Spades), 23); yield return new Tuple<Card, byte>(new Card(CardRank.Eight, CardSuit.Clubs), 24); yield return new Tuple<Card, byte>(new Card(CardRank.Eight, CardSuit.Diamonds), 25); yield return new Tuple<Card, byte>(new Card(CardRank.Eight, CardSuit.Hearts), 26); yield return new Tuple<Card, byte>(new Card(CardRank.Eight, CardSuit.Spades), 27); yield return new Tuple<Card, byte>(new Card(CardRank.Nine, CardSuit.Clubs), 28); yield return new Tuple<Card, byte>(new Card(CardRank.Nine, CardSuit.Diamonds), 29); yield return new Tuple<Card, byte>(new Card(CardRank.Nine, CardSuit.Hearts), 30); yield return new Tuple<Card, byte>(new Card(CardRank.Nine, CardSuit.Spades), 31); yield return new Tuple<Card, byte>(new Card(CardRank.Ten, CardSuit.Clubs), 32); yield return new Tuple<Card, byte>(new Card(CardRank.Ten, CardSuit.Diamonds), 33); yield return new Tuple<Card, byte>(new Card(CardRank.Ten, CardSuit.Hearts), 34); yield return new Tuple<Card, byte>(new Card(CardRank.Ten, CardSuit.Spades), 35); yield return new Tuple<Card, byte>(new Card(CardRank.Jack, CardSuit.Clubs), 36); yield return new Tuple<Card, byte>(new Card(CardRank.Jack, CardSuit.Diamonds), 37); yield return new Tuple<Card, byte>(new Card(CardRank.Jack, CardSuit.Hearts), 38); yield return new Tuple<Card, byte>(new Card(CardRank.Jack, CardSuit.Spades), 39); yield return new Tuple<Card, byte>(new Card(CardRank.Queen, CardSuit.Clubs), 40); yield return new Tuple<Card, byte>(new Card(CardRank.Queen, CardSuit.Diamonds), 41); yield return new Tuple<Card, byte>(new Card(CardRank.Queen, CardSuit.Hearts), 42); yield return new Tuple<Card, byte>(new Card(CardRank.Queen, CardSuit.Spades), 43); yield return new Tuple<Card, byte>(new Card(CardRank.King, CardSuit.Clubs), 44); yield return new Tuple<Card, byte>(new Card(CardRank.King, CardSuit.Diamonds), 45); yield return new Tuple<Card, byte>(new Card(CardRank.King, CardSuit.Hearts), 46); yield return new Tuple<Card, byte>(new Card(CardRank.King, CardSuit.Spades), 47); yield return new Tuple<Card, byte>(new Card(CardRank.Ace, CardSuit.Clubs), 48); yield return new Tuple<Card, byte>(new Card(CardRank.Ace, CardSuit.Diamonds), 49); yield return new Tuple<Card, byte>(new Card(CardRank.Ace, CardSuit.Hearts), 50); yield return new Tuple<Card, byte>(new Card(CardRank.Ace, CardSuit.Spades), 51); } } [Test, Description("Tests whether assumed card codes are correct")] public void TestCardCode([ValueSource("Codes")] Tuple<Card, byte> data) { Assert.AreEqual(data.Item2, data.Item1.Code, "Card code does not match."); } [Test] public void TestCardUrl([ValueSource("Codes")] Tuple<Card, byte> data) { CardImageModule module = new CardImageModule(null); string url = module.GetCardUrl(data.Item1); Match match = Regex.Match(url, "code=(?<code>[0-9]+)$"); Assert.That(match.Success); Assert.AreEqual(data.Item2, byte.Parse(match.Groups["code"].Value)); } [Test] public void TestResourcePath([ValueSource("Codes")] Tuple<Card, byte> data) { CardResourceHttpService service = new CardResourceHttpService(); string path = service.GetResourcePath(data.Item2); Match match = Regex.Match(path, "Card(?<code>[0-9]+)\\.png$"); Assert.That(match.Success); Assert.AreEqual(data.Item2 + 1, byte.Parse(match.Groups["code"].Value)); } } }
using LanchesMac.Models; using System.Collections.Generic; namespace LanchesMac.ViewModels { public class LancheListViewModel { public IEnumerable<Lanche> Lanches { get; set; } public string CategoriaAtual { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using GameSpark.Plus; namespace GameSpark { [System.Serializable] public class CameraSystem : GameSparkModule { List<GameCam> cams; private static CameraSystem manager; public CameraSettingData cameraSetting; public static CameraSystem GetInstance() { if (manager == null) { manager = new CameraSystem(); } return manager; } public void initilaze() { cams = new List<GameCam>(); for (int i = 0; i < cameraSetting.cams.Length; i++) { cams.Add(cameraSetting.cams[i].GetComponent<GameCam>()); cams[i].SetICam(new OffCam(), null); } } public void SetCamOff(string camName) { SetCam(camName, new OffCam(), null); } public void SetCam(string camName, FixedCamLayout layout) { SetCam(camName, new FixedCam(), layout); } public void SetCam(string camName, BasicFollowCamLayout layout) { SetCam(camName, new BasicFollowCam(), layout); } // For custom cam atribute public void SetCam(string camName, ICam atr, SparkCameraLayout layout) { for (int i = 0; i < cams.Count; i++) { if (cams[i].camName == camName) { cams[i].SetICam(atr, layout); break; } } } public GameCam GetCam(string camName) { foreach (GameCam x in cams) { if (x.camName == camName) { return x; } } return null; } private CameraSystem() { } } }
using System; using UnityEngine.SceneManagement; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; public class ViewpointChange : MonoBehaviour { [SerializeField] private GameObject _pivotCamera; [SerializeField] private GameObject _frontCamera; [SerializeField] private GameObject _upsideCamera; private int _keyCount; //切り替えキーを押した回数 void Start() { _pivotCamera.SetActive(true); _frontCamera.SetActive(false); _upsideCamera.SetActive(false); _keyCount = 0; } void Update() { if (SceneManager.GetActiveScene().name != "BattleCustom" && SceneManager.GetActiveScene().name != "TimeAttackCustom") { ViewChanging(); } } private void ViewChanging() { if (CrossPlatformInputManager.GetButtonDown("Camera")) { ++_keyCount; } switch (_keyCount) { case 0: _pivotCamera.SetActive(true); _upsideCamera.SetActive(false); break; case 1: _pivotCamera.SetActive(false); _frontCamera.SetActive(true); break; case 2: _frontCamera.SetActive(false); _upsideCamera.SetActive(true); break; default: _keyCount = 0;//0~2以外は0に戻す break; } } }
namespace Grunt.Models.HaloInfinite { public class BanResult { public object[] BansInEffect { get; set; } } }
using System.Xml; namespace Platform.Xml.Serialization { /// <summary> /// Abstract base class for classes that support serializing of objects. /// </summary> /// <remarks> /// Serializers of this type also support seralizing objects to a simple text representation. /// Only types are serialized with a TypeSerializerWithSimpleTextSupport can be serialized /// to an XML attribute. /// </remarks> public abstract class TypeSerializerWithSimpleTextSupport : TypeSerializer { public abstract string Serialize(object obj, SerializationContext state); public abstract object Deserialize(string value, SerializationContext state); public override void Serialize(object obj, XmlWriter writer, SerializationContext state) { writer.WriteString(Serialize(obj, state)); } public override object Deserialize(XmlReader reader, SerializationContext state) { var s = XmlReaderHelper.ReadCurrentNodeValue(reader); if (state.GetCurrentMemberInfo().Substitutor != null) { s = state.GetCurrentMemberInfo().Substitutor.Substitute(s); } return Deserialize(s, state); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Globalization; using Microsoft.WindowsAzure.Storage; namespace Dashboard.Data { public static class StorageAccountValidator { private const string HttpsEndpointScheme = "https"; [CLSCompliant(false)] public static bool ValidateAccountAccessible(CloudStorageAccount account) { if (account == null) { throw new ArgumentNullException("account"); } // Verify the credentials are correct. // Have to actually ping a storage operation. var client = account.CreateCloudBlobClient(); try { // This can hang for a long time if the account name is wrong. // If will fail fast if the password is incorrect. client.GetServiceProperties(); } catch (OperationCanceledException) { throw; } catch { return false; } return true; } [CLSCompliant(false)] public static bool ValidateEndpointsSecure(CloudStorageAccount account) { if (account == null) { throw new ArgumentNullException("account"); } if (!IsSecureEndpointProtocol(account.BlobEndpoint) || !IsSecureEndpointProtocol(account.QueueEndpoint)) { //For supporting local development with azure storage emulator return true; } return true; } private static bool IsSecureEndpointProtocol(Uri endpoint) { return String.Equals(endpoint.Scheme, HttpsEndpointScheme, StringComparison.OrdinalIgnoreCase); } } }
using Newtonsoft.Json; namespace DGP.Genshin.DataModel.Character { /// <summary> /// 角色统计值 /// </summary> [SuppressMessage("", "SA1134")] [SuppressMessage("", "SA1516")] [SuppressMessage("", "SA1600")] public class CharStatValues { [JsonProperty("1")] public string? Level1 { get; set; } [JsonProperty("20")] public string? Level20 { get; set; } [JsonProperty("20+")] public string? Level20p { get; set; } [JsonProperty("40")] public string? Level40 { get; set; } [JsonProperty("40+")] public string? Level40p { get; set; } [JsonProperty("50")] public string? Level50 { get; set; } [JsonProperty("50+")] public string? Level50p { get; set; } [JsonProperty("60")] public string? Level60 { get; set; } [JsonProperty("60+")] public string? Level60p { get; set; } [JsonProperty("70")] public string? Level70 { get; set; } [JsonProperty("70+")] public string? Level70p { get; set; } [JsonProperty("80")] public string? Level80 { get; set; } [JsonProperty("80+")] public string? Level80p { get; set; } [JsonProperty("90")] public string? Level90 { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Backgammon { public struct OneStep { public int _from; public int _to; public OneStep(int from, int to) { _from = from; _to = to; } } }
using System.Runtime.InteropServices; namespace QuickJS.Native { [StructLayout(LayoutKind.Sequential)] public struct JSClassID { private uint _value; public static implicit operator JSClassID(uint value) { return new JSClassID {_value = value}; } public static implicit operator uint(JSClassID value) { return value._value; } public override int GetHashCode() { return _value.GetHashCode(); } public override string ToString() { return _value.ToString(); } public override bool Equals(object obj) { if (obj is JSClassID) { return ((JSClassID) obj)._value == _value; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Security.AccessControl; using System.Security.Principal; namespace System.IO.Pipes { public sealed class PipeAccessRule : AccessRule { // // Constructor for creating access rules for pipe objects // public PipeAccessRule(string identity, PipeAccessRights rights, AccessControlType type) : this(new NTAccount(identity), AccessMaskFromRights(rights, type), false, type) { } public PipeAccessRule( IdentityReference identity, PipeAccessRights rights, AccessControlType type ) : this(identity, AccessMaskFromRights(rights, type), false, type) { } // // Internal constructor to be called by public constructors // and the access rights factory methods // internal PipeAccessRule( IdentityReference identity, int accessMask, bool isInherited, AccessControlType type ) : base( identity, accessMask, isInherited, InheritanceFlags.None, PropagationFlags.None, type ) { } public PipeAccessRights PipeAccessRights { get { return RightsFromAccessMask(base.AccessMask); } } // ACL's on pipes have a SYNCHRONIZE bit, and CreateFile ALWAYS asks for it. // So for allows, let's always include this bit, and for denies, let's never // include this bit unless we're denying full control. This is the right // thing for users, even if it does make the model look asymmetrical from a // purist point of view. internal static int AccessMaskFromRights( PipeAccessRights rights, AccessControlType controlType ) { if ( rights < (PipeAccessRights)0 || rights > (PipeAccessRights.FullControl | PipeAccessRights.AccessSystemSecurity) ) throw new ArgumentOutOfRangeException( nameof(rights), SR.ArgumentOutOfRange_NeedValidPipeAccessRights ); if (controlType == AccessControlType.Allow) { rights |= PipeAccessRights.Synchronize; } else if (controlType == AccessControlType.Deny) { if (rights != PipeAccessRights.FullControl) { rights &= ~PipeAccessRights.Synchronize; } } return (int)rights; } internal static PipeAccessRights RightsFromAccessMask(int accessMask) { return (PipeAccessRights)accessMask; } } }
namespace LPG2.Runtime { /** * Low-Level interface to act as recipient for error messages generated by a * parser/compiler. */ public interface IMessageHandler { /** * The following constants can be used as indexes to dereference * values in the msgLocation and errorLocation arrays. * * Locations are constructed by the method getLocation in LexStream which * takes two arguments: a start and an end location and returns an array * of 6 integers. */ static int OFFSET_INDEX = 0, LENGTH_INDEX = 1, START_LINE_INDEX = 2, START_COLUMN_INDEX = 3, END_LINE_INDEX = 4, END_COLUMN_INDEX = 5; /** * * When a location is undefined, the value of its offset is 0. * * @param errorCode * @param msgLocation * @param errorLocation * @param filename * @param errorInfo */ void handleMessage(int errorCode, int[] msgLocation, int[] errorLocation, string filename, string[] errorInfo); } }