content
stringlengths
23
1.05M
namespace CarsVelingrad.Services { using CarsVelingrad.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; public class WindowsFormService { private ApplicationDbContext dbContext; public WindowsFormService(ApplicationDbContext dbContext) { this.dbContext = dbContext; } public object[] GetBrands() { return this.dbContext.Brands.Select(x => x.Name).ToArray(); } public object[] GetModels() { return this.dbContext.Models.Select(x => x.Name).ToArray(); } public object[] GetVehicleTypes() { return this.dbContext.VehicleTypes.Select(x => x.Name).ToArray(); } public object[] GetEngineTypes() { return this.dbContext.EngineTypes.Select(x => x.Name).ToArray(); } } }
namespace DotnetModelFuzzing.Manipulations { public interface IGenerationManipulation<T> { T Manipulate(T input = default); } }
using System.Collections.Generic; public interface ISensor { float[] GetReceptors(); IEnumerable<string> GetLabels(); void OnRefresh(); void OnReset(); }
using System; using System.Threading.Tasks; using Newtonsoft.Json; using Microsoft.WindowsAzure.Storage.Table; using Streamstone; namespace Example.Scenarios { public class S06_Include_additional_entities : Scenario { public override async Task RunAsync() { var existent = await Stream.TryOpenAsync(Partition); var stream = existent.Found ? existent.Stream : new Stream(Partition); Console.WriteLine("Writing to new stream along with making snapshot in partition '{0}'", stream.Partition); var snapshot = Include.Insert(new InventoryItemShapshot { RowKey = "SNAPSHOT", Name = "iPhone7", Count = 100 - 50 - 40, Version = 5 }); var events = new[] { Event(new InventoryItemCreated(Id, "iPhone6")), Event(new InventoryItemCheckedIn(Id, 100)), Event(new InventoryItemCheckedOut(Id, 50)), Event(new InventoryItemRenamed(Id, "iPhone6", "iPhone7")), Event(new InventoryItemCheckedOut(Id, 40), snapshot) }; var result = await Stream.WriteAsync(stream, events); Console.WriteLine("Succesfully written to new stream.\r\nEtag: {0}, Version: {1}", result.Stream.ETag, result.Stream.Version); } static EventData Event(object @event, params Include[] includes) { var id = Guid.NewGuid(); var properties = new { Type = @event.GetType().Name, Data = JsonConvert.SerializeObject(@event) }; return new EventData( EventId.From(id), EventProperties.From(properties), EventIncludes.From(includes)); } class InventoryItemShapshot : TableEntity { public string Name { get; set; } public int Count { get; set; } public int Version { get; set; } } } }
using System.Collections.Generic; using UnityEngine; namespace com.liteninja.unityextensions { public static class IListExtensions { /// <summary> /// Pops element by index /// </summary> public static T Pop<T>(this IList<T> list, int index) { var element = list[index]; list.RemoveAt(index); return element; } /// <summary> /// Pops random element from list /// </summary> public static T PopRandom<T>(this IList<T> list) => Pop(list, Random.Range(0, list.Count)); } }
using AutoMapper; using LuizaLabs.Application.ViewModels; using LuizaLabs.Domain.Commands.Customer; namespace LuizaLabs.Application.AutoMapper { public class ViewModelToDomainMappingProfile : Profile { public ViewModelToDomainMappingProfile() { CreateMap<AddCustomerViewModel, AddNewCustomerCommand>() .ConstructUsing(c => new AddNewCustomerCommand(c.Name, c.Email)); CreateMap<CustomerViewModel, UpdateCustomerCommand>() .ConstructUsing(c => new UpdateCustomerCommand(c.Id, c.Name, c.Email)); } } }
using System; using System.Threading; using Xunit; using Yggrasil.Ai.BehaviorTree; using Yggrasil.Ai.BehaviorTree.Leafs; namespace Yggdrasil.Test.AI.BehaviorTree.Leafs { public class WaitTests { [Fact] public void Wait_2000() { var state = new State(); var waitTime = 2000; var routine = new Wait(TimeSpan.FromMilliseconds(waitTime)); Assert.Equal(RoutineStatus.Running, routine.Act(state)); Thread.Sleep(1000); Assert.Equal(RoutineStatus.Running, routine.Act(state)); Thread.Sleep(1100); Assert.Equal(RoutineStatus.Success, routine.Act(state)); } [Fact] public void Wait_0() { var state = new State(); var waitTime = 0; var routine = new Wait(TimeSpan.FromMilliseconds(waitTime)); Assert.Equal(RoutineStatus.Success, routine.Act(state)); Thread.Sleep(1000); Assert.Equal(RoutineStatus.Success, routine.Act(state)); } } }
using UnityEngine; namespace CVRLabSJSU { public class DebugLogHelper : MonoBehaviour { public void DebugLog(string message) { Debug.Log(message); } public void DebugLog(float value) { Debug.Log(value); } } }
using SimControls.Model; using SimControls.Model.CompositeElements; using Xunit; namespace SimControls.Test.Model { public class TwoStepDoubleItemTest { private readonly DataItem<double> innerItem = new(); private readonly TwoStepDoubleItem sut; public TwoStepDoubleItemTest() { sut = new TwoStepDoubleItem( innerItem, ConstantDataItem.FromValue(0.0), ConstantDataItem.FromValue(100d), ConstantDataItem.FromValue(2.0), ConstantDataItem.FromValue(10.0)); } [Fact] public void IncrementTest() { sut.BigIncrement(); Assert.Equal(10.0, sut.Value); sut.BigIncrement(); Assert.Equal(20, sut.Value); } [Fact] public void DecrementTest() { sut.Value = 50; sut.BigDecrement(); Assert.Equal(40, sut.Value); } } }
using System; namespace Job.Logger.Services.Flags { [Flags] public enum ProviderKind { None = 0, File = 1, Console = 2, Database = 4, All = 7 } }
using System; using Psh; /// <summary>PshGP executes a genetic programming run using the given parameter file.</summary> /// <remarks> /// PshGP executes a genetic programming run using the given parameter file. More /// information about parameter files can be found in the README. /// </remarks> public class PshGP { /* * Copyright 2009-2010 Jon Klein * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <exception cref="System.Exception"/> public static void Main(string[] args) { if (args.Length != 1 && args.Length != 3) { Console.Out.WriteLine("Usage: PshGP paramfile [testprogram testcasenumber]"); System.Environment.Exit(0); } Console.Out.WriteLine("Hi"); GA ga = null; // if (args[0].EndsWith(".gz")) // { // ga = GA.GAWithCheckpoint(args[0]); // } // else { ga = GA.GAWithParameters(Params.ReadFromFile(args[0])); } if (args.Length == 3) { // Execute a test program Program p = new Program(args[1]); ((PushGP)ga).RunTestProgram(p, System.Convert.ToInt32(args[2])); } else { // Execute a GP run. ga.Run(); } } }
using System.Text.Json.Serialization; namespace Horizon.Payment.Alipay.Domain { /// <summary> /// BakingItemOperationData Data Structure. /// </summary> public class BakingItemOperationData : AlipayObject { /// <summary> /// 累计库存 /// </summary> [JsonPropertyName("accumulate_inventory")] public string AccumulateInventory { get; set; } /// <summary> /// 操作后库存 /// </summary> [JsonPropertyName("ending_inventory")] public string EndingInventory { get; set; } /// <summary> /// 操作后位置,传中文或id均可 /// </summary> [JsonPropertyName("ending_position")] public string EndingPosition { get; set; } /// <summary> /// 商品毛利率,百分比毛利率*100 /// </summary> [JsonPropertyName("gross_profit_margin")] public string GrossProfitMargin { get; set; } /// <summary> /// 操作前库存 /// </summary> [JsonPropertyName("opening_inventory")] public string OpeningInventory { get; set; } /// <summary> /// 操作名称;如果是示例值中的操作请按示例值英文传递,其他操作自行传递有意义的英文 /// </summary> [JsonPropertyName("operation_name")] public string OperationName { get; set; } /// <summary> /// 操作数量 /// </summary> [JsonPropertyName("operation_num")] public string OperationNum { get; set; } /// <summary> /// 操作时间 /// </summary> [JsonPropertyName("operation_time")] public string OperationTime { get; set; } /// <summary> /// 操作人,传中文或id均可 /// </summary> [JsonPropertyName("operator")] public string Operator { get; set; } /// <summary> /// 商品批次 /// </summary> [JsonPropertyName("sku_batch")] public string SkuBatch { get; set; } /// <summary> /// 商品id /// </summary> [JsonPropertyName("sku_id")] public string SkuId { get; set; } /// <summary> /// 商品名称 /// </summary> [JsonPropertyName("sku_name")] public string SkuName { get; set; } /// <summary> /// 商品制作时长,单位为秒 /// </summary> [JsonPropertyName("sku_production_time")] public long SkuProductionTime { get; set; } /// <summary> /// 商品售卖价格 /// </summary> [JsonPropertyName("sku_selling_price")] public string SkuSellingPrice { get; set; } /// <summary> /// 操作前位置,传中文或id均可 /// </summary> [JsonPropertyName("starting_position")] public string StartingPosition { get; set; } } }
using System; using UnityEngine; using System.Collections.Generic; public class AssetBundleManager { private readonly Main _main; public GameObject FrontCarGo; public GameObject BackCarGo; public GameObject[] Support_Go; public GameObject[] AngledSupportGo; public GameObject SupportHalf; private readonly AssetBundle assetBundle; public AssetBundleManager (Main main) { this._main = main; var dsc = System.IO.Path.DirectorySeparatorChar; assetBundle = AssetBundle.LoadFromFile(_main.Path + dsc + "assetbundle" + dsc + "reel"); FrontCarGo = assetBundle.LoadAsset<GameObject> ("Front_Car"); BackCarGo = assetBundle.LoadAsset<GameObject> ("Cart"); Support_Go = new GameObject[] { assetBundle.LoadAsset<GameObject> ("Support_1"), assetBundle.LoadAsset<GameObject> ("Support_2"), assetBundle.LoadAsset<GameObject> ("Support_3 1") }; AngledSupportGo = new GameObject[] { assetBundle.LoadAsset<GameObject>("Angle_support_1"), assetBundle.LoadAsset<GameObject>("Angle_support_2") }; SupportHalf = assetBundle.LoadAsset<GameObject> ("Half_Support"); assetBundle.Unload(false); } }
using SystemDot.Messaging.Packaging; namespace SystemDot.Messaging.Direct { public class DirectChannelMessageHeader : IMessageHeader { } }
/* * Copyright (c) 2014, Furore (info@furore.com) and contributors * See the file CONTRIBUTORS for details. * * This file is licensed under the BSD 3-Clause license * available at https://raw.github.com/furore-fhir/spark/master/LICENSE */ using Hl7.Fhir.Model; using Hl7.Fhir.Rest; using System; using System.Collections.Generic; // mh: KeyExtensions terugverplaatst naar Spark.Engine.Core omdat ze in dezelfde namespace moeten zitten als Key. namespace Spark.Engine.Core { public static class KeyExtensions { public static Key ExtractKey(this Resource resource) { string _base = resource.ResourceBase?.ToString(); Key key = new Key(_base, resource.TypeName, resource.Id, resource.VersionId); return key; } public static Key ExtractKey(Uri uri) { var identity = new ResourceIdentity(uri); string _base = (identity.HasBaseUri) ? identity.BaseUri.ToString() : null; Key key = new Key(_base, identity.ResourceType, identity.Id, identity.VersionId); return key; } public static Key ExtractKey(this Localhost localhost, Bundle.EntryComponent entry) { Uri uri = new Uri(entry.Request.Url, UriKind.RelativeOrAbsolute); return localhost.LocalUriToKey(uri); } public static void ApplyTo(this IKey key, Resource resource) { resource.ResourceBase = key.HasBase() ? new Uri(key.Base) : null; resource.Id = key.ResourceId; resource.VersionId = key.VersionId; } public static Key Clone(this IKey self) { Key key = new Key(self.Base, self.TypeName, self.ResourceId, self.VersionId); return key; } public static bool HasBase(this IKey key) { return !string.IsNullOrEmpty(key.Base); } public static Key WithBase(this IKey self, string _base) { Key key = self.Clone(); key.Base = _base; return key; } public static Key WithoutBase(this IKey self) { Key key = self.Clone(); key.Base = null; return key; } public static Key WithoutVersion(this IKey self) { Key key = self.Clone(); key.VersionId = null; return key; } public static bool HasVersionId(this IKey self) { return !string.IsNullOrEmpty(self.VersionId); } public static bool HasResourceId(this IKey self) { return !string.IsNullOrEmpty(self.ResourceId); } public static IKey WithoutResourceId(this IKey self) { var key = self.Clone(); key.ResourceId = null; return key; } /// <summary> /// If an id is provided, the server SHALL ignore it. /// If the request body includes a meta, the server SHALL ignore /// the existing versionId and lastUpdated values. /// http://hl7.org/fhir/STU3/http.html#create /// http://hl7.org/fhir/R4/http.html#create /// </summary> public static IKey CleanupForCreate(this IKey key) { if (key.HasResourceId()) { key = key.WithoutResourceId(); } if (key.HasVersionId()) { key = key.WithoutVersion(); } return key; } public static IEnumerable<string> GetSegments(this IKey key) { if (key.Base != null) yield return key.Base; if (key.TypeName != null) yield return key.TypeName; if (key.ResourceId != null) yield return key.ResourceId; if (key.VersionId != null) { yield return "_history"; yield return key.VersionId; } } public static string ToUriString(this IKey key) { var segments = key.GetSegments(); return string.Join("/", segments); } public static string ToOperationPath(this IKey self) { Key key = self.WithoutBase(); return key.ToUriString(); } /// <summary> /// A storage key is a resource reference string that is ensured to be server wide unique. /// This way resource can refer to eachother at a database level. /// These references are also used in SearchResult lists. /// The format is "resource/id/_history/vid" /// </summary> /// <returns>a string</returns> public static string ToStorageKey(this IKey key) { return key.WithoutBase().ToUriString(); } public static Key CreateFromLocalReference(string reference) { string[] parts = reference.Split('/'); if (parts.Length == 2) { return Key.Create(parts[0], parts[1], parts[3]); } else if (parts.Length == 4) { return Key.Create(parts[0], parts[1], parts[3]); } else throw new ArgumentException("Could not create key from local-reference: " + reference); } public static Uri ToRelativeUri(this IKey key) { string path = key.ToOperationPath(); return new Uri(path, UriKind.Relative); } public static Uri ToUri(this IKey self) { return new Uri(self.ToUriString(), UriKind.RelativeOrAbsolute); } public static Uri ToUri(this IKey key, Uri endpoint) { string _base = endpoint.ToString().TrimEnd('/'); string s = string.Format("{0}/{1}", _base, key); return new Uri(s); } /// <summary> /// Determines if the Key was constructed from a temporary id. /// </summary> public static bool IsTemporary(this IKey key) { if (key.ResourceId != null) { return UriHelper.IsTemporaryUri(key.ResourceId); } else return false; } /// <summary> /// Value equality for two IKey's /// </summary> /// <returns>true if all parts of of the keys are the same</returns> public static bool EqualTo(this IKey key, IKey other) { return (key.Base == other.Base) && (key.TypeName == other.TypeName) && (key.ResourceId == other.ResourceId) && (key.VersionId == other.VersionId); } } }
using Sharpen; namespace android.net { [Sharpen.NakedStub] public class UrlQuerySanitizer { [Sharpen.NakedStub] public class ParameterValuePair { } [Sharpen.NakedStub] public interface ValueSanitizer { } [Sharpen.NakedStub] public class IllegalCharacterValueSanitizer { } } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. Licensed under the MIT license. //---------------------------------------------------------------- namespace Microsoft.Azure.Documents.ChangeFeedProcessor.FeedProcessing { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; internal class AutoCheckpointer : IChangeFeedObserver { private readonly CheckpointFrequency checkpointFrequency; private readonly IChangeFeedObserver observer; private int processedDocCount; private DateTime lastCheckpointTime = DateTime.UtcNow; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, IChangeFeedObserver observer) { if (checkpointFrequency == null) throw new ArgumentNullException(nameof(checkpointFrequency)); if (observer == null) throw new ArgumentNullException(nameof(observer)); this.checkpointFrequency = checkpointFrequency; this.observer = observer; } public Task OpenAsync(IChangeFeedObserverContext context) { return this.observer.OpenAsync(context); } public Task CloseAsync(IChangeFeedObserverContext context, ChangeFeedObserverCloseReason reason) { return this.observer.CloseAsync(context, reason); } public async Task ProcessChangesAsync(IChangeFeedObserverContext context, IReadOnlyList<Document> docs, CancellationToken cancellationToken) { await this.observer.ProcessChangesAsync(context, docs, cancellationToken).ConfigureAwait(false); this.processedDocCount += docs.Count; if (this.IsCheckpointNeeded()) { await context.CheckpointAsync().ConfigureAwait(false); this.processedDocCount = 0; this.lastCheckpointTime = DateTime.UtcNow; } } private bool IsCheckpointNeeded() { if (!this.checkpointFrequency.ProcessedDocumentCount.HasValue && !this.checkpointFrequency.TimeInterval.HasValue) { return true; } if (this.processedDocCount >= this.checkpointFrequency.ProcessedDocumentCount) return true; TimeSpan delta = DateTime.UtcNow - this.lastCheckpointTime; if (delta >= this.checkpointFrequency.TimeInterval) return true; return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; namespace IronPlot { public class MarkersVisualHost : FrameworkElement { VisualCollection visualChildren; DrawingVisual markers = new DrawingVisual(); public MarkersVisualHost() { visualChildren = new VisualCollection(this); UpdateMarkersVisual(null); visualChildren.Add(markers); } void UpdateMarkersVisual(Geometry geometry) { DrawingContext context = markers.RenderOpen(); context.DrawRectangle(Brushes.Red, new Pen(Brushes.Red, 1), new Rect(30, 30, 30, 30)); context.Close(); } protected override int VisualChildrenCount { get { return visualChildren.Count; } } protected override Visual GetVisualChild(int index) { if (index < 0 || index >= visualChildren.Count) throw new ArgumentOutOfRangeException("index"); return visualChildren[index]; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MicroService.TeamService.Models { /// <summary> /// 团队成员模型 /// </summary> public class Member { /// <summary> /// 团队成员主键 /// </summary> public int Id { set; get; } /// <summary> /// 团队成员名 /// </summary> public string FirstName { set; get; } /// <summaryhua /// 团队成员花名 /// </summary> public string NickName { set; get; } /// <summary> /// 团队主键 /// </summary> public int TeamId { set; get; } } }
using NetSales.Entitys.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NetSales.Entitys.Tables { // fiş tablosu public class Slip:IEntity { public int Id { get; set; } public string SlipCode { get; set; } public string SlipType { get; set; } public string CurrentCode { get; set; } public string CurrentName { get; set; } public string DocumentNo { get; set; } public DateTime Date { get; set; } public string SalesMan { get; set; } //Plasiyer, satış elemanı public string SalesManName { get; set; } public decimal DiscountRate { get; set; } //indirim public decimal DiscountAmount { get; set; } //indirim tutarı public decimal TotalAmount { get; set; } // toplam tutar public string Comment { get; set; } // açıklama } }
 namespace BusinessLayer.DTO { public class BandReviewDTO : ReviewDTO { public int BandId { get; set; } } }
using System; using System.Threading.Tasks; using ReactiveUI; namespace NeptunLight.Services { public interface IRefreshManager : IReactiveObject { bool IsRefreshing { get; set; } DateTime LastRefreshTime { get; set; } Task RefreshAsync(); Task RefreshIfNeeded(); } }
using System.Threading.Tasks; namespace HousingFinanceInterimApi.V1.Gateways.Interface { /// <summary> /// The UP cash file name gateway interface. /// </summary> public interface IUPCashLoadGateway { public Task LoadCashFiles(); } }
using DurableDice.Common.Models.Commands; namespace DurableDice.Common.Abstractions; public interface IGameEntity { Task AddPlayerAsync(AddPlayerCommand command); Task AttackFieldAsync(AttackMoveCommand command); Task EndRoundAsync(string playerId); Task RemovePlayerAsync(string playerId); Task ReadyAsync(string playerId); }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace MSt.Data.Entity { /// <summary> /// User used to identify a authenticated user /// </summary> public class User { /// <summary> /// ID User /// </summary> [Key] public Guid Guid { get; set; } /// <summary> /// User Login /// </summary> [Required] [MaxLength(50)] public string Login { get; set; } /// <summary> /// Password for login /// </summary> [Required] [MaxLength(50)] public string Password { get; set; } /// <summary> /// User email /// </summary> [Required] [MaxLength(50)] public string Email { get; set; } /// <summary> /// Collection of claims of the user /// </summary> public ICollection<UserClaim> UserClaims { get; set; } /// <summary> /// Collection of the roles of the user /// </summary> public ICollection<UserRole> UserRoles { get; set; } /// <summary> /// If the user is deleted /// </summary> public bool IsDeleted { get; set; } } }
using System; namespace RootSE.ORM { [Serializable] public class RepositoryException : Exception { public RepositoryException(string message) : base(message) { } } [Serializable] public class RepositoryException<InstanceT> : RepositoryException { public RepositoryException(string message) : base(typeof(InstanceT) + " repository: " + message) { } } }
namespace CurrencyRateAgregator.Api.Services.BY { using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; using CurrencyRateAgregator.Api.Models; public class ProviderBY : IProvider { private const string _apiurl = "https://www.nbrb.by/api/exrates/rates?periodicity=0"; private readonly HttpClient _client = new HttpClient(); public IEnumerable<CurrencyRate> GetCurrencyRates() { var t = Task.Run<IEnumerable<CurrencyRate>>(async () => await GetCurrencyRatesAsync()); return t.Result; } public async Task<IEnumerable<CurrencyRate>> GetCurrencyRatesAsync() { var streamTask = _client.GetStreamAsync(_apiurl); var repositories = await JsonSerializer.DeserializeAsync<List<CurrencyRateNbrb>>(await streamTask); var r = new List<CurrencyRate>(); foreach (var currencyBY in repositories) { Currency currency; try { currency = (Currency)Enum.Parse( typeof(Currency), currencyBY.Cur_Abbreviation, ignoreCase: true ); } catch (ArgumentNullException) { continue; } catch (ArgumentException) { continue; } catch (OverflowException) { continue; } r.Add(new CurrencyRate { Currency = currency, Date = currencyBY.Date, Rate = currencyBY.Cur_OfficialRate, Scale = currencyBY.Cur_Scale }); } return r; } } }
using System; using System.Collections.Generic; using HotChocolate.Configuration; using HotChocolate.Language; using HotChocolate.Properties; using HotChocolate.Types.Descriptors; namespace HotChocolate.Types.Factories { internal class SchemaSyntaxVisitor : SchemaSyntaxWalker<object> { private readonly ObjectTypeFactory _objectTypeFactory = new ObjectTypeFactory(); private readonly ObjectTypeExtensionFactory _objectTypeExtensionFactory = new ObjectTypeExtensionFactory(); private readonly InterfaceTypeFactory _interfaceTypeFactory = new InterfaceTypeFactory(); private readonly InterfaceTypeExtensionFactory _interfaceTypeExtensionFactory = new InterfaceTypeExtensionFactory(); private readonly UnionTypeFactory _unionTypeFactory = new UnionTypeFactory(); private readonly UnionTypeExtensionFactory _unionTypeExtensionFactory = new UnionTypeExtensionFactory(); private readonly InputObjectTypeFactory _inputObjectTypeFactory = new InputObjectTypeFactory(); private readonly InputObjectTypeExtensionFactory _inputObjectTypeExtensionFactory = new InputObjectTypeExtensionFactory(); private readonly EnumTypeFactory _enumTypeFactory = new EnumTypeFactory(); private readonly EnumTypeExtensionFactory _enumTypeExtensionFactory = new EnumTypeExtensionFactory(); private readonly DirectiveTypeFactory _directiveTypeFactory = new DirectiveTypeFactory(); private readonly List<ITypeReference> _types = new List<ITypeReference>(); private readonly IBindingLookup _bindingLookup; public SchemaSyntaxVisitor(IBindingLookup bindingLookup) { _bindingLookup = bindingLookup ?? throw new ArgumentNullException(nameof(bindingLookup)); } public string QueryTypeName { get; private set; } public string MutationTypeName { get; private set; } public string SubscriptionTypeName { get; private set; } public string Description { get; private set; } public IReadOnlyCollection<DirectiveNode> Directives { get; private set; } public IReadOnlyList<ITypeReference> Types => _types; protected override void VisitObjectTypeDefinition( ObjectTypeDefinitionNode node, object context) { _types.Add(SchemaTypeReference.Create( _objectTypeFactory.Create(_bindingLookup, node))); } protected override void VisitObjectTypeExtension( ObjectTypeExtensionNode node, object context) { _types.Add(SchemaTypeReference.Create( _objectTypeExtensionFactory.Create(_bindingLookup, node))); } protected override void VisitInterfaceTypeDefinition( InterfaceTypeDefinitionNode node, object context) { _types.Add(SchemaTypeReference.Create( _interfaceTypeFactory.Create(_bindingLookup, node))); } protected override void VisitInterfaceTypeExtension( InterfaceTypeExtensionNode node, object context) { _types.Add(SchemaTypeReference.Create( _interfaceTypeExtensionFactory.Create(_bindingLookup, node))); } protected override void VisitUnionTypeDefinition( UnionTypeDefinitionNode node, object context) { _types.Add(SchemaTypeReference.Create( _unionTypeFactory.Create(_bindingLookup, node))); } protected override void VisitUnionTypeExtension( UnionTypeExtensionNode node, object context) { _types.Add(SchemaTypeReference.Create( _unionTypeExtensionFactory.Create(_bindingLookup, node))); } protected override void VisitInputObjectTypeDefinition( InputObjectTypeDefinitionNode node, object context) { _types.Add(SchemaTypeReference.Create( _inputObjectTypeFactory.Create(_bindingLookup, node))); } protected override void VisitInputObjectTypeExtension( InputObjectTypeExtensionNode node, object context) { _types.Add(SchemaTypeReference.Create( _inputObjectTypeExtensionFactory.Create(_bindingLookup, node))); } protected override void VisitEnumTypeDefinition( EnumTypeDefinitionNode node, object context) { _types.Add(SchemaTypeReference.Create( _enumTypeFactory.Create(_bindingLookup, node))); } protected override void VisitEnumTypeExtension( EnumTypeExtensionNode node, object context) { _types.Add(SchemaTypeReference.Create( _enumTypeExtensionFactory.Create(_bindingLookup, node))); } protected override void VisitDirectiveDefinition( DirectiveDefinitionNode node, object context) { _types.Add(SchemaTypeReference.Create( _directiveTypeFactory.Create(_bindingLookup, node))); } protected override void VisitSchemaDefinition( SchemaDefinitionNode node, object context) { Description = node.Description?.Value; Directives = node.Directives; foreach (OperationTypeDefinitionNode operationType in node.OperationTypes) { switch (operationType.Operation) { case OperationType.Query: QueryTypeName = operationType.Type.Name.Value; break; case OperationType.Mutation: MutationTypeName = operationType.Type.Name.Value; break; case OperationType.Subscription: SubscriptionTypeName = operationType.Type.Name.Value; break; default: throw new InvalidOperationException( TypeResources.SchemaSyntaxVisitor_UnknownOperationType); } } } } }
// --------------------------------------------------------------------------------------- // ILGPU // Copyright (c) 2020-2021 ILGPU Project // www.ilgpu.net // // File: CLKernelTypeGenerator.cs // // This file is part of ILGPU and is distributed under the University of Illinois Open // Source License. See LICENSE.txt for details. // --------------------------------------------------------------------------------------- using ILGPU.Backends.EntryPoints; using ILGPU.IR; using ILGPU.IR.Types; using ILGPU.IR.Values; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace ILGPU.Backends.OpenCL { /// <summary> /// Generates OpenCL type structures that can be used for data marshaling data. /// </summary> sealed class CLKernelTypeGenerator : ICLTypeGenerator { #region Constants /// <summary> /// The string format of a single structure-like type. /// </summary> private const string KernelTypeNameSuffix = "_kernel"; #endregion #region Nested Types /// <summary> /// Replaces pointers with an integer index offsets. /// </summary> private sealed class CLKernelTypeConverter : TypeConverter<PointerType> { /// <summary> /// Converts a pointer to an index argument for kernel-argument mapping. /// </summary> protected override TypeNode ConvertType<TTypeContext>( TTypeContext typeContext, PointerType type) => typeContext.GetPrimitiveType(BasicValueType.Int32); /// <summary> /// The result will consume one field. /// </summary> protected override int GetNumFields(PointerType type) => 1; } #endregion #region Instance private readonly CLKernelTypeConverter typeConverter; private readonly (StructureType, string)[] parameterTypes; /// <summary> /// Constructs a new type generator and defines all internal types for the /// OpenCL backend. /// </summary> /// <param name="typeGenerator">The parent type generator.</param> /// <param name="entryPoint">The current entry point.</param> public CLKernelTypeGenerator( CLTypeGenerator typeGenerator, SeparateViewEntryPoint entryPoint) { TypeGenerator = typeGenerator; EntryPoint = entryPoint; ParameterOffset = entryPoint.KernelIndexParameterOffset; typeConverter = new CLKernelTypeConverter(); parameterTypes = new (StructureType, string)[ entryPoint.Parameters.Count + ParameterOffset]; } #endregion #region Properties /// <summary> /// Returns the parent type generator to use. /// </summary> public CLTypeGenerator TypeGenerator { get; } /// <summary> /// Returns the associated entry point. /// </summary> public SeparateViewEntryPoint EntryPoint { get; } /// <summary> /// Returns the current parameter offset. /// </summary> public int ParameterOffset { get; } /// <summary> /// Returns the associated OpenCL type name. /// </summary> /// <param name="parameter">The IR parameter.</param> /// <returns>The resolved OpenCL type name.</returns> public string this[Parameter parameter] { get { var (_, typeName) = parameterTypes[parameter.Index]; if (typeName != null) return typeName; // Resolve base type name from the parent type generator return TypeGenerator[parameter.ParameterType]; } } #endregion #region Methods /// <summary> /// Registers a new kernel parameter. /// </summary> /// <param name="parameter">The parameter to register.</param> public void Register(Parameter parameter) { ref var parameterType = ref parameterTypes[parameter.Index]; parameter.Assert(parameterType.Item1 is null); // Check whether we require a custom mapping if (!EntryPoint.TryGetViewParameters( parameter.Index - ParameterOffset, out var _)) { return; } // Resolve base type name from the parent type generator var clName = TypeGenerator[parameter.ParameterType]; // Adjust the current type name clName += KernelTypeNameSuffix; // Retrieve structure type var structureType = parameter.ParameterType.As<StructureType>(parameter); // Convert the kernel type using a specific type converter structureType = typeConverter.ConvertType( TypeGenerator.TypeContext, structureType) as StructureType; // Register internally parameterTypes[parameter.Index] = (structureType, clName); } /// <summary> /// Generate all forward type declarations. /// </summary> /// <param name="builder">The target builder.</param> public void GenerateTypeDeclarations(StringBuilder builder) { foreach (var (_, typeName) in parameterTypes) { if (typeName == null) continue; builder.Append(typeName); builder.AppendLine(";"); } builder.AppendLine(); } /// <summary> /// Generate all type definitions. /// </summary> /// <param name="builder">The target builder.</param> public void GenerateTypeDefinitions(StringBuilder builder) { var generatedTypes = new HashSet<string>(); for ( int paramIdx = ParameterOffset, numParams = parameterTypes.Length; paramIdx < numParams; ++paramIdx) { // Check for registered types var (type, typeName) = parameterTypes[paramIdx]; if (type == null || !generatedTypes.Add(typeName)) continue; #if DEBUG // Get the current view mapping var viewMapping = EntryPoint.GetViewParameters( paramIdx - ParameterOffset); Debug.Assert( viewMapping.Count > 0, "There must be at least one view entry"); for ( int i = 0, specialParamIdx = 0, e = type.NumFields; i < e && specialParamIdx < viewMapping.Count; ++i) { // Check whether the current field is a view pointer if (viewMapping[specialParamIdx].TargetAccess.Index == i) { Debug.Assert( type[i].BasicValueType == BasicValueType.Int32, "Invalid view index"); } } #endif TypeGenerator.GenerateStructureDefinition( type, typeName, builder); } builder.AppendLine(); } #endregion } }
using System; using System.Reflection; using EasyNetQ; using EasyNetQ.AutoSubscribe; using EasyNetQ.DI; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Sikiro.Bus.Extension { public static class IocExtension { public static IServiceCollection AddEasyNetQ(this IServiceCollection services, string connectionStr) { services.AddSingleton(RabbitHutch.CreateBus(connectionStr, a => a.EnableLegacyDeadLetterExchangeAndMessageTtlScheduler())); return services; } public static IServiceCollection AddEasyNetQ(this IServiceCollection services, string connectionStr, Action<IServiceRegister> registerServices) { services.AddSingleton(RabbitHutch.CreateBus(connectionStr, registerServices)); return services; } public static IApplicationBuilder UseAutoSubscribe(this IApplicationBuilder appBuilder, IHostApplicationLifetime lifetime, Assembly[] assemblies, string subscriptionIdPrefix = "") { var bus = appBuilder.ApplicationServices.GetService<IBus>(); lifetime.ApplicationStarted.Register(() => { var subscriber = new AutoSubscriber(bus, subscriptionIdPrefix); subscriber.Subscribe(assemblies); subscriber.SubscribeAsync(assemblies); }); lifetime.ApplicationStopped.Register(() => bus.Dispose()); return appBuilder; } public static IApplicationBuilder UseAutoSubscribe(this IApplicationBuilder appBuilder, IHostApplicationLifetime lifetime, string subscriptionIdPrefix) { return UseAutoSubscribe(appBuilder, lifetime, new[] { Assembly.GetEntryAssembly() }, subscriptionIdPrefix); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Logic; using System.Collections.Generic; namespace Tests { [TestClass] public class Day23Tests { private List<int> input = new List<int> { 4, 8, 7, 9, 1, 2, 3, 6, 5 }; [TestMethod] public void Day23Part1Example1Test() { var day23 = new Day23(); var actual = day23.Part1(new List<int> { 3, 8, 9, 1, 2, 5, 4, 6, 7 }, 10); var expected = 92658374; Assert.AreEqual(expected, actual); } [TestMethod] public void Day23Part1Example2Test() { var day23 = new Day23(); var actual = day23.Part1(new List<int> { 3, 8, 9, 1, 2, 5, 4, 6, 7 }, 100); var expected = 67384529; Assert.AreEqual(expected, actual); } [TestMethod] public void Day23Part1Test() { var day23 = new Day23(); var actual = day23.Part1(input, 100); var expected = 89573246; Assert.AreEqual(expected, actual); } [TestMethod] public void Day23Part2Test() { var day23 = new Day23(); var actual = day23.Part2(input, 10000000); var expected = 2029056128; Assert.AreEqual(expected, actual); } } }
using System; namespace NvimClient.API.NvimPlugin.Attributes { [AttributeUsage(AttributeTargets.Method)] public class NvimCommandAttribute : Attribute { public string Addr { get; set; } public string Complete { get; set; } public long Count { get; set; } public string Eval { get; set; } public string Range { get; set; } public bool Register { get; set; } public string NArgs { get; set; } public string Name { get; set; } public bool Bar { get; set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace RightClickAmplifier { public partial class FrmMakroEditor : Form { ContextMakro oldMakro; ContextMakro newMakro; public FrmMakroEditor() { InitializeComponent(); } private void FrmMakroEditor_Load(object sender, EventArgs e) { ShowMakro(newMakro); //presets cboxPresets.Items.Clear(); cboxPresets.Items.Add("Custom"); cboxPresets.SelectedIndex = 0; foreach ( var preset in ContextFunction.GetAllPresets()) { cboxPresets.Items.Add(preset); } } private void ShowMakro(ContextMakro makro) { txtMakroName.Text = makro.Name; customListBox1.Items.Clear(); foreach (var function in makro.Functions) { customListBox1.Items.Add(function); } txtExtensions.Text = string.Join(" ", makro.FileExtensions); } public ContextMakro ShowDialog(ContextMakro editMakro) { oldMakro = editMakro; if(oldMakro == null) { newMakro = new ContextMakro(); } else { newMakro = oldMakro.Clone(); } base.ShowDialog(); return oldMakro; } private void cmdSaveMakro_Click(object sender, EventArgs e) { if (oldMakro == null) oldMakro = newMakro; oldMakro.Name = txtMakroName.Text; oldMakro.Functions = new List<ContextFunction>(); foreach (var function in customListBox1.Items) { oldMakro.Functions.Add((ContextFunction)function); } oldMakro.FileExtensions = new List<CString>(); foreach(string extens in txtExtensions.Text.Trim(' ').Split(' ')) { oldMakro.FileExtensions.Add(new CString(extens)); } this.Close(); } private void customListBox1_ButtonEditClick(object sender, EventArgs e) { ContextFunction oldConFunc = ((Control)sender).Tag as ContextFunction; ContextFunction newConFunc = (new FrmFunctionEditor()).ShowDialog(oldConFunc); int idx = customListBox1.Items.IndexOf(((Control)sender).Tag); customListBox1.Items.RemoveAt(idx); if (newConFunc != null) { customListBox1.Items.Insert(idx, newConFunc); } } private void cmdAddFunction_Click(object sender, EventArgs e) { ContextFunction newConFunc = (new FrmFunctionEditor()).ShowDialog(null); if (newConFunc != null) { customListBox1.Items.Add(newConFunc); } } private void customListBox1_ButtonDeleteClick(object sender, EventArgs e) { var function = ((Control)sender).Tag as ContextFunction; if (function != null) { customListBox1.Items.Remove(function); } } private void cboxPresets_SelectedIndexChanged(object sender, EventArgs e) { if(cboxPresets.SelectedIndex >= 0) { ContextMakro selMakro = cboxPresets.SelectedItem as ContextMakro; if(selMakro != null) { newMakro = selMakro; ShowMakro(newMakro); } } } } }
using System; using System.Collections.Generic; using Xamarin.Forms; namespace CyberEyes { public partial class EndScreenPage : ContentPage { public EndScreenPage() { InitializeComponent(); finalPhoto.Source = ImageSource.FromResource("CyberEyes.Images.finalImage.jpg"); var appData = (ScavengerHuntManager)BindingContext; TimeSpan t = TimeSpan.FromSeconds(appData.TimeLeftInSeconds); fTime.Text = String.Format("Time Left: {0:D2}:{1:D2}", t.Minutes, t.Seconds); fFound.Text = String.Format("Items Found: {0}/{1}", appData.ItemsFilled, appData.TotalItems); fPoints.Text = String.Format("Total Points: {0}/{1}", appData.TotalPoints, appData.TotalPointsMax); } void Handle_NewGameClicked(object sender, System.EventArgs e) { Navigation.PushAsync(new MainScreenPage(), true); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIController : MonoBehaviour { private int scoreNum = 0; public Text health, round, score, turret, timer; public void DoHealth(int h) { health.text = h.ToString() + "%"; } public void DoRound(int r) { round.text = "Round: " + r.ToString(); } public void DoScore(int s) { scoreNum += s; score.text = scoreNum.ToString(); } public void DoTimer(float time) { float value = (float)System.Math.Round(time, 2); timer.text = value.ToString(); } public void ToggleTimer(bool enabled = true) { timer.enabled = enabled; } public void NextRoundText() { timer.enabled = true; timer.text = "Next Round Starting Soon"; } public void DoTurretText(int tLeft) { turret.text = "Turrets: " + tLeft.ToString(); } }
using Community.Sitecore.ContentSearch.Azure.Tests.Mocks; using Community.Sitecore.ContentSearch.Azure; using Microsoft.VisualStudio.TestTools.UnitTesting; using Sitecore.ContentSearch.Azure.Models; using System.Collections; using System.Collections.Generic; namespace Community.Sitecore.ContentSearch.Azure.Tests { [TestClass] public class TruncatingSearchServiceTests { private readonly TruncatingSearchService sut; private readonly MockSchema schema; private readonly MockSearchService mockService; public TruncatingSearchServiceTests() { schema = new MockSchema(); mockService = new MockSearchService(schema); sut = new TruncatingSearchService(mockService); } [TestMethod] public void Truncates_sortable_fields() { sut.MaxFieldSize = 5; schema.Add(new IndexedField("big", "string", false, true, true, true, true, true)); sut.PostDocuments(new TransparentCloudBatch(new[] { new Dictionary<string, object> { ["uniqueid_1"] = "d1", ["big"] = "abc def" } })); Assert.AreEqual("abc", mockService.PostedBatches[0][0]["big"]); } [TestMethod] public void Does_not_truncate_purely_searchable_fields() { sut.MaxFieldSize = 5; schema.Add(new IndexedField("big", "string", false, true, true, false, false, false)); sut.PostDocuments(new TransparentCloudBatch(new[] { new Dictionary<string, object> { ["uniqueid_1"] = "d1", ["big"] = "abc def" } })); Assert.AreEqual("abc def", mockService.PostedBatches[0][0]["big"]); } [TestMethod] public void Truncates_complex_field_types() { sut.MaxFieldSize = 8; schema.Add(new IndexedField("big", "string", false, true, true, true, true, true)); sut.PostDocuments(new TransparentCloudBatch(new[] { new Dictionary<string, object> { ["uniqueid_1"] = "d1", ["big"] = new Dictionary<string, object> { ["abc"] = new [] { "aa", "bb cc" } } } })); var result = mockService.PostedBatches[0][0]["big"] as Dictionary<string, object>; CollectionAssert.AreEqual(new[] { "aa", "bb" }, result["abc"] as ICollection); } [TestMethod] public void Splits_batches_into_smaller_sizes_when_required() { sut.MaxBatchSize = 250; schema.Add(new IndexedField("big", "string", false, true, true, true, true, true)); sut.PostDocuments(new TransparentCloudBatch(new[] { new Dictionary<string, object> { ["uniqueid_1"] = "d1", ["big"] = new Dictionary<string, object> { ["abc"] = new [] { "aa", "bb cc" } } }, new Dictionary<string, object> { ["uniqueid_1"] = "d2", ["big"] = new Dictionary<string, object> { ["abc"] = new [] { "aa", "bb cc" } } } })); Assert.AreEqual(2, mockService.PostedBatches.Count); Assert.AreEqual(1, mockService.PostedBatches[0].Count); Assert.AreEqual("d1", mockService.PostedBatches[0][0]["uniqueid_1"]); Assert.AreEqual(1, mockService.PostedBatches[1].Count); Assert.AreEqual("d2", mockService.PostedBatches[1][0]["uniqueid_1"]); } [TestMethod] public void Does_not_split_batches_into_smaller_sizes_when_not_required() { sut.MaxBatchSize = 1000; schema.Add(new IndexedField("big", "string", false, true, true, true, true, true)); sut.PostDocuments(new TransparentCloudBatch(new[] { new Dictionary<string, object> { ["uniqueid_1"] = "d1", ["big"] = new Dictionary<string, object> { ["abc"] = new [] { "aa", "bb cc" } } }, new Dictionary<string, object> { ["uniqueid_1"] = "d2", ["big"] = new Dictionary<string, object> { ["abc"] = new [] { "aa", "bb cc" } } } })); Assert.AreEqual(1, mockService.PostedBatches.Count); Assert.AreEqual(2, mockService.PostedBatches[0].Count); Assert.AreEqual("d1", mockService.PostedBatches[0][0]["uniqueid_1"]); Assert.AreEqual("d2", mockService.PostedBatches[0][1]["uniqueid_1"]); } [TestMethod] public void GetDocumentId_returns_uniqueid_field_if_specified() { var result = TruncatingSearchService.GetDocumentId(new Dictionary<string, object> { ["uniqueid_1"] = "d1", ["big"] = "abc def" }); Assert.AreEqual("d1", result); } [TestMethod] public void GetDocumentId_returns_UNKNOWN_if_uniqueid_field_not_specified() { var result = TruncatingSearchService.GetDocumentId(new Dictionary<string, object> { ["big"] = "abc def" }); Assert.AreEqual("UNKNOWN", result); } } }
using System; using Lench.AdvancedControls.Blocks; using Lench.AdvancedControls.Resources; using UnityEngine; // ReSharper disable UseNullPropagation namespace Lench.AdvancedControls.Controls { /// <summary> /// Input control creates analog input for otherwise one or two key actions. /// </summary> public class InputControl : Control { private Cog _cog; private Steering _steering; private Spring _spring; /// <summary> /// Input control key is 'INPUT'. /// </summary> public override string Key => "INPUT"; /// <summary> /// Localized display name of the control. /// </summary> public override string Name => Strings.ControlName_Input; /// <summary> /// Creates an input control for a block with given GUID. /// </summary> /// <param name="guid">GUID of the block.</param> public InputControl(Guid guid) : base(guid) {} /// <summary> /// Control's block handler. /// Angle control accepts Lench.AdvancedControls.Blocks.Steering, Cog and Spring handlers. /// </summary> public override Block Block { get { if (_cog != null) return _cog; if (_steering != null) return _steering; if (_spring != null) return _spring; return null; } protected set { _cog = value as Cog; _steering = value as Steering; _spring = value as Spring; } } /// <summary> /// Applies input to the block. /// </summary> /// <param name="value">Input value.</param> protected override void Apply(float value) { value = value > 0 ? Mathf.Lerp(Center, Max, value) : Mathf.Lerp(Center, Min, -value); _cog?.SetInput(value); _steering?.SetInput(value); _spring?.SetInput(value); } /// <summary> /// Clears Left and Right keys for steering. /// Clears Contract key for springs. /// Cog input is overriden without clearing keys. /// </summary> protected override void ClearKeys() { if (_steering != null) { Block.ClearKeys("LEFT"); Block.ClearKeys("RIGHT"); } if (_spring != null) { Block.ClearKeys("CONTRACT"); } } internal override Control Clone() { var clone = new InputControl(BlockGUID) { Enabled = Enabled, Axis = Axis, Block = Block, Min = Min, Center = Center, Max = Max }; return clone; } } }
using System; using System.Linq; using NknSdk.Client; using NknSdk.Common.Extensions; namespace NknSdk.Common { public static class Address { public const int Uint160Length = 20; public const int CheckSumLength = 4; public const string Prefix = "02b825"; public static readonly int PrefixLength = Address.Prefix.Length / 2; public static readonly int FullLength = Address.PrefixLength + Address.Uint160Length + Address.CheckSumLength; public static bool Verify(string address) { try { var addressBytes = address.Base58Decode(); if (addressBytes.Length != Address.FullLength) { return false; } var addressPrefixBytes = new ArraySegment<byte>(addressBytes, 0, Address.PrefixLength).ToArray(); var addressPrefix = addressPrefixBytes.ToHexString(); if (addressPrefix != Address.Prefix) { return false; } var programHash = Address.ToProgramHash(address); var addressVerificationCode = Address.GetVerificationCodeFromAddress(address); var programHashVerificationCode = Address.GetVerificationCodeFromProgramHash(programHash); return addressVerificationCode == programHashVerificationCode; } catch (Exception) { return false; } } public static string PublicKeyToSignatureRedeem(string publicKey) => $"20{publicKey}ac"; public static string HexStringToProgramHash(string hexString) { var sha256hash = Hash.Sha256Hex(hexString); var result = Hash.Ripemd160Hex(sha256hash); return result.ToHexString(); } public static string SignatureToParameter(string hex) => "40" + hex; public static string PrefixByteCountToHexString(string hex) { var length = hex.Length; if (length == 0) { return "00"; } if (length % 2 == 1) { hex = "0" + hex; length++; } var byteCount = length / 2; var byteCountHex = byteCount.ToString("x"); if (byteCountHex.Length % 2 == 1) { byteCountHex = "0" + byteCountHex; } return byteCountHex + hex; } public static string ToProgramHash(string address) { var addressBytes = address.Base58Decode(); var bytesToTake = addressBytes.Length - Address.PrefixLength - Address.CheckSumLength; var programHashBytes = new ArraySegment<byte>(addressBytes, Address.PrefixLength, bytesToTake).ToArray(); return programHashBytes.ToHexString(); } public static string FromProgramHash(string programHash) { var addressVerifyBytes = Address.GetVerificationBytesFromProgramHash(programHash); var prefixedProgramHash = Address.Prefix + programHash; var addressBaseData = prefixedProgramHash.FromHexString(); var result = addressBaseData.Concat(addressVerifyBytes); return result.Base58Encode(); } public static string AddressToId(string address) => Hash.Sha256(address); public static string AddressToPublicKey(string address) => address .Split(new char[] { '.' }) .LastOrDefault(); public static string AddIdentifier(string address, string identifier) { if (identifier == "") { return address; } return Address.AddIdentifierPrefix(address, $"__{identifier}__"); } public static string AddIdentifierPrefix(string identifier, string prefix) { if (identifier == "") { return "" + prefix; } if (prefix == "") { return "" + identifier; } return prefix + "." + identifier; } public static (string Address, string ClientId) RemoveIdentifier(string source) { var parts = source.Split('.'); if (Constants.MultiClientIdentifierRegex.IsMatch(parts[0])) { var address = string.Join(".", parts.Skip(1)); return (address, parts[0]); } return (source, ""); } private static string GetVerificationCodeFromAddress(string address) { var addressBytes = address.Base58Decode(); var offset = addressBytes.Length - Address.CheckSumLength; var verificationBytes = new ArraySegment<byte>(addressBytes, offset, Address.CheckSumLength).ToArray(); return verificationBytes.ToHexString(); } private static byte[] GetVerificationBytesFromProgramHash(string programHash) { var prefixedProgramHash = Address.Prefix + programHash; var prefixedProgramHashBytes = prefixedProgramHash.FromHexString(); var programHashHex = Hash.DoubleSha256(prefixedProgramHashBytes); var verificationBytes = programHashHex.FromHexString(); var addressVerificationBytes = verificationBytes.Take(Address.CheckSumLength).ToArray(); return addressVerificationBytes; } private static string GetVerificationCodeFromProgramHash(string programHash) { var verificationBytes = Address.GetVerificationBytesFromProgramHash(programHash); return verificationBytes.ToHexString(); } } }
using System; using System.Collections.Generic; using OctoPatch.Descriptions; namespace OctoPatch.Server { /// <summary> /// Repository for some plugin driven types /// </summary> public interface IRepository { /// <summary> /// Returns all discovered messages /// </summary> /// <returns>all messages</returns> IEnumerable<TypeDescription> GetTypeDescriptions(); /// <summary> /// Returns all discovered nodes /// </summary> /// <returns>all nodes</returns> IEnumerable<NodeDescription> GetNodeDescriptions(); /// <summary> /// Returns all discovered adapters /// </summary> /// <returns></returns> IEnumerable<AdapterDescription> GetAdapterDescriptions(); /// <summary> /// Generates a new node for the given key /// </summary> /// <param name="key">unique key of the node description</param> /// <param name="nodeId">id of the new node</param> /// <param name="parent">optional reference to the parent node in case of an attached node</param> /// <param name="connectorKey">optional connector key for splitters and collectors</param> /// <returns>new node instance</returns> INode CreateNode(string key, Guid nodeId, INode parent = null, string connectorKey = null); /// <summary> /// Generates a new adapter for the given key /// </summary> /// <param name="key">adapter key</param> /// <returns>new instance</returns> IAdapter CreateAdapter(string key); } }
using System; namespace Cupboard { public sealed class ChocolateyPackage : Resource { public string Package { get; set; } public PackageState Ensure { get; set; } public ChocolateyPackage(string name) : base(name) { Package = name ?? throw new ArgumentNullException(nameof(name)); } } }
using System.Linq; using System.Text; using SQLite; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #else using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; #endif using System.IO; namespace SQLite.Tests { [TestFixture] public class MigrationTest { [Table ("Test")] class LowerId { public int Id { get; set; } } [Table ("Test")] class UpperId { public int ID { get; set; } } [Test] public void UpperAndLowerColumnNames () { using (var db = new TestDb (true) { Trace = true } ) { db.CreateTable<LowerId> (); db.CreateTable<UpperId> (); var cols = db.GetTableInfo ("Test").ToList (); Assert.That (cols.Count, Is.EqualTo (1)); Assert.That (cols[0].Name, Is.EqualTo ("Id")); } } } }
using Sirenix.OdinInspector; using UnityEngine; namespace Project.Store { public class StoreInstaller : SerializedMonoBehaviour { [SerializeField, Required] StoreSO storeScriptableObject; } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Threading; using System.Windows.Forms; namespace OpenLiveWriter.CoreServices { public class PaddedWaitCursor : IDisposable { public PaddedWaitCursor(int msPadding) { _targetEndTime = DateTime.Now.AddMilliseconds(msPadding); _previousCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; } public void Dispose() { // sleep if necessary TimeSpan padTime = _targetEndTime.Subtract(DateTime.Now); if (padTime.Milliseconds > 0) Thread.Sleep(padTime); Cursor.Current = _previousCursor; } Cursor _previousCursor; DateTime _targetEndTime; } }
using System; using System.Linq; using Flurl; namespace NuGet.Net { public static class StringExtensions { public static Uri WithoutPathSegments(this Uri uri, int number) { var segments = uri .Segments .Take(uri.Segments.Length - number) .ToArray(); segments[segments.Length - number] = segments[segments.Length - number].TrimEnd('/'); var uriBuilder = new UriBuilder(uri) { Path = string.Concat(segments) }; return uriBuilder.Uri; } public static string WithoutPathSegments(this string s, int number) => new Uri(s) .WithoutPathSegments(number) .ToString(); public static string WithoutLastPathSegment(this string s) => s.WithoutPathSegments(1); public static string ForNuspec(this string url, string packageName) { if (url == null) { throw new ArgumentNullException(nameof(url)); } if (packageName == null) { throw new ArgumentNullException(nameof(packageName)); } return url .WithoutLastPathSegment() .AppendPathSegment($"/{packageName.ToLowerInvariant()}.nuspec"); } } }
using DomainValidation.Interfaces.Validation; using DomainValidation.Validation; using EP.CursoMvc.Domain.Validations.Clientes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EP.CursoMvc.Domain.Entities { public class Cliente : ISelfValidator { public Cliente() { ClienteId = Guid.NewGuid(); Enderecos = new List<Endereco>(); } public Guid ClienteId { get; set; } public string Nome { get; set; } public string Email { get; set; } public string CPF { get; set; } public DateTime DataNascimento { get; set; } public DateTime DataCadastro { get; set; } public bool Ativo { get; set; } public virtual ICollection<Endereco> Enderecos { get; set; } public ValidationResult ValidationResult { get; set;} public bool IsValid() { ValidationResult = new ClienteEstaConsistenteValidation().Validate(this); return ValidationResult.IsValid; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class static_Master_Admin_Admin_Master_Page : System.Web.UI.MasterPage { //protected void Page_Load(object sender, EventArgs e) //{ //} //protected void lbtn_Contact_Click(object sender, EventArgs e) //{ // Response.Redirect("~/Web/Support/Inquiry.aspx"); //} protected void lbtn_Index_Click(object sender, EventArgs e) { Response.Redirect("~/Web/Home/Index.aspx"); } // protected void lbtn_FAQ_Click(object sender, EventArgs e) // { // Response.Redirect("~/Web/Support/FAQ.aspx"); // } // protected void lbtn_Notification_Click(object sender, EventArgs e) // { // Response.Redirect("~/Web/Notification/Notification.aspx"); // } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPattern { /* 该模式涉及到三个角色: 环境角色(Context):持有一个Strategy类的引用 抽象策略角色(Strategy):这是一个抽象角色,通常由一个接口或抽象类来实现。此角色给出所有具体策略类所需实现的接口。 具体策略角色(ConcreteStrategy):包装了相关算法或行为。 */ public class StrategyContext { protected ICaculate ICalculate; public StrategyContext(ICaculate caculate) { ICalculate = caculate; } public decimal GetCaculateValue(decimal x,decimal y) { return ICalculate.Caculate(x, y); } } public interface ICaculate { decimal Caculate(decimal x, decimal y); } public class Add : ICaculate { public decimal Caculate(decimal x, decimal y) { return x + y; } } public class Minus : ICaculate { public decimal Caculate(decimal x, decimal y) { return x - y; } } public class Mulitply : ICaculate { public decimal Caculate(decimal x, decimal y) { return x * y; } } public class Divide : ICaculate { public decimal Caculate(decimal x, decimal y) { if (y==0) { throw new DivideByZeroException("被除数y不能为0"); } return x / y; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Text; using Xunit; namespace System.Net.Http.Tests { public class EntityTagHeaderValueTest { [Fact] public void Ctor_ETagNull_Throw() { AssertExtensions.Throws<ArgumentException>("tag", () => { new EntityTagHeaderValue(null); }); } [Fact] public void Ctor_ETagEmpty_Throw() { // null and empty should be treated the same. So we also throw for empty strings. AssertExtensions.Throws<ArgumentException>("tag", () => { new EntityTagHeaderValue(string.Empty); }); } [Fact] public void Ctor_ETagInvalidFormat_ThrowFormatException() { // When adding values using strongly typed objects, no leading/trailing LWS (whitespace) are allowed. AssertFormatException("tag"); AssertFormatException("*"); AssertFormatException(" tag "); AssertFormatException("\"tag\" invalid"); AssertFormatException("\"tag"); AssertFormatException("tag\""); AssertFormatException("\"tag\"\""); AssertFormatException("\"\"tag\"\""); AssertFormatException("\"\"tag\""); AssertFormatException("W/\"tag\""); } [Fact] public void Ctor_ETagValidFormat_SuccessfullyCreated() { EntityTagHeaderValue etag = new EntityTagHeaderValue("\"tag\""); Assert.Equal("\"tag\"", etag.Tag); Assert.False(etag.IsWeak); } [Fact] public void Ctor_ETagValidFormatAndIsWeak_SuccessfullyCreated() { EntityTagHeaderValue etag = new EntityTagHeaderValue("\"e tag\"", true); Assert.Equal("\"e tag\"", etag.Tag); Assert.True(etag.IsWeak); } [Fact] public void ToString_UseDifferentETags_AllSerializedCorrectly() { EntityTagHeaderValue etag = new EntityTagHeaderValue("\"e tag\""); Assert.Equal("\"e tag\"", etag.ToString()); etag = new EntityTagHeaderValue("\"e tag\"", true); Assert.Equal("W/\"e tag\"", etag.ToString()); etag = new EntityTagHeaderValue("\"\"", false); Assert.Equal("\"\"", etag.ToString()); } [Fact] public void GetHashCode_UseSameAndDifferentETags_SameOrDifferentHashCodes() { EntityTagHeaderValue etag1 = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue etag2 = new EntityTagHeaderValue("\"TAG\""); EntityTagHeaderValue etag3 = new EntityTagHeaderValue("\"tag\"", true); EntityTagHeaderValue etag4 = new EntityTagHeaderValue("\"tag1\""); EntityTagHeaderValue etag5 = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue etag6 = EntityTagHeaderValue.Any; Assert.NotEqual(etag1.GetHashCode(), etag2.GetHashCode()); Assert.NotEqual(etag1.GetHashCode(), etag3.GetHashCode()); Assert.NotEqual(etag1.GetHashCode(), etag4.GetHashCode()); Assert.NotEqual(etag1.GetHashCode(), etag6.GetHashCode()); Assert.Equal(etag1.GetHashCode(), etag5.GetHashCode()); } [Fact] public void Equals_UseSameAndDifferentETags_EqualOrNotEqualNoExceptions() { EntityTagHeaderValue etag1 = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue etag2 = new EntityTagHeaderValue("\"TAG\""); EntityTagHeaderValue etag3 = new EntityTagHeaderValue("\"tag\"", true); EntityTagHeaderValue etag4 = new EntityTagHeaderValue("\"tag1\""); EntityTagHeaderValue etag5 = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue etag6 = EntityTagHeaderValue.Any; Assert.False(etag1.Equals(etag2)); Assert.False(etag2.Equals(etag1)); Assert.False(etag1.Equals(null)); Assert.False(etag1.Equals(etag3)); Assert.False(etag3.Equals(etag1)); Assert.False(etag1.Equals(etag4)); Assert.False(etag1.Equals(etag6)); Assert.True(etag1.Equals(etag5)); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { EntityTagHeaderValue source = new EntityTagHeaderValue("\"tag\""); EntityTagHeaderValue clone = (EntityTagHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Tag, clone.Tag); Assert.Equal(source.IsWeak, clone.IsWeak); source = new EntityTagHeaderValue("\"tag\"", true); clone = (EntityTagHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Tag, clone.Tag); Assert.Equal(source.IsWeak, clone.IsWeak); Assert.Same(EntityTagHeaderValue.Any, ((ICloneable)EntityTagHeaderValue.Any).Clone()); } [Fact] public void GetEntityTagLength_DifferentValidScenarios_AllReturnNonZero() { EntityTagHeaderValue result = null; Assert.Equal(6, EntityTagHeaderValue.GetEntityTagLength("\"ta\u4F1Ag\"", 0, out result)); Assert.Equal("\"ta\u4F1Ag\"", result.Tag); Assert.False(result.IsWeak); Assert.Equal(9, EntityTagHeaderValue.GetEntityTagLength("W/\"tag\" ", 0, out result)); Assert.Equal("\"tag\"", result.Tag); Assert.True(result.IsWeak); // Note that even if after a valid tag & whitespace there are invalid characters, GetEntityTagLength() // will return the length of the valid tag and ignore the invalid characters at the end. It is the callers // responsibility to consider the whole string invalid if after a valid ETag there are invalid chars. Assert.Equal(11, EntityTagHeaderValue.GetEntityTagLength("\"tag\" \r\n !!", 0, out result)); Assert.Equal("\"tag\"", result.Tag); Assert.False(result.IsWeak); Assert.Equal(7, EntityTagHeaderValue.GetEntityTagLength("\"W/tag\"", 0, out result)); Assert.Equal("\"W/tag\"", result.Tag); Assert.False(result.IsWeak); Assert.Equal(9, EntityTagHeaderValue.GetEntityTagLength("W/ \"tag\"", 0, out result)); Assert.Equal("\"tag\"", result.Tag); Assert.True(result.IsWeak); // We also accept lower-case 'w': e.g. 'w/"tag"' rather than 'W/"tag"' Assert.Equal(4, EntityTagHeaderValue.GetEntityTagLength("w/\"\"", 0, out result)); Assert.Equal("\"\"", result.Tag); Assert.True(result.IsWeak); Assert.Equal(2, EntityTagHeaderValue.GetEntityTagLength("\"\"", 0, out result)); Assert.Equal("\"\"", result.Tag); Assert.False(result.IsWeak); Assert.Equal(2, EntityTagHeaderValue.GetEntityTagLength(",* , ", 1, out result)); Assert.Same(EntityTagHeaderValue.Any, result); } [Fact] public void GetEntityTagLength_DifferentInvalidScenarios_AllReturnZero() { EntityTagHeaderValue result = null; // no leading spaces allowed. Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(" \"tag\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("\"tag", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("tag\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("a/\"tag\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W//\"tag\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W/", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W/\"", 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(null, 0, out result)); Assert.Null(result); Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(string.Empty, 0, out result)); Assert.Null(result); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidParse("\"tag\"", new EntityTagHeaderValue("\"tag\"")); CheckValidParse(" \"tag\" ", new EntityTagHeaderValue("\"tag\"")); CheckValidParse("\r\n \"tag\"\r\n ", new EntityTagHeaderValue("\"tag\"")); CheckValidParse("\"tag\"", new EntityTagHeaderValue("\"tag\"")); CheckValidParse("\"tag\u4F1A\"", new EntityTagHeaderValue("\"tag\u4F1A\"")); CheckValidParse("W/\"tag\"", new EntityTagHeaderValue("\"tag\"", true)); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse(null); CheckInvalidParse(string.Empty); CheckInvalidParse(" "); CheckInvalidParse(" !"); CheckInvalidParse("tag\" !"); CheckInvalidParse("!\"tag\""); CheckInvalidParse("\"tag\","); CheckInvalidParse("\"tag\" \"tag2\""); CheckInvalidParse("/\"tag\""); CheckInvalidParse("*"); // "any" is not allowed as ETag value. } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidTryParse("\"tag\"", new EntityTagHeaderValue("\"tag\"")); CheckValidTryParse(" \"tag\" ", new EntityTagHeaderValue("\"tag\"")); CheckValidTryParse("\r\n \"tag\"\r\n ", new EntityTagHeaderValue("\"tag\"")); CheckValidTryParse("\"tag\"", new EntityTagHeaderValue("\"tag\"")); CheckValidTryParse("\"tag\u4F1A\"", new EntityTagHeaderValue("\"tag\u4F1A\"")); CheckValidTryParse("W/\"tag\"", new EntityTagHeaderValue("\"tag\"", true)); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse(null); CheckInvalidTryParse(string.Empty); CheckInvalidTryParse(" "); CheckInvalidTryParse(" !"); CheckInvalidTryParse("tag\" !"); CheckInvalidTryParse("!\"tag\""); CheckInvalidTryParse("\"tag\","); CheckInvalidTryParse("\"tag\" \"tag2\""); CheckInvalidTryParse("/\"tag\""); CheckInvalidTryParse("*"); // "any" is not allowed as ETag value. } #region Helper methods private void CheckValidParse(string input, EntityTagHeaderValue expectedResult) { EntityTagHeaderValue result = EntityTagHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { EntityTagHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, EntityTagHeaderValue expectedResult) { EntityTagHeaderValue result = null; Assert.True(EntityTagHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input) { EntityTagHeaderValue result = null; Assert.False(EntityTagHeaderValue.TryParse(input, out result)); Assert.Null(result); } private static void AssertFormatException(string tag) { Assert.Throws<FormatException>(() => { new EntityTagHeaderValue(tag); }); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; namespace Models { public class StudentModel { public int Id { get; set; } public int ClassId { get; set; } public string CardId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public List<SelectListItem> Classes { get; set; } public StudentModel() { Classes = new List<SelectListItem>(); } public StudentModel(string FirstName, string LastName, int ClassId) { Classes = new List<SelectListItem>(); this.ClassId = ClassId; this.FirstName = FirstName; this.LastName = LastName; } } }
using System; using Volo.Abp.Domain.Repositories; namespace EShopOnAbp.PaymentService.PaymentRequests { public interface IPaymentRequestRepository : IBasicRepository<PaymentRequest, Guid> { } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace SimpleRemote.Controls.Dragablz.Core { internal class CollectionTeaser { private readonly Action<object> _addMethod; private readonly Action<object> _removeMethod; private CollectionTeaser(Action<object> addMethod, Action<object> removeMethod) { _addMethod = addMethod; _removeMethod = removeMethod; } public static bool TryCreate(object items, out CollectionTeaser collectionTeaser) { collectionTeaser = null; var list = items as IList; if (list != null) { collectionTeaser = new CollectionTeaser(i => list.Add(i), list.Remove); } else if (items != null) { var itemsType = items.GetType(); var genericCollectionType = typeof (ICollection<>); //TODO, *IF* we really wanted to we could get the consumer to inform us of the correct type //if there are multiple impls. havent got time for this edge case right now though var collectionImplType = itemsType.GetInterfaces().SingleOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == genericCollectionType); if (collectionImplType != null) { var genericArgType = collectionImplType.GetGenericArguments().First(); var addMethodInfo = collectionImplType.GetMethod("Add", new[] {genericArgType}); var removeMethodInfo = collectionImplType.GetMethod("Remove", new[] { genericArgType }); collectionTeaser = new CollectionTeaser( i => addMethodInfo.Invoke(items, new[] {i}), i => removeMethodInfo.Invoke(items, new[] {i})); } } return collectionTeaser != null; } public void Add(object item) { _addMethod(item); } public void Remove(object item) { _removeMethod(item); } } }
// Copyright (c) Jeremy Likness. All rights reserved. // Licensed under the MIT License. See LICENSE in the repository root for license information. using System; using System.Linq.Expressions; using ExpressionPowerTools.Core.Comparisons; namespace ExpressionPowerTools.Core.Extensions { /// <summary> /// Building blocks for expression rules. /// </summary> /// <remarks> /// The purpose of these extensions are to provide fluent building blocks for rules. They /// can be chained to test any aspect of comparison. See <see cref="DefaultComparisonRules"/> for /// example implementations. /// </remarks> public static partial class ExpressionRulesExtensions { /// <summary> /// Basic rule definition. Exists as a base to provide typed template. /// </summary> /// <example> /// For example: /// <code> /// ExpressionRulesExtensions.Rule&lt;ConstantExpression>((s, t) => s.Value == t.Vale); /// </code> /// </example> /// <typeparam name="T">The <see cref="Expression"/> type.</typeparam> /// <param name="rule">The rule to make.</param> /// <returns>The rule as an expression.</returns> public static Expression<Func<T, T, bool>> Rule<T>( Expression<Func<T, T, bool>> rule) where T : Expression => rule; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BoundingContextMenu : BaseMenu { FocusableButton button; BoundingBoxMenu boundingBoxMenu; protected override void Start() { base.Start(); boundingBoxMenu = transform.parent.Find("Bounding Box Menu").GetComponent<BoundingBoxMenu>(); InitializeButtons(); } private void InitializeButtons() { button = transform.Find("Button").gameObject.GetComponent<FocusableButton>(); boundingBoxMenu.OnCloseAction = () => { gameObject.SetActive(true); }; button.OnPressed = () => { boundingBoxMenu.gameObject.SetActive(true); gameObject.SetActive(false); }; } }
using System; namespace Capabilities.Util { public static partial class Convert { private const ulong MaskUnsigned16Bit = 0b_1111_1111_1111_1111; private const ulong MaskSigned16Bit = 0b_0111_1111_1111_1111; private const ulong Mask16BitSign = 0b_1000_0000_0000_0000; private const uint Max16 = 0b_1111_1111_1111_1111; private const ulong ULongMidValue = ulong.MaxValue / 2; private static float Signed16BitToScaledFloat(ulong data, int offset) { var mask = MaskSigned16Bit << offset; var signMask = Mask16BitSign << offset; var a = (data & mask) >> offset; var sign = (data & signMask) == 0 ? 1 : -1; return (float) sign * a / Max16; } private static ulong ScaledFloatToSigned16Bit(float data, int offset) { var a = (ulong)Math.Abs((int) (data * Max16)); var val = data > 0 ? a : a | Mask16BitSign; return val << offset; } private static uint Unsigned16BitToUInt(ulong data, int offset) { var mask = MaskUnsigned16Bit << offset; var a = (data & mask) >> offset; return (uint) a; } private static ulong UIntToUnsigned16Bit(uint data, int offset) { return (data & MaskUnsigned16Bit) << offset; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using CtfPlayback.FieldValues; using LTTngCds.CookerData; using LTTngDataExtensions.DataOutputTypes; using Microsoft.Performance.SDK; using Microsoft.Performance.SDK.Extensibility; using Microsoft.Performance.SDK.Extensibility.DataCooking; namespace LTTngDataExtensions.SourceDataCookers.Cpu { public class LTTngCpuDataCooker : LTTngBaseSourceCooker { public static string ContextSwitchEventName = "sched_switch"; public const string Identifier = "CpuDataCooker"; private static readonly HashSet<string> Keys = new HashSet<string>( new[] { ContextSwitchEventName }); readonly List<IContextSwitch> contextSwitches = new List<IContextSwitch>(); public LTTngCpuDataCooker() : base(Identifier) { this.DataKeys = new ReadOnlyHashSet<string>(Keys); this.ContextSwitches = new ProcessedEventData<IContextSwitch>(); } public override string Description => "Provides information on context switching."; public override ReadOnlyHashSet<string> DataKeys { get; } public override DataProcessingResult CookDataElement( LTTngEvent data, LTTngContext context, CancellationToken cancellationToken) { try { ContextSwitchUserData parsed = ContextSwitchUserData.Read(data.Payload); ContextSwitches.AddEvent( new ContextSwitch( data.Timestamp, parsed.PrevComm, parsed.PrevTid, parsed.PrevPrio, parsed.NextComm, parsed.NextTid, parsed.NextPrio)); } catch (Exception e) { Console.Error.WriteLine(e); return DataProcessingResult.CorruptData; } return DataProcessingResult.Processed; } public override void EndDataCooking(CancellationToken cancellationToken) { this.ContextSwitches.FinalizeData(); } [DataOutput] public ProcessedEventData<IContextSwitch> ContextSwitches { get; } struct ContextSwitchUserData { public string PrevComm; public int PrevTid; public int PrevPrio; public long PrevState; public string NextComm; public int NextTid; public int NextPrio; public static ContextSwitchUserData Read(CtfStructValue data) { return new ContextSwitchUserData { PrevComm = data.ReadFieldAsArray("_prev_comm").ReadAsString(), PrevTid = data.ReadFieldAsInt32("_prev_tid"), PrevPrio = data.ReadFieldAsInt32("_prev_prio"), PrevState = data.ReadFieldAsInt64("_prev_state"), NextComm = data.ReadFieldAsArray("_next_comm").ReadAsString(), NextTid = data.ReadFieldAsInt32("_next_tid"), NextPrio = data.ReadFieldAsInt32("_next_prio") }; } } } }
using System; namespace Survi.Prevention.ServiceLayer.Import.Base.Cache { public class CachedForeignKey { public Guid Id { get; set; } public Type Type { get; set; } public String ExternalId { get; set; } public DateTime ExpiredAt { get; } = DateTime.Now.AddMinutes(30); } }
// System.Net.WebPermission.WebPermission(); // System.Net.WebPermission.AddPermission(NetworkAccess,stringuri); // System.Net.WebPermission.Intersect; /** * This program shows the use of the WebPermission() constructor, the AddPermission, * and Intersect' methods of the WebPermission' class. * It first creates two WebPermission objects with no arguments, with each of them * setting the access rights to one pair of URLs. * Then it displays the attributes , values and childrens of the XML encoded instances. * Finally, it creates a third WebPermission object using the logical intersection of the * first two objects. It does so by using the Intersect method. * It then displays the attributes , values and childrens of the related XML encoded * instances. */ using System; using System.Net; using System.Security; using System.Security.Permissions; using System.Collections; class WebPermissionIntersect { static void Main(String[] Args) { try { WebPermissionIntersect myWebPermissionIntersect = new WebPermissionIntersect(); myWebPermissionIntersect.CreateIntersect(); }catch(SecurityException e) { Console.WriteLine("SecurityException : " + e.Message); } catch(Exception e) { Console.WriteLine("Exception : " + e.Message); } } public void CreateIntersect() { // <Snippet1> // Create two WebPermission instances. WebPermission myWebPermission1 = new WebPermission(); WebPermission myWebPermission2 = new WebPermission(); // <Snippet2> // Allow access to the first set of resources. myWebPermission1.AddPermission(NetworkAccess.Connect,"http://www.contoso.com/default.htm"); myWebPermission1.AddPermission(NetworkAccess.Connect,"http://www.adventure-works.com/default.htm"); // Check whether if the callers higher in the call stack have been granted // access permissions. myWebPermission1.Demand(); // </Snippet2> // Allow access right to the second set of resources. myWebPermission2.AddPermission(NetworkAccess.Connect,"http://www.alpineskihouse.com/default.htm"); myWebPermission2.AddPermission(NetworkAccess.Connect,"http://www.baldwinmuseumofscience.com/default.htm"); myWebPermission2.Demand(); // </Snippet1> // Display the attributes , values and childrens of the XML encoded instances. Console.WriteLine("Attributes and values of first 'WebPermission' instance are :"); PrintKeysAndValues(myWebPermission1.ToXml().Attributes,myWebPermission2.ToXml().Children); Console.WriteLine("\nAttributes and values of second 'WebPermission' instance are : "); PrintKeysAndValues(myWebPermission2.ToXml().Attributes,myWebPermission2.ToXml().Children); // <Snippet3> // Create a third WebPermission instance via the logical intersection of the previous // two WebPermission instances. WebPermission myWebPermission3 =(WebPermission) myWebPermission1.Intersect(myWebPermission2); Console.WriteLine("\nAttributes and Values of the WebPermission instance after the Intersect are:\n"); Console.WriteLine(myWebPermission3.ToXml().ToString()); // </Snippet3> } private void PrintKeysAndValues(Hashtable myHashtable,IEnumerable myList) { // Get the enumerator that can iterate through Hashtable. IDictionaryEnumerator myEnumerator = myHashtable.GetEnumerator(); Console.WriteLine("\t-KEY-\t-VALUE-"); while (myEnumerator.MoveNext()) Console.WriteLine("\t{0}:\t{1}", myEnumerator.Key, myEnumerator.Value); Console.WriteLine(); IEnumerator myEnumerator1 = myList.GetEnumerator(); Console.WriteLine("The Children are : "); while (myEnumerator1.MoveNext()) Console.Write("\t{0}", myEnumerator1.Current); } }
using Microsoft.Extensions.DependencyInjection; using System; using System.Linq; namespace MarsRoverConsole { class Program { public static void Main() { var inputMaxPoints = Console.ReadLine().Trim().Split(' '); var inputInstructions = Console.ReadLine().Trim().Split(' '); NavigateRover(inputMaxPoints, inputInstructions); Console.ReadLine(); } private static void NavigateRover(string[] inputMaxPoints, string[] inputInstructions) { var maxPointsOfPlateau = new Coordinate() { XAxis = Convert.ToInt16(inputMaxPoints.First()), YAxis = Convert.ToInt16(inputMaxPoints.Last()) }; var rover = new Position() { XAxis = Convert.ToInt16(inputInstructions[0]), YAxis = Convert.ToInt16(inputInstructions[1]), FacingDirection = (Direction)Enum.Parse(typeof(Direction), inputInstructions[2]) }; var thirdLine = Console.ReadLine().ToUpper(); var instruction = new Instruction() { InitialPosition = rover, Moves = thirdLine }; try { ServiceProvider serviceProvider = new ServiceCollection() .AddTransient<INavigator, Navigator>() .BuildServiceProvider(); var navigator = serviceProvider.GetService<INavigator>(); var nextPosition = navigator.Move(instruction, maxPointsOfPlateau); Console.WriteLine($"{nextPosition.XAxis} {nextPosition.YAxis} {nextPosition.FacingDirection}"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Text; using System; public class startMenuDemo : MonoBehaviour { public InputField keyInputField; public Text keyString = null; public GameObject encryptButton; public GameObject demoKeyButton; private bool allowEnter; private bool entered; void Start() { entered = false; allowEnter = false; } void Update() { if (allowEnter && keyInputField.text != "" && Input.GetKey(KeyCode.Return)) { encryptKey(); } else allowEnter = keyInputField.isFocused; } // Encrypt the key in the input field public void encryptKey() { if (!entered) { DideryDemoManager.Instance.demoEncryptKey(keyInputField.text); deactivateEncryptButtons(); changeKeyToCensored(); entered = true; } else { deactivateEncryptButtons(); } } // Deactivate the encrypt buttons on the start screen public void deactivateEncryptButtons() { encryptButton.SetActive(false); demoKeyButton.SetActive(false); } // Censor the text in the input field public void changeKeyToCensored() { keyInputField.text = censoredKey(keyInputField.text); } // Use a set seed for demo purposes public void useDemoSeed() { DideryDemoManager.IsDemo = true; DideryDemoManager.DemoBlob = keyInputField.text; SeedManager.InputSeed = "148436BD13EEB72557080989DF01"; //"A021E0A80264A33C08B6C2884AC0685C"; deactivateEncryptButtons(); } public void useDemoKeyAndStart() { DideryDemoManager.IsDemo = true; DideryDemoManager.DemoBlob = keyInputField.text; SeedManager.InputSeed = "A021E0A80264A33C08B6C2884AC0685C"; //"4040C1A90886218984850151AC123249"; GameManager.State = GameState.Rehearsal; } // Test getting an encrypted key public void testGetKey() { DideryDemoManager.Instance.demoGetEncryptedKey(); } // Test decrypting a key from a didery blob public void testDecrypt() { string seed = SeedManager.InputSeed; Debug.Log("Seed: " + seed); byte[] keyByte = OTPworker.decryptFromBlob(seed, DideryDemoManager.DemoBlob); string finalKey = Encoding.ASCII.GetString(keyByte); keyString.text = finalKey; Debug.Log("Decrypted key: " + finalKey); } // Test that an invalid key fails the key validation function public void testBadDecrypt() { string seed = "A021E0A80264A33C08B6C2884AC0685C"; string badBlob = "aaaabbbbaaaabbbbaaaabbbbaaaabbbb"; byte[] keyByte = OTPworker.decryptFromBlob(seed, badBlob); string finalKey = Encoding.ASCII.GetString(keyByte); Debug.Log("Bad decrypted key: " + finalKey); } // Test the function to generate public address from private key public void testRegenerateAddress() { string privateKey = "0xb5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7"; string address = VerifyKeys.regeneratePublicAddress(privateKey); Debug.Log("Your public address is: " + address); } // Test that a valid key passes the key validation function public void testValidKey() { string key = "0xb5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7"; VerifyKeys.verifyKey(key); } // Test that a valid key passes the key validation function public void testGoodDecrypt() { string seed = "A021E0A80264A33C08B6C2884AC0685C"; string key = "0xb5b1870957d373ef0eeffecc6e4812c0fd08f554b37b233526acc331bf1544f7"; key = VerifyKeys.removeHexPrefix(key); byte[] otp = new byte[32]; byte[] seedByte = new byte[14]; byte[] encryptedKey = new byte[34]; byte[] keyByte = Encoding.ASCII.GetBytes(key); seedByte = Encoding.ASCII.GetBytes(seed); byte[] goodKey = OTPworker.OTPxor(seedByte, keyByte); byte[] decryptedKey = OTPworker.decryptFromBlob(seed, Convert.ToBase64String(goodKey)); string finalKey = Encoding.ASCII.GetString(keyByte); Debug.Log("Bad decrypted key: " + finalKey); } // Censor all but the last 4 digits of the input key public string censoredKey(string key) { char[] oldKey = key.ToCharArray(); char[] newKey = new char[key.Length]; for (int i = 0; i < oldKey.Length; i++) { if (i > oldKey.Length - 5) { newKey[i] = oldKey[i]; } else newKey[i] = '*'; } string returnStr = new string(newKey); return returnStr; } }
using Eqstra.BusinessLogic.Helpers; using Microsoft.Practices.Prism.PubSubEvents; using Microsoft.Practices.Prism.StoreApps; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Eqstra.BusinessLogic.ServiceSchedule { public class Address : ValidatableBindableBase { public Address() { this.Countries = new List<Country>(); this.Provinces = new List<Province>(); this.Cities = new List<City>(); this.Suburbs = new List<Suburb>(); this.Regions = new List<Region>(); } private long entityRecId; public long EntityRecId { get { return entityRecId; } set { SetProperty(ref entityRecId, value); } } private string street; public string Street { get { return street; } set { SetProperty(ref street, value); } } private List<string> postcodes; public List<string> Postcodes { get { return postcodes; } set { SetProperty(ref postcodes, value); } } private List<Country> countries; public List<Country> Countries { get { return countries; } set { SetProperty(ref countries, value); } } private List<Province> provinces; public List<Province> Provinces { get { return provinces; } set { SetProperty(ref provinces, value); } } private List<City> cities; public List<City> Cities { get { return cities; } set { SetProperty(ref cities, value); } } private List<Suburb> suburbs; public List<Suburb> Suburbs { get { return suburbs; } set { SetProperty(ref suburbs, value); } } private List<Region> region; public List<Region> Regions { get { return region; } set { SetProperty(ref region, value); } } private Country selectedCountry; public Country SelectedCountry { get { return selectedCountry; } set { SetProperty(ref selectedCountry, value); } } private Province selectedprovince; public Province SelectedProvince { get { return selectedprovince; } set { SetProperty(ref selectedprovince, value); } } private City selectedCity; public City SelectedCity { get { return selectedCity; } set { SetProperty(ref selectedCity, value); } } private Suburb selectedSuburb; public Suburb SelectedSuburb { get { return selectedSuburb; } set { SetProperty(ref selectedSuburb, value); } } private string selectedZip; public string SelectedZip { get { return selectedZip; } set { SetProperty(ref selectedZip, value); } } private Region selectedRegion; public Region SelectedRegion { get { return selectedRegion; } set { SetProperty(ref selectedRegion, value); } } } public class AddressEvent : PubSubEvent<Address> { } }
using System.Collections.Generic; namespace SlackLeadsBidder.Email { public interface IEmailDelivery { IEmailDelivery AddAttachment(string base64Data, string fileName, string fileType); IEmailDelivery AddRecipient(string email); List<EmailDeliveryResult> Send(); } }
using NETCore.Encrypt.Extensions; using System; namespace WFw.GeTui.Models.Auth { /// <summary> /// 鉴权 /// </summary> public class AuthRequest { /// <summary> /// 签名 /// </summary> public string sign { get; set; } /// <summary> /// 时间戳 /// </summary> public string timestamp { get; set; } /// <summary> /// appkey /// </summary> public string appkey { get; set; } /// <summary> /// /// </summary> /// <param name="auth"></param> public AuthRequest(IAuth auth) { appkey = auth.AppKey; timestamp = DateTime.Now.ToMillisecondTimeStamp(); sign = $"{auth.AppKey}{timestamp}{auth.MasterSecret}".SHA256(); } } }
namespace StatHarvester.DAL.Models.Specs.Items { using SpecAttributes; [ItemSpecType("Exterminator")] public class Exterminator : ItemSpec { [IntField] public int ActivationEnergy { get; set; } [IntField] public int Douses { get; set; } public bool Fire { get; set; } [IntField] public int Frequency { get; set; } [IntField] public int Dps { get; set; } [IntField] public int Dpe { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using Havit.Collections; namespace Havit.Business.Query { /// <summary> /// Kolekce položek SortItem. /// Určeno pro položky ORDER BY skládače SQL dotazu (QueryParameters). /// </summary> public class OrderByCollection : Havit.Collections.SortItemCollection { /// <summary> /// Přidá na konec kolekce položku pro vzestupné řazení. /// </summary> public void Add(FieldPropertyInfo propertyInfo) { Add(propertyInfo, SortDirection.Ascending); } /// <summary> /// Přidá na konec kolekce položku pro řazení. /// </summary> public void Add(FieldPropertyInfo propertyInfo, SortDirection direction) { Add(new FieldPropertySortItem(propertyInfo, direction)); } /// <summary> /// Přidá do kolekce položku pro vzestuné řazení. /// </summary> public void Insert(int index, FieldPropertyInfo propertyInfo) { Insert(index, propertyInfo, SortDirection.Ascending); } /// <summary> /// Přidá do kolekce položku pro řazení. /// </summary> public void Insert(int index, FieldPropertyInfo propertyInfo, SortDirection direction) { Insert(index, new FieldPropertySortItem(propertyInfo, direction)); } } }
namespace Data.Enums { public enum NpcRace { None, RedCap, Pixie, YoungCentaurs, SaberToothCougar, PollutedUnicorn, LongTusk, Pigling, UnseelieNoble, DyingGhillieDhu, PollutedEarthSpirit, FallenSpiritOfNature, SorcererDarker, Honeybee, DumperkanFignther, Undeadcavalry, UndeadEscort, DevaHunter, DevaShaman, Basilisk, DevaFemaleRouge, BerserkerDarker, UndeadBeast, FrostGiantJarl, Human, Eatingplant, DestroyerOfFire, BloodGolem, Pollutedwolf, UndeadCommander, DruggedShurianWarrior, DarkMarauder, ShadowArmor, AvatarOfDarkness, DarkReaper, KilliansServant, DruggedShurianSummoner, SummonedHellhound, YuantiShaman, Goral, Mole, HookaCaptain, HookaFootman, Toad, Lizard, ShadowCougar, Pygmytula, PygmytulaMiss, DecayingArgass, Hyena, KoboldBeliever, KoboldFighter, EnragedBear, KoboldProphet, WarriorDarker, ElementalistDarker, SlayerDarker, PriestDarker, CraftyArachne, Castanic, YuantiPirateRaider, LesserElementalKumas, OrcanPirate, KoboldMarauder, LanceDarker, ImpServant, KaidunsEliteWarrior, DyingCromos, NympiWarrior, Animal, GulaChef, ManEater, KoboldRaider, Argon, Zombie, UndeadSynuuthSlave, SlaveManager, Arctus, ArcherDarker, Volcanus, Mantiscore, Qamara, PollutedTreeSpirit, YuantiWarleader, PirateSynuuth, YuantiWarrior, YuantiBuserker, Crab, PirateDeva, DrownedSailor, OrcanMinimi, BloodMagician, TorturedSouls, HoundMaligoth, StoneHead, AngryDummy, DecayingGhillieDhu, SpiritOfNature, BlackMarauder, DumperkanCaster, Creationfarmer, CreationWorkman, SlimCastanicMadman, FatAmanMadman, TownMilitiaOfficier, TownMilitia, MadmanDuo, DwarfMadman, BloodCreature, VampirHandyman, VampirGentleman, VampirLady, DarkWitchMaster, SalvaGangBurglar, FierceDoberman, ClownOfKillian, BisqueDoll, CloderA, ServantOfGiant, BronzeGolemFighter, ShamBattleGolem, Swindler, UndeadSpearman, ViolentArachne, GiantTula, Scorpion, Doll, Witch, AbandonedAutomatedGuardian, PoporiBrute, FollowersOfLida, GiantStormDrake, Volcan, FuryMaligoth, Baraka, Ghost, DarkBishop, DarkKnight, Gorilla, ArgoniteKallashProtector, KaidunsWizard, ShadowMonster, Rhinoceros, Ostrich, Monkey, MonkeyA, MonkeyB, PygmytulaMissA, BossGhilliedhu, FlowerTreespirit, AncientGardener, ArchaeopteryxA, ArchaeopteryxB, CraftyForestSpiderA, GiantMonkey, Bird, SyreneOfWind, Pandurus, WendigoShaman, WendigoWarrior, AlpinePredator, Highelf, Arkus, DevilJailer, PrionWarrior, PrionMadman, ArgoniteShamalanBattleOracle, ArgoniteKallashGuardLeader, TrainedTschodanBeast, Orcan, SikandariOracle, SikandariEliteSoldier, KalanHeavyWarrior, BlackPig, ArgoniteGiant, ArgoniteFemaleMagician, WormFlowerAni, GuardCube, GiantBird, NpcFlashArgonTenTacle, NpcArgonFieldlnhaler, NpcDestructArgonWall, SikandariBlindGuardianBArgoniteHalf, NympiElementalistArgoniteHalf, MightyKuchartFighterArgoniteHalf, MightyKuchartProphetArgoniteHalf, SlayerDarker3ArgoniteHalf, TwistedBloodCreatureArgoniteHalf, TwistedBloodCreatureArgonite, UnseelieNobleAArgoniteHalf, UndeadCommander32EliteArgoniteHalf, KnightPlasmaGuardian27EliteArgoniteHalf, LokianBeastArgoniteHalf, NpcArgonCommander, ArgonExtractor, ArgonExcavaterDig, TwistedAlpinePredator, NpcDestrucFairy, NpcDestructStonedToadstool, ArgoniteGilgashGuardian, IronEatingMonster, PossessionGiant, ArgoniteFly, ArgoniteLancer, ArchakalashTrooperR, ArgonTeleporter, ArgonGenerator, InfestedFrostGiant, Aman, NpcT4MionKanovia, Armadillo, ArgoniteMotherShip, HatchlingArgoniteParasite, ArgoniteEnergyAbsorber, RamayanR, HighpriestArcnanR, SpreadMind, DailyFlower, NpcT4BattleArgonMachine, LastemoerorBelten, DarkRookSlayer, DarkPawnArcher, DarkKing, DarkQueen, DarkRookWarrior, DarkPawnBerserker, UnseelieWarrior, SikandariBlindGuardian, ArgoniteShamalanGroup, MightyDarkreeper, HellhoundBeast, EyeofWacher, Popori, Original, God, Child, Object, Monster, Male, HighElf, Orignal, CastanicFAni, NpcT4MionKarego, DailyArgonMagic, NpcT4MissionIllu, LifrPipe, NpcT4MissionArgonnSwA, NpcT4MissionArgonnSwB, NpcT4MissionCable01, NpcTutoCrashStone, NpcTutFsoldierW, NpcTutTsoldierW, KalanShockTrooperR, ArgoniteShamalanBattleOracleR, ArgoniteGiantR, Baphomet, ChiefPriest, Thief, SummonedSnake, NpcT4BattleDrill, NpcCultist, NpcT4BattleCommand, NpcDaganhalidom, NpcT4BattleStone, SynuuthEggrobber, Demonstone02, NpcT4BattleGolem, NpcT4BattleGolem02, NpcT4BattleKumas, NpcT4BattlePot, RelicOfGuardian, NpcT4BattleMirror, NpcT4BattleWall, NpcT4BattleDirection, NpcSwcDoor, Coin, Tulsa, GiantGriffin, GreatGriffin, MagicianDragon, ForestGiant, PoisonousZombie, MysteryBoxEvent, CraftyArachneJr, CraftyArachneKid, WalkingDead, Ssalissali, VehicleHorse, VihicleHorsePrime, HorseLord, HorseGray, HorseYellow, HorsePaint, HorseYellowdot, HorseBluedot, HorseRanker, InfernoHorse, HorseBlack, HorseGold, HorseRed, HorseWhite, HorseWhitedot, HorseUndead, Lion, LionWhite, Puma, HookaChieftainArgoniteHalf, HookaToadArgoniteHalf, EnragedBearArgoniteHalf, PixieArgonite, RedcapBig, RedcapSmall, BloodCreatureArgoniteHalf, BloodCreatureArgonite, TwistedBloodCreatureArgoniteFirst, BloodCreatureArgoniteFirst, Synnuth, HoundMaligothArgoniteHalf, AngryDwarfMadman, CreationCultist, SacredGuardianBoss, SacredGuardianBoss01, YuantiPirateBossArgoniteHalf, TwistedAlpinePredatorBoss, EnragedIceBearArgoniteHalf, CommanderBarcadusR, YuantiBuserkerBoss, YuantiWarleaderArgoniteHalf, FlowerTreespritA, KalanHeavyWarriorMr, KalanHeavyWarriorR, AngryDummyA, NympiWarriorArgoniteHalf, WendigoShamanArgoniteHalf, WendigoWarriorArgoniteHalf, WendigoWarriorArgonite, WendigoWarriorArgoniteFirst, YuantiWarriorArgoniteHalf, CultlistLancerBoss, ArcherDarker3ArgoniteHalf, CultistPriestDagon, PriestDarkerBoss, CultistMysticDagonA, CultistMysticDagonB, WarriorDarker3ArgoniteHalf, CultistWarriorDagon, CultistBerserkDagon, Seal, ArgoniteMotherShipW, FatHunter, ArgoniteFemaleMagicianR, GuardCubeA, BossGhiliedhuA, ShurianHunter, LegSpider, Killian, HeterotypicMonster, SummonedTentacle, TreasureHunter, SpiritOfFury, JuniorSpirit, MessengerOfSandramanaia, SeparateMonsterOfSandramanaia, CapsuleOfSandramanaia, IncubatorOfSandramanaia, TentacleOfSandramanaia, QHasmina, AmanMWound, HumanMWound, PoporiMWound, HumanMCommomCold02, ElinWounded, CastanicMKDark, CastanicMKGold, CastanicMKSilver, CastanicFKDark, CastanicFKGold, BarakaMCommomCold01, BarakaMCommomCold02, AmanFSentry, AmanMBlacksmith, Box, NpcDoor, T4Stone, NpcHeavyWagon, MiaEgg, NpcT4BattleDrill01, NpcT4BattleDoor, NpcT4BattleMirror01, BlackCrackBigStone, NpcCylinderBookcase, NpcStonelantern, ArgonPipe, MilitaryBase, CampFlag, NpcT4CampFlag, NpcT4ArgTentaTele, NpcFishA01, NpcFishA02, NpcTreasureBox01, NpcTreasureBox02, DailyArgonMushroom, Bananatree, LightHouseDev, DailyFeed, DailyBirdNest, LifrTree, MionArgon, MionKarego, MionSeren, NpcT4DailySolarMonster01, NpcT4DailySolarMonster02, NpcT4DailySolarMonster03, CastanicFTalentia, HumanFElviennue, PoporiMPobarian, NpcT4MionArogonn, NpcT4MionIncubator, NpcT4MionLifeBall, NpcT4MionMysteriousRd, NpcT4MissionArgonea, Tirkaieffect01, Marker, NpcTutoCrashingAirShip, NpcTutoBlackBird, NpcTutoCrashSet, NpcTutAmanFOfficer, NpcTutAmanMOfficer, NpcTutBarakaMOfficer, NpcTutBoxcarryH, NpcTutCastanicFOfficer, NpcTutFsoldierH, NpcTutHealerH, NpcTutTsoldierH, EnchantedDollEv, GuardianSpirit1, GuardianSpirit2, HealSpirit1, HealSpirit2, LightningSpirit1, LightningSpirit2, NukesSpirit1, NukesSpirit2, Magicwand, Pegasus, } }
namespace HoodedCrow.uCore.Core { public struct LoadDataMessageContent: IMessageContent { } }
using System.Collections; using System; using UnityEngine; namespace WellFired.Initialization { public class ContextInitializer<T> : MonoBehaviour where T : IInitializationContext { protected T Context { get; set; } private void Start() { if(Context == null) throw new Exception("Created an ContextInitializer without passing a Context before Start."); Ready(); } protected virtual void Ready() { throw new NotImplementedException("Your class must implement the Ready Method"); } public void SetContext(T context) { if(Context != null) throw new Exception("Setting a context on the level initializer when we already have one."); if(context == null) throw new Exception("Cannot pass a null context to the LevelInitialiser"); if(!context.IsContextSetupComplete()) throw new Exception("The context passed to this oject has not been setup correctly."); Context = context; } } }
private sealed class LeftShiftInstruction.LeftShiftUInt16 : LeftShiftInstruction // TypeDefIndex: 2498 { // Methods // RVA: 0x17BFBF0 Offset: 0x17BFCF1 VA: 0x17BFBF0 Slot: 8 public override int Run(InterpretedFrame frame) { } // RVA: 0x17BF560 Offset: 0x17BF661 VA: 0x17BF560 public void .ctor() { } }
using System; using System.Collections.Generic; using System.Text; using System.Xml.Linq; namespace RfgTools.Types { public class matrix43 { //The names of these vectors are based on the common purpose of a 4x3 matrix in RFG public vector3f rvec; public vector3f uvec; public vector3f fvec; public vector3f translation; public matrix43(vector3f rvec, vector3f uvec, vector3f fvec, vector3f translation) { this.rvec = rvec; this.uvec = uvec; this.fvec = fvec; this.translation = translation; } public matrix43(float initialValue) { rvec = new vector3f(initialValue); uvec = new vector3f(initialValue); fvec = new vector3f(initialValue); translation = new vector3f(initialValue); } public XElement ToXElement(string nodeName) { var node = new XElement(nodeName); node.Add(rvec.ToXElement("rvec")); node.Add(uvec.ToXElement("uvec")); node.Add(fvec.ToXElement("fvec")); node.Add(translation.ToXElement("translation")); return node; } } }
@using Template.Application.TodoLists.Commands.CreateTodoList; @model CreateTodoListCommand; <form class="form-inline" method="post" asp-controller="TodoLists" asp-action="Create"> <div class="form-group mx-sm-3 mb-2"> <input type="text" class="form-control" asp-for="Title" placeholder="New List"> </div> <button type="submit" class="btn btn-primary mb-2">Add List</button> </form>
using Microsoft.Identity.Client; using System.Threading.Tasks; namespace HDR_UK_Web_Application.IServices { public interface IAccessTokenService { Task<AuthenticationResult> GetAuthenticationResult(); } }
 using System; namespace BusinessModel { public interface IBaseRequest { Guid RequestId { get; set; } string Userid { get; set; } } }
/// <summary> /// Camera zoom 2D /// /// Programmer: Carl Childers /// Date: 1/18/2015 /// /// Zooms a 2D camera using the mouse wheel. /// </summary> using UnityEngine; using System.Collections; public class CameraZoom2D : MonoBehaviour { public float MinCameraSize = 1, MaxCameraSize = 20, SizeInterval = 1; public string InputAxisName = "Mouse ScrollWheel"; void Awake() { if (camera == null) { enabled = false; } } // Update is called once per frame void Update () { float inScroll = Input.GetAxis (InputAxisName); if (inScroll > 0) { camera.orthographicSize = Mathf.Max (camera.orthographicSize - SizeInterval, MinCameraSize); } else if (inScroll < 0) { camera.orthographicSize = Mathf.Min (camera.orthographicSize + SizeInterval, MaxCameraSize); } } }
using System; using System.Collections.Generic; /// <summary> /// Represents a kind of action, as opposed to an instance of an action /// </summary> public class ActionType { /// <summary> /// Name of this type of action /// </summary> public string ActionName; /// <summary> /// The frequency at which this ActionType should occur, 1.0 is the default. /// Higher for more frequent, Lower for less frequent. Exact probability is /// managed by the sum of all frequencies, balanced against a reference ActionType /// for a specified number of expected occurances (see ActionLibrary) /// </summary> public float Frequency = 1; /// <summary> /// List of roles that need to be bound in an instance of this action type /// </summary> public List<RoleTypeBase> RoleList; /// <summary> /// Change the world to reflect the execution of the specified action /// </summary> public Action<Action> Modifications; /// <summary> /// Perform any further operations associated with the execution of an action, /// after the world is modified. For example, queuing subsequent actions to /// perform in the future. /// </summary> public Action<Action> PostExecute; // TODO: add ability to queue an action for later steps. /// <summary> /// Create a new ActionType describing a new type of action with the specified roles. /// </summary> /// <param name="name">Name of the type of action</param> /// <param name="role_list">Roles (arguments) of actions of this type.</param> public ActionType(string name, params RoleTypeBase[] role_list) { ActionName = name; RoleList = new List<RoleTypeBase>(role_list); } /// <summary> /// Create an instance of this action type by finding values to fill each of /// its roles. Roles can be filled by passing in a string (with the role name) /// and an object (to fill that role) which will be validated by the filter /// method. This is not type safe, it relies on proper type being passed in. /// Or, the role will be attempted to be filled by the regular Role filling function. /// </summary> /// <param name="roleBindings">List of bindings to force for the actions roles, /// expects alternating strings (naming a role) and objects (to fill that role)</param> /// <returns></returns> public Action Instantiate(params object[] roleBindings) { List<RoleBase> filledRoles = new List<RoleBase>(); Action action = new Action(ActionName, Simulator.CurrentTime, filledRoles); foreach (var role in RoleList) { var BoundObject = BindingOf(role.Name, roleBindings); if (BoundObject != null) { RoleBase temp = role.FillRoleWith(BoundObject, action); if (temp != null) { filledRoles.Add(temp); } else { return null; } } else { RoleBase temp = role.FillRoleUntyped(action); if (temp != null) { filledRoles.Add(temp); } else { return null; } } } return action; } /// <summary> /// Helps us treat the object[] roleBindings from Instantiate as a dictionary /// </summary> /// <returns>The object to be bound to the role</returns> /// <param name="role">string specifying the binding object to use</param> /// <param name="bindings">Bindings, passed along from Instantiate</param> object BindingOf(string role, object[] bindings) { for (int i = 0; i < bindings.Length - 1; i += 2) if ((string)bindings[i] == role) return bindings[i + 1]; return null; } /// <summary> /// Perform the action in the (simulated) world /// </summary> /// <param name="action">Action to perform</param> public void Execute(Action action) { ActionSimulator.action_history.Add(action); Modifications?.Invoke(action); PostExecute?.Invoke(action); } /// <summary> /// Instantiates and (if the action was instatiated) executes it. /// </summary> /// <param name="bindings">Bindings to pass to Instantiate</param> public void InstantiateAndExecute(params object[] bindings) { Action act = Instantiate(bindings); if (act != null) { Execute(act); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Slack.Net.Core.Client; using Slack.Net.Core.Model.Request; using Slack.Net.Core.Model.Response; using Slack.Net.Core.Repositories.Test; namespace Slack.Net.Core.Console { public class Program { public static void Main(string[] args) { ISlackApiClient<TestRequest, TestResponse> repository = new SlackApiV1Client<TestRequest, TestResponse>(); ITestRepository test = new TestRepository(repository); var result = test.TestAsync(new TestRequest() { Error = "my test error", Foo = "boooo" }).Result; System.Console.WriteLine("Done"); } } }
using Microsoft.AspNetCore.Builder; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SecureBank.Interfaces { public interface IDbInitializer { void Initialize(string admin, string adminPassword); void Seed(string userPassword); void Create(IApplicationBuilder app); } }
namespace BotBits { public enum CampaignStatus { Locked = -1, Unlocked = 0, Completed = 1 } }
// Copyright (c) Kornei Dontsov. All Rights Reserved. Licensed under the MIT. // See LICENSE in the project root for license information. namespace KorneiDontsov.Logging.Example { using Microsoft.Extensions.Hosting; using Serilog; using System; using System.Threading; using System.Threading.Tasks; class ServiceExample: IHostedService { IHostApplicationLifetime appLifetime { get; } ILogger logger { get; } public ServiceExample (IHostApplicationLifetime appLifetime, ILogger logger) { this.appLifetime = appLifetime; this.logger = logger.ForContext<ServiceExample>(); } async void BeginWork () { logger.Information("An error will be thrown after 3 seconds."); await Task.Delay(3_000); try { throw new Exception("Exception example."); } catch(Exception ex) { logger.Error(ex, "Exception example was thrown."); } finally { appLifetime.StopApplication(); } } /// <inheritdoc /> public async Task StartAsync (CancellationToken cancellationToken) { logger.Information("Application will start after 2 seconds."); await Task.Delay(2_000, cancellationToken); BeginWork(); } /// <inheritdoc /> public Task StopAsync (CancellationToken cancellationToken) => Task.CompletedTask; } }
@{ Layout = "_Layout"; } <div class="row"> <div class="col-md-12" id="splash"> <h2>Welcome back Pierre,<h2> <h4>What would you like to do?</h4> <a href="/vendors"> <button type="submit" class="btn btn-primary">View Vendors</button> </a> </div> </div>
using AstralKeks.Workbench.Common.Context; namespace AstralKeks.ChefSpoon.Core.Resources { internal class Paths { public static string WorkspaceDirectory => Location.Workspace(); public static string UserspaceDirectory => Location.Userspace(Directories.Spoon); } }
using System; using DotNetCommons.Temporal; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DotNetCommons.Test.Temporal { [TestClass] public class DateBasedHolidayTests { [TestMethod] public void Test() { var holiday = new DateBasedHoliday("Bork Day", HolidayType.Halfday, 3, 5); Assert.AreEqual("Bork Day", holiday.Name); Assert.AreEqual(HolidayType.Halfday, holiday.Type); Assert.AreEqual(new DateTime(2020, 3, 5), holiday.InternalCalculateDate(2020)); Assert.AreEqual(new DateTime(2021, 3, 5), holiday.InternalCalculateDate(2021)); Assert.AreEqual(new DateTime(2022, 3, 5), holiday.InternalCalculateDate(2022)); Assert.AreEqual(new DateTime(2023, 3, 5), holiday.InternalCalculateDate(2023)); } } }
using NUnit.Framework; namespace Ncqrs.Spec { public class SpecificationAttribute : TestFixtureAttribute { } }
using Microsoft.AspNetCore.Mvc; using Allergies.Models; namespace Allergies.Controllers { public class HomeController : Controller { [Route("/")] public ActionResult AllergyForm() { return View(); } [Route("/results")] public ActionResult Results(int score) { AllergyScore allergy = new AllergyScore(); allergy.Score = allergy.GetAllergyScore(score); return View(allergy); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace week5 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { VM vm = new VM(); public MainWindow() { InitializeComponent(); } Random r = new Random(date); private void Btn_Click(object sender, RoutedEventArgs e) { string text = string.Empty; File.AppendAllText("output.txt", "need to input string"); int x = 0; while (x < 7) { int v = r.Next(1, 21); x++; text += v + ' '; } File.AppendAllText("output.txt", text); File.AppendAllText("output.txt", Environment.NewLine); File.AppendAllText("output.txt", text); for (int i = 0; i < 7; i++) { lb.Items.Add(i); } int z = 0; do { lb.Items.Add(r.Next()); z++; } while (z<7); } } }
#nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Mvc.Rendering; using GroceryDelivery.Models; namespace GroceryDelivery.Pages.Customers { public class CustomerModel : PageModel { private readonly GroceryDbContext _context; private readonly ILogger<CustomerModel> _logger; public List<Customer> Customers {get; set;} public CustomerModel(GroceryDbContext context, ILogger<CustomerModel> logger) { _context = context; _logger = logger; } public void OnGet() { // Takes all current Customers in database and puts them in a list. Customers = _context.Customers.ToList(); } } }
namespace FootballPredictions.Models { public class Prediction { public int Id { get; set; } public Game Game { get; set; } public GameResult Result { get; set; } // TODO: prediction should have user } }
using Newtonsoft.Json; namespace Monaco.Editor { /// <summary> /// Configuration options for go to location /// </summary> public sealed class GoToLocationOptions { [JsonProperty("alternativeDeclarationCommand", NullValueHandling = NullValueHandling.Ignore)] public string AlternativeDeclarationCommand { get; set; } [JsonProperty("alternativeDefinitionCommand", NullValueHandling = NullValueHandling.Ignore)] public string AlternativeDefinitionCommand { get; set; } [JsonProperty("alternativeImplementationCommand", NullValueHandling = NullValueHandling.Ignore)] public string AlternativeImplementationCommand { get; set; } [JsonProperty("alternativeReferenceCommand", NullValueHandling = NullValueHandling.Ignore)] public string AlternativeReferenceCommand { get; set; } [JsonProperty("alternativeTypeDefinitionCommand", NullValueHandling = NullValueHandling.Ignore)] public string AlternativeTypeDefinitionCommand { get; set; } [JsonProperty("multiple", NullValueHandling = NullValueHandling.Ignore)] public Multiple? Multiple { get; set; } [JsonProperty("multipleDeclarations", NullValueHandling = NullValueHandling.Ignore)] public Multiple? MultipleDeclarations { get; set; } [JsonProperty("multipleDefinitions", NullValueHandling = NullValueHandling.Ignore)] public Multiple? MultipleDefinitions { get; set; } [JsonProperty("multipleImplementations", NullValueHandling = NullValueHandling.Ignore)] public Multiple? MultipleImplementations { get; set; } [JsonProperty("multipleReferences", NullValueHandling = NullValueHandling.Ignore)] public Multiple? MultipleReferences { get; set; } [JsonProperty("multipleTypeDefinitions", NullValueHandling = NullValueHandling.Ignore)] public Multiple? MultipleTypeDefinitions { get; set; } } }
using System; using System.Collections.Generic; namespace Tbs.DomainModels { internal class CommonStat { public HashSet<DateTime> DtHS {get; set; } public int[] Qtums { get; set; } public CommonStat(int count) { DtHS = new HashSet<DateTime>(); Qtums = new int[count]; } } }
using System.Collections.Generic; using MVsFileTypes.Contracts.Collections; namespace MVsFileTypes.Contracts.Validation { public class ValidationIncident { public string Extension { get; set; } public ValidationMode ValidationMode { get; set; } public IEnumerable<FileType> FileTypes { get; set; } public IEnumerable<FileTypeGroup> Groups { get; set; } } }
using System.Reflection; using Nancy; using SerpoServer.Api; using SerpoServer.Data.Models.Enums; namespace SerpoServer.Routes { public class DynamicModule : NancyModule { private Assembly asm = typeof(DynamicModule).Assembly; public DynamicModule(RequestManager rm) { Get("/", x => { var path = (string) x.path; return rm.GenerateResponse(Context, RequestMethods.Get); }); Post("/", x => { var path = (string) x.path; return rm.GenerateResponse(Context, RequestMethods.Post); }); Put("/", x => { var path = (string) x.path; return rm.GenerateResponse(Context, RequestMethods.Put); }); Delete("/", x => { var path = (string) x.path; return rm.GenerateResponse(Context, RequestMethods.Delete); }); Get("/*", x => { var path = (string) x.path; return rm.GenerateResponse(Context, RequestMethods.Get); }); Post("/*", x => { var path = (string) x.path; return rm.GenerateResponse(Context, RequestMethods.Post); }); Put("/*", x => { var path = (string) x.path; return rm.GenerateResponse(Context, RequestMethods.Put); }); Delete("/*", x => { var path = (string) x.path; return rm.GenerateResponse(Context, RequestMethods.Delete); }); } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.UI.Xaml.Controls; namespace Microsoft.Maui.Handlers { public partial class MenuFlyoutItemHandler { protected override MenuFlyoutItem CreatePlatformElement() { return new MenuFlyoutItem(); } protected override void ConnectHandler(MenuFlyoutItem PlatformView) { base.ConnectHandler(PlatformView); PlatformView.Click += OnClicked; } protected override void DisconnectHandler(MenuFlyoutItem PlatformView) { base.DisconnectHandler(PlatformView); PlatformView.Click -= OnClicked; } void OnClicked(object sender, UI.Xaml.RoutedEventArgs e) { VirtualView.Clicked(); } public static void MapSource(IMenuFlyoutItemHandler handler, IMenuFlyoutItem view) { handler.PlatformView.Icon = view.Source?.ToIconSource(handler.MauiContext!)?.CreateIconElement(); } public static void MapText(IMenuFlyoutItemHandler handler, IMenuFlyoutItem view) { handler.PlatformView.Text = view.Text; } public static void MapIsEnabled(IMenuFlyoutItemHandler handler, IMenuFlyoutItem view) => handler.PlatformView.UpdateIsEnabled(view.IsEnabled); } }
using System; namespace Acolyte.Numeric { public static class FloatExtensions { public static bool IsEqual(this float value, float otherValue, float tolerance) { return Math.Abs(value - otherValue) < tolerance; } public static bool IsEqual(this float value, float otherValue) { return IsEqual(value, otherValue, tolerance: 1E-6F); } } }
using Jacobi.Zim80.CpuZ80.Opcodes; using Jacobi.Zim80.CpuZ80.UnitTests; using Jacobi.Zim80.Diagnostics; using Jacobi.Zim80.Memory.UnitTests; using Jacobi.Zim80.Test; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace Jacobi.Zim80.CpuZ80.Instructions.UnitTests { [TestClass] public class LoadRepeatInstructionTest { private const ushort RdAddress = 0x04; private const ushort WrAddress = 0x08; private const byte Value1 = 0x55; private const byte Value2 = 0xAA; private const byte Length = 0x02; [TestMethod] public void LDI() { var ob = OpcodeByte.New(x: 2, z: 0, y: 4); var model = ExecuteTest(ob, (cpu) => { cpu.Registers.HL = RdAddress; cpu.Registers.DE = WrAddress; cpu.Registers.BC = Length; }, true); model.Cpu.AssertRegisters(hl: RdAddress + 1, de: WrAddress + 1, bc: Length - 1); model.Memory.Assert(WrAddress, Value1); } [TestMethod] public void LDD() { var ob = OpcodeByte.New(x: 2, z: 0, y: 5); var model = ExecuteTest(ob, (cpu) => { cpu.Registers.HL = RdAddress + 1; cpu.Registers.DE = WrAddress + 1; cpu.Registers.BC = Length; }, true); model.Cpu.AssertRegisters(hl: RdAddress, de: WrAddress, bc: Length - 1); model.Memory.Assert(WrAddress + 1, Value2); } [TestMethod] public void LDIR() { var ob = OpcodeByte.New(x: 2, z: 0, y: 6); var model = ExecuteTest(ob, (cpu) => { cpu.Registers.HL = RdAddress; cpu.Registers.DE = WrAddress; cpu.Registers.BC = Length; }, false); model.Cpu.AssertRegisters(hl: RdAddress + 2, de: WrAddress + 2, bc: 0); model.Memory.Assert(WrAddress, Value1); model.Memory.Assert(WrAddress + 1, Value2); } [TestMethod] public void LDDR() { var ob = OpcodeByte.New(x: 2, z: 0, y: 7); var model = ExecuteTest(ob, (cpu) => { cpu.Registers.HL = RdAddress + 1; cpu.Registers.DE = WrAddress + 1; cpu.Registers.BC = Length; }, false); model.Cpu.AssertRegisters(hl: RdAddress - 1, de: WrAddress - 1, bc: 0); model.Memory.Assert(WrAddress, Value1); model.Memory.Assert(WrAddress + 1, Value2); } private SimulationModel ExecuteTest(OpcodeByte ob, Action<CpuZ80> preTest, bool isConditionMet) { var cpu = new CpuZ80(); var model = cpu.Initialize( new byte[] { 0xED, ob.Value, 0, 0, Value1, Value2, 0, 0, 0, 0, 0 }); cpu.FillRegisters(); preTest(cpu); long cycles = 16; if (!isConditionMet) cycles += 21; model.ClockGen.SquareWave(cycles); Console.WriteLine(model.LogicAnalyzer.ToWaveJson()); return model; } } }
using SF.Entitys.Abstraction; using System.Security.Claims; using System.Collections.Generic; using System.Linq; using System; namespace SF.Web.Security { public class Permission { public const string ClaimType = "Permission"; public Permission() { } public Permission(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } Name = name; } public Permission(string name, string description) : this(name) { Description = description; } public long Id { get; set; } public string Name { get; set; } public string ActionAddress { get; set; } public string Description { get; set; } /// <summary> /// Id of the module which has registered this permission. /// </summary> public long ModuleId { get; set; } = -1; /// <summary> /// Display name of the group to which this permission belongs. The '|' character is used to separate Child and parent groups. /// </summary> public string GroupName { get; set; } /// <summary> /// Generate permissions string with scope combination /// </summary> public IEnumerable<string> GetPermissionWithScopeCombinationNames() { var retVal = new List<string>(); retVal.Add(Name.ToString()); return retVal; } public static implicit operator Claim(Permission p) { return new Claim(ClaimType, p.Name); } } }
using System.ComponentModel.Composition; using System.Waf.Applications; using System.Windows.Input; using Waf.BookLibrary.Library.Applications.Views; using Waf.BookLibrary.Library.Domain; namespace Waf.BookLibrary.Library.Applications.ViewModels; [Export] public class PersonViewModel : ViewModel<IPersonView> { private bool isValid = true; private Person? person; [ImportingConstructor] public PersonViewModel(IPersonView view) : base(view) { } public bool IsEnabled => Person != null; public bool IsValid { get => isValid; set => SetProperty(ref isValid, value); } public Person? Person { get => person; set { if (!SetProperty(ref person, value)) return; RaisePropertyChanged(nameof(IsEnabled)); } } public ICommand? CreateNewEmailCommand { get; set; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.IO; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DWGLib.Control { public partial class CSCECDECLib : UserControl { public string DWGPath = null; public ImageList ImageList; public CSCECDECLib(string DWGPath) { this.DWGPath = DWGPath; InitializeComponent(); } private void CSCECDECLib_Load(object sender, EventArgs e) { this.InitTreeView(DWGPath); } private void InitTreeView(string FolderPath) { this.FolderTree.ImageList = this.ImageList; string RootNodeName = Path.GetFileNameWithoutExtension(FolderPath); TreeNode RootNode = new TreeNode(RootNodeName); RootNode.ImageIndex = 1; string[] DirArr = Directory.GetDirectories(FolderPath); } private void InitImageList() { this.ImageList.Images.Add("Root",Properties.Resources.file_pdf); this.ImageList.Images.Add("Sub", Properties.Resources.file_pdf); } private void FolderTree_Click(object sender, EventArgs e) { } } }
#region FileInfo // Copyright (c) 2022 Wang Qirui. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // This file is part of Project Simulator. // File Name : ITimeLine.cs // Author : Qirui Wang // Created at : 2022/04/08 10:06 // Description : #endregion using Terminal.Gui; using Terminal.Gui.Graphs; using Attribute = Terminal.Gui.Attribute; namespace Simulator.UI; public class TimeLineSeries : ISeries { // TODO: add random color assign private static readonly Attribute[] Colors = { Application.Driver.MakeAttribute(Color.White, Color.Black), Application.Driver.MakeAttribute(Color.Blue, Color.Black), Application.Driver.MakeAttribute(Color.Brown, Color.Black), Application.Driver.MakeAttribute(Color.Cyan, Color.Black), Application.Driver.MakeAttribute(Color.Gray, Color.Black), Application.Driver.MakeAttribute(Color.Green, Color.Black), Application.Driver.MakeAttribute(Color.Magenta, Color.Black), Application.Driver.MakeAttribute(Color.Red, Color.Black), Application.Driver.MakeAttribute(Color.BrightBlue, Color.Black), Application.Driver.MakeAttribute(Color.BrightRed, Color.Black), Application.Driver.MakeAttribute(Color.BrightCyan, Color.Black), Application.Driver.MakeAttribute(Color.BrightGreen, Color.Black), Application.Driver.MakeAttribute(Color.BrightMagenta, Color.Black), Application.Driver.MakeAttribute(Color.BrightYellow, Color.Black) }; public readonly List<Timeline> Timelines = new(); public int Width { get; set; } = 2; public float Offset { get; set; } = 0; public bool DrawLabels { get; set; } = true; public void DrawSeries(GraphView graph, Rect drawBounds, RectangleF graphBounds) { for (var index = 0; index < Timelines.Count; ++index) { var y1 = Offset + (float)(index + 1) * Width; var screen1 = graph.GraphSpaceToScreen(new PointF(0f, y1)); if (screen1.Y < 0 || screen1.Y > drawBounds.Height - graph.MarginBottom) continue; if (Timelines[index].Intervals.Count != 0) DrawTimeLine(graph, screen1.Y, Timelines[index]); if (DrawLabels && !string.IsNullOrWhiteSpace(Timelines[index].Name)) graph.AxisY.DrawAxisLabel(graph, screen1.Y, Timelines[index].Name); } } public void Tick(int pid, int clock) { foreach (var timeline in Timelines) timeline.Tick(pid, clock); } public void AddProcess(in Process process) { Timelines.Add(new Timeline(process.ProcessId) { Name = process.Name ?? process.ProcessId.ToString() }); } private static void DrawTimeLine(GraphView graph, int height, Timeline beingDrawn) { var graphCellToRender = beingDrawn.Fill; if (graphCellToRender.Color.HasValue) Application.Driver.SetAttribute(graphCellToRender.Color.Value); foreach (var interval in beingDrawn.Intervals) { var left = new Point((int)(Math.Min(graph.Bounds.Width - 1, interval.Left) + graph.MarginLeft), height); var right = new Point((int)(Math.Min(graph.Bounds.Width - 1, interval.Right) + graph.MarginLeft), height); graph.DrawLine(left, right, graphCellToRender.Rune); } graph.SetDriverColorToGraphColor(); } public class Timeline { private readonly int _clock; public Timeline(int pid) { PId = pid; Fill = new GraphCellToRender('\u2593', Colors[pid % Colors.Length]); } public int PId { get; set; } public string Name { get; set; } = string.Empty; /// <summary> /// The color and character that will be rendered in the console /// when the bar extends over it /// </summary> public GraphCellToRender Fill { get; set; } public List<Interval> Intervals { get; set; } = new(); public void Tick(int pid, int clock) { if (pid != PId) return; if (Intervals.Count == 0) { Intervals.Add(new Interval { Left = clock, Right = clock }); } else { if (Intervals.Last().Right == clock - 1) Intervals.Last().Right = clock; else Intervals.Add(new Interval { Left = clock, Right = clock }); } } public class Interval { public int Left; public int Right; } } }
using ProtoBuf.Grpc.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mov.Core { public class GenericBinder : ServiceBinder { protected override string GetDefaultName(Type contractType) { var val = base.GetDefaultName(contractType); if (val.EndsWith("`1") && contractType.IsGenericType) { // replace IFoo`1 with IFoo`TheThing var args = contractType.GetGenericArguments(); if (args.Length == 1) { val = val[0..^1] + args[0].Name; } } return val; } } }
#Mon Feb 27 04:08:29 GMT 2017 lib/com.ibm.ws.dynacache.monitor_1.0.16.jar=ecc301655f93deb78297662a8abb9a07 lib/features/com.ibm.websphere.appserver.distributedMapPMI-1.0.mf=9efe6fa248f4e37f74c58e61f0aa4b52
using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; namespace CMiX.ColorPicker { public class ColorText : TextBox { protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.Key == Key.Enter) { BindingExpression bindingExpression = BindingOperations.GetBindingExpression(this, TextProperty); if (bindingExpression != null) bindingExpression.UpdateSource(); } } } }