content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Text.Json.Serialization; using System; using System.Collections.Generic; using System.Text; namespace AntDesign.Charts { public interface IGraphicStyle { [JsonPropertyName("fill")] public string Fill { get; set; } [JsonPropertyName("fillOpacity")] public decimal? FillOpacity { get; set; } [JsonPropertyName("stroke")] public string Stroke { get; set; } [JsonPropertyName("lineWidth")] public int? LineWidth { get; set; } [JsonPropertyName("lineDash")] public int[] LineDash { get; set; } [JsonPropertyName("lineOpacity")] public int? LineOpacity { get; set; } [JsonPropertyName("opacity")] public double? Opacity { get; set; } [JsonPropertyName("shadowColor")] public string ShadowColor { get; set; } [JsonPropertyName("shadowBlur")] public int? ShadowBlur { get; set; } [JsonPropertyName("shadowOffsetX")] public int? ShadowOffsetX { get; set; } [JsonPropertyName("shadowOffsetY")] public int? ShadowOffsetY { get; set; } [JsonPropertyName("cursor")] public string Cursor { get; set; } // [field: string]: any; } public class GraphicStyle : IGraphicStyle { [JsonPropertyName("fill")] public string Fill { get; set; } [JsonPropertyName("fillOpacity")] public decimal? FillOpacity { get; set; } [JsonPropertyName("stroke")] public string Stroke { get; set; } [JsonPropertyName("lineWidth")] public int? LineWidth { get; set; } [JsonPropertyName("lineDash")] public int[] LineDash { get; set; } [JsonPropertyName("lineOpacity")] public int? LineOpacity { get; set; } [JsonPropertyName("opacity")] public double? Opacity { get; set; } [JsonPropertyName("shadowColor")] public string ShadowColor { get; set; } [JsonPropertyName("shadowBlur")] public int? ShadowBlur { get; set; } [JsonPropertyName("shadowOffsetX")] public int? ShadowOffsetX { get; set; } [JsonPropertyName("shadowOffsetY")] public int? ShadowOffsetY { get; set; } [JsonPropertyName("cursor")] public string Cursor { get; set; } } }
34.791045
49
0.603604
[ "Apache-2.0" ]
CAPCHIK/ant-design-charts-blazor
src/AntDesign.Charts/Components/Configs/IGraphicStyle.cs
2,331
C#
using BolaoNet.Services.Controllers; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; namespace BolaoNet.Services.Areas.Boloes.Controllers { public class PagamentoController: GenericApiController<Domain.Entities.Boloes.Pagamento>, Domain.Interfaces.Services.Boloes.IPagamentoService { #region Properties /// <summary> /// Propriedade que retorna o objeto que possui regras de negócio do gerenciamento da entidade. /// </summary> private Domain.Interfaces.Services.Boloes.IPagamentoService Service { get { return (Domain.Interfaces.Services.Boloes.IPagamentoService)base.BaseBo; } } #endregion #region Constructors/Destructors //public PagamentoController() // : base(new Domain.Services.FactoryService(null).CreatePagamentoService()) //{ //} public PagamentoController(Domain.Interfaces.Services.Boloes.IPagamentoService service) : base(service) { } #endregion #region Methods #endregion #region IPagamentoService members [HttpPost] public override long Insert(Domain.Entities.Boloes.Pagamento entity) { long res = base.BaseBo.Insert(entity); Domain.Entities.Base.BaseEntity baseEntity = entity as Domain.Entities.Base.BaseEntity; string identityName = baseEntity.GetIdentifyName(); if (string.IsNullOrEmpty(identityName)) return res; object resIdentity = baseEntity.GetIdentityValue(); return 1; } [HttpPost] public override bool Delete(Domain.Entities.Boloes.Pagamento entity) { Domain.Entities.Boloes.Pagamento entityLoaded = base.Load(entity); return base.Delete(entityLoaded); } [HttpPost] public IList<Domain.Entities.Boloes.Pagamento> GetPagamentosBolao(Domain.Entities.Boloes.Bolao bolao) { return Service.GetPagamentosBolao(bolao); } [HttpPost] public IList<Domain.Entities.Boloes.Pagamento> GetPagamentosBolaoSoma(Domain.Entities.Boloes.Bolao bolao) { return Service.GetPagamentosBolaoSoma(bolao); } #endregion } }
27.848837
113
0.641754
[ "MIT" ]
Thoris/BolaoNet
BolaoNet.WebApi/Areas/Boloes/Controllers/PagamentoController.cs
2,398
C#
// ReSharper disable InconsistentNaming // ReSharper disable UnusedMember.Global // ReSharper disable ClassNeverInstantiated.Global namespace zentao.client.Core { public class StoryItem { public string id { get; set; } = ""; public string name { get; set; } = ""; } }
29.3
50
0.679181
[ "MIT" ]
lotosbin/zentao_dotnet
zentao.client/Core/StoryItem.cs
295
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using BuildXL.Utilities.Tracing; namespace BuildXL.Cache.ContentStore.Tracing { /// <summary> /// Lighter-weight implementation of <see cref="System.Diagnostics.Stopwatch"/> /// </summary> public readonly struct StopwatchSlim { private readonly TimeSpan _startTimestamp; private StopwatchSlim(TimeSpan startTimestamp) : this() { _startTimestamp = startTimestamp; } /// <summary> /// Elapsed time. /// </summary> public TimeSpan Elapsed => TimestampUtilities.Timestamp - _startTimestamp; /// <summary> /// Starts measuring elapsed time. /// </summary> public static StopwatchSlim Start() { return new StopwatchSlim(TimestampUtilities.Timestamp); } } }
26.828571
84
0.600639
[ "MIT" ]
Bhaskers-Blu-Org2/BuildXL
Public/Src/Cache/ContentStore/Library/Tracing/StopwatchSlim.cs
939
C#
using System.Runtime.Serialization; namespace AKDK.Messages.DockerEvents { /// <summary> /// Well-known event types used by the Docker API. /// </summary> public enum DockerEventType { /// <summary> /// An unknown event type. /// </summary> Unknown = 0, /// <summary> /// Attached container console. /// </summary> [EnumMember(Value = "attach")] Attach, /// <summary> /// Commit container changes. /// </summary> [EnumMember(Value = "commit")] Commit, /// <summary> /// Connected to a container. /// </summary> [EnumMember(Value = "connect")] Connect, /// <summary> /// Copied a container. /// </summary> [EnumMember(Value = "copy")] Copy, /// <summary> /// Created a container. /// </summary> [EnumMember(Value = "create")] Create, /// <summary> /// Deleted a container. /// </summary> [EnumMember(Value = "delete")] Delete, /// <summary> /// Destroyed a container. /// </summary> [EnumMember(Value = "destroy")] Destroy, /// <summary> /// Detached container console. /// </summary> [EnumMember(Value = "detach")] Detach, /// <summary> /// Container died. /// </summary> [EnumMember(Value = "die")] Die, /// <summary> /// Disconnected from a container. /// </summary> [EnumMember(Value = "disconnect")] Disconnect, /// <summary> /// Created a container via "docker exec". /// </summary> [EnumMember(Value = "exec_create")] ExecCreate, /// <summary> /// Detached console for a container via "docker exec". /// </summary> [EnumMember(Value = "exec_detach")] ExecDetach, /// <summary> /// Started a container via "docker exec". /// </summary> [EnumMember(Value = "exec_start")] ExecStart, /// <summary> /// Exported a container. /// </summary> [EnumMember(Value = "export")] Export, /// <summary> /// Container health status. /// </summary> [EnumMember(Value = "health_status")] HealthStatus, /// <summary> /// Imported a container. /// </summary> [EnumMember(Value = "import")] Import, /// <summary> /// Killed a container. /// </summary> [EnumMember(Value = "kill")] Kill, /// <summary> /// Loaded a container. /// </summary> [EnumMember(Value = "load")] Load, /// <summary> /// Mounted a volume into a container. /// </summary> [EnumMember(Value = "mount")] Mount, /// <summary> /// Container ran out of memory. /// </summary> [EnumMember(Value = "oom")] OutOfMemory, /// <summary> /// Paused a container. /// </summary> [EnumMember(Value = "pause")] Pause, /// <summary> /// Pulled an image. /// </summary> [EnumMember(Value = "pull")] Pull, /// <summary> /// Pushed an image. /// </summary> [EnumMember(Value = "push")] Push, /// <summary> /// Reloaded a container. /// </summary> [EnumMember(Value = "reload")] Reload, /// <summary> /// Renamed a container. /// </summary> [EnumMember(Value = "rename")] Rename, /// <summary> /// Resized a container (or is it an image?). /// </summary> [EnumMember(Value = "resize")] Resize, /// <summary> /// Restarted a container. /// </summary> [EnumMember(Value = "restart")] Restart, /// <summary> /// Saved container state. /// </summary> [EnumMember(Value = "save")] Save, /// <summary> /// Started a container. /// </summary> [EnumMember(Value = "start")] Start, /// <summary> /// Stopped a container. /// </summary> [EnumMember(Value = "stop")] Stop, /// <summary> /// Tagged an image. /// </summary> [EnumMember(Value = "tag")] Tag, /// <summary> /// Process info for a container. /// </summary> [EnumMember(Value = "top")] Top, /// <summary> /// Unmounted a volume from a container. /// </summary> [EnumMember(Value = "unmount")] Unmount, /// <summary> /// Unpaused a container. /// </summary> [EnumMember(Value = "unpause")] Unpause, /// <summary> /// Untagged an image. /// </summary> [EnumMember(Value = "untag")] Untag, /// <summary> /// Updated a container (or is it an image?). /// </summary> [EnumMember(Value = "update")] Update } }
22.275862
67
0.466138
[ "MIT" ]
tintoy/akdk
src/AKDK/Messages/DockerEvents/DockerEventType.cs
5,168
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Linq; using EnsureThat; using Microsoft.Extensions.Configuration; using Microsoft.Health.Extensions.DependencyInjection; using Microsoft.Health.Fhir.Core.Registration; using Microsoft.Health.Fhir.SqlServer.Features.Schema; using Microsoft.Health.Fhir.SqlServer.Features.Search; using Microsoft.Health.Fhir.SqlServer.Features.Search.Expressions.Visitors; using Microsoft.Health.Fhir.SqlServer.Features.Storage; using Microsoft.Health.SqlServer.Api.Registration; using Microsoft.Health.SqlServer.Configs; using Microsoft.Health.SqlServer.Features.Schema; using Microsoft.Health.SqlServer.Features.Schema.Model; using Microsoft.Health.SqlServer.Registration; namespace Microsoft.Extensions.DependencyInjection { public static class FhirServerBuilderSqlServerRegistrationExtensions { public static IFhirServerBuilder AddSqlServer(this IFhirServerBuilder fhirServerBuilder, IConfiguration configuration, Action<SqlServerDataStoreConfiguration> configureAction = null) { EnsureArg.IsNotNull(fhirServerBuilder, nameof(fhirServerBuilder)); IServiceCollection services = fhirServerBuilder.Services; services.AddSqlServerBase<SchemaVersion>(configuration, configureAction); services.AddSqlServerApi(); services.Add(provider => new SchemaInformation(SchemaVersionConstants.Min, SchemaVersionConstants.Max)) .Singleton() .AsSelf() .AsImplementedInterfaces(); services.Add<SqlServerFhirModel>() .Singleton() .AsSelf() .AsImplementedInterfaces(); services.Add<SearchParameterToSearchValueTypeMap>() .Singleton() .AsSelf(); services.Add<SqlServerFhirDataStore>() .Scoped() .AsSelf() .AsImplementedInterfaces(); services.Add<SqlServerFhirOperationDataStore>() .Scoped() .AsSelf() .AsImplementedInterfaces(); services.Add<SqlServerSearchService>() .Scoped() .AsSelf() .AsImplementedInterfaces(); AddSqlServerTableRowParameterGenerators(services); services.Add<NormalizedSearchParameterQueryGeneratorFactory>() .Singleton() .AsSelf(); services.Add<SqlRootExpressionRewriter>() .Singleton() .AsSelf(); services.Add<ChainFlatteningRewriter>() .Singleton() .AsSelf(); services.Add<StringOverflowRewriter>() .Singleton() .AsSelf(); services.Add<SortRewriter>() .Singleton() .AsSelf(); return fhirServerBuilder; } internal static void AddSqlServerTableRowParameterGenerators(this IServiceCollection serviceCollection) { var types = typeof(SqlServerFhirDataStore).Assembly.GetTypes().Where(t => t.IsClass && !t.IsAbstract).ToArray(); foreach (var type in types) { var interfaces = type.GetInterfaces().ToArray(); foreach (var interfaceType in interfaces) { if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IStoredProcedureTableValuedParametersGenerator<,>)) { serviceCollection.AddSingleton(type); } if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(ITableValuedParameterRowGenerator<,>)) { serviceCollection.Add(type).Singleton().AsSelf().AsService(interfaceType); } } } } } }
38.810811
190
0.595172
[ "MIT" ]
HiteshRamnani/fhir-server
src/Microsoft.Health.Fhir.SqlServer/Registration/FhirServerBuilderSqlServerRegistrationExtensions.cs
4,310
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Our.Umbraco.BlockListMvc.Models { internal class BlockListItemRendering { public string ControllerName { get; set; } public string ActionName { get; set; } public object RouteValues { get; set; } } }
22.75
50
0.703297
[ "MIT" ]
skttl/umbraco-blocklistmvc
src/Our.Umbraco.BlockListMvc/Models/BlockListItemRendering.cs
366
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Manual changes to this file will be overwritten if the code is regenerated. // // </auto-generated> //------------------------------------------------------------------------------ namespace UblSharp { using UblSharp.CommonAggregateComponents; using UblSharp.UnqualifiedDataTypes; using UblSharp.CommonExtensionComponents; /// <summary> /// A document used by a Contracting party to announce a project to buy goods, services, or works. /// <para />ComponentType: ABIE /// <para />DictionaryEntryName: Contract Notice. Details /// <para />ObjectClass: Contract Notice /// </summary> #if FEATURE_SERIALIZATION [System.SerializableAttribute()] #endif [System.Diagnostics.DebuggerStepThroughAttribute()] [System.Xml.Serialization.XmlTypeAttribute("ContractNotice", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:ContractNotice-2")] [System.Xml.Serialization.XmlRootAttribute("ContractNotice", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:ContractNotice-2", IsNullable=false)] public partial class ContractNoticeType : BaseDocument, IBaseDocument { private System.Collections.Generic.List<UBLExtensionType> _uBLExtensions; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlArrayAttribute("UBLExtensions", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2", Order=0)] [System.Xml.Serialization.XmlArrayItemAttribute("UBLExtension", IsNullable=false)] public UBLExtensionType[] @__UBLExtensions { get { return _uBLExtensions?.ToArray(); } set { _uBLExtensions = value == null ? null : new System.Collections.Generic.List<UBLExtensionType>(value); } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("UBLVersionID", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", Order=1)] public IdentifierType @__UBLVersionID; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("CustomizationID", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", Order=2)] public IdentifierType @__CustomizationID; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("ProfileID", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", Order=3)] public IdentifierType @__ProfileID; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("ProfileExecutionID", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", Order=4)] public IdentifierType @__ProfileExecutionID; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("ID", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", Order=5)] public IdentifierType @__ID; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("CopyIndicator", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", Order=6)] public IndicatorType @__CopyIndicator; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("UUID", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", Order=7)] public IdentifierType @__UUID; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("ContractFolderID", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", Order=8)] public IdentifierType @__ContractFolderID; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("IssueDate", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", Order=9)] public DateType @__IssueDate; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("IssueTime", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", Order=10)] public TimeType @__IssueTime; private System.Collections.Generic.List<TextType> _note; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("Note", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", Order=11)] public TextType[] @__Note { get { return _note?.ToArray(); } set { _note = value == null ? null : new System.Collections.Generic.List<TextType>(value); } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("RequestedPublicationDate", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", Order=12)] public DateType @__RequestedPublicationDate; private System.Collections.Generic.List<TextType> _regulatoryDomain; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("RegulatoryDomain", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", Order=13)] public TextType[] @__RegulatoryDomain { get { return _regulatoryDomain?.ToArray(); } set { _regulatoryDomain = value == null ? null : new System.Collections.Generic.List<TextType>(value); } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("FrequencyPeriod", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", Order=14)] public PeriodType @__FrequencyPeriod; private System.Collections.Generic.List<SignatureType> _signature; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("Signature", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", Order=15)] public SignatureType[] @__Signature { get { return _signature?.ToArray(); } set { _signature = value == null ? null : new System.Collections.Generic.List<SignatureType>(value); } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("ContractingParty", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", Order=16)] public ContractingPartyType @__ContractingParty; private System.Collections.Generic.List<CustomerPartyType> _originatorCustomerParty; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("OriginatorCustomerParty", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", Order=17)] public CustomerPartyType[] @__OriginatorCustomerParty { get { return _originatorCustomerParty?.ToArray(); } set { _originatorCustomerParty = value == null ? null : new System.Collections.Generic.List<CustomerPartyType>(value); } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("ReceiverParty", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", Order=18)] public PartyType @__ReceiverParty; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("TenderingTerms", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", Order=19)] public TenderingTermsType @__TenderingTerms; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("TenderingProcess", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", Order=20)] public TenderingProcessType @__TenderingProcess; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("ProcurementProject", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", Order=21)] public ProcurementProjectType @__ProcurementProject; private System.Collections.Generic.List<ProcurementProjectLotType> _procurementProjectLot; [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Xml.Serialization.XmlElementAttribute("ProcurementProjectLot", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", Order=22)] public ProcurementProjectLotType[] @__ProcurementProjectLot { get { return _procurementProjectLot?.ToArray(); } set { _procurementProjectLot = value == null ? null : new System.Collections.Generic.List<ProcurementProjectLotType>(value); } } /// <summary> /// A container for all extensions present in the document. /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] System.Collections.Generic.List<UBLExtensionType> IBaseDocument.UBLExtensions { get { return _uBLExtensions ?? (_uBLExtensions = new System.Collections.Generic.List<UBLExtensionType>()); } set { _uBLExtensions = value; } } /// <summary> /// Free-form text pertinent to this document, conveying information that is not contained explicitly in other structures. /// <para />ComponentType: BBIE /// <para />DictionaryEntryName: Contract Notice. Note. Text /// <para />Cardinality: 0..n /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Note /// <para />RepresentationTerm: Text /// <para />DataType: Text. Type /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public System.Collections.Generic.List<TextType> Note { get { return _note ?? (_note = new System.Collections.Generic.List<TextType>()); } set { _note = value; } } /// <summary> /// Information about the law that defines the regulatory domain. /// <para />ComponentType: BBIE /// <para />DictionaryEntryName: Contract Notice. Regulatory Domain. Text /// <para />Cardinality: 0..n /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Regulatory Domain /// <para />RepresentationTerm: Text /// <para />DataType: Text. Type /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public System.Collections.Generic.List<TextType> RegulatoryDomain { get { return _regulatoryDomain ?? (_regulatoryDomain = new System.Collections.Generic.List<TextType>()); } set { _regulatoryDomain = value; } } /// <summary> /// A signature applied to this document. /// <para />ComponentType: ASBIE /// <para />DictionaryEntryName: Contract Notice. Signature /// <para />Cardinality: 0..n /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Signature /// <para />AssociatedObjectClass: Signature /// <para />RepresentationTerm: Signature /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] System.Collections.Generic.List<SignatureType> IBaseDocument.Signature { get { return _signature ?? (_signature = new System.Collections.Generic.List<SignatureType>()); } set { _signature = value; } } /// <summary> /// A party who originally requested the tender. /// <para />ComponentType: ASBIE /// <para />DictionaryEntryName: Contract Notice. Originator_ Customer Party. Customer Party /// <para />Cardinality: 0..n /// <para />ObjectClass: Contract Notice /// <para />PropertyTermQualifier: Originator /// <para />PropertyTerm: Customer Party /// <para />AssociatedObjectClass: Customer Party /// <para />RepresentationTerm: Customer Party /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public System.Collections.Generic.List<CustomerPartyType> OriginatorCustomerParty { get { return _originatorCustomerParty ?? (_originatorCustomerParty = new System.Collections.Generic.List<CustomerPartyType>()); } set { _originatorCustomerParty = value; } } /// <summary> /// One of the procurement project lots into which this contract can be split. /// <para />ComponentType: ASBIE /// <para />DictionaryEntryName: Contract Notice. Procurement Project Lot /// <para />Cardinality: 0..n /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Procurement Project Lot /// <para />AssociatedObjectClass: Procurement Project Lot /// <para />RepresentationTerm: Procurement Project Lot /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public System.Collections.Generic.List<ProcurementProjectLotType> ProcurementProjectLot { get { return _procurementProjectLot ?? (_procurementProjectLot = new System.Collections.Generic.List<ProcurementProjectLotType>()); } set { _procurementProjectLot = value; } } /// <summary> /// Identifies the earliest version of the UBL 2 schema for this document type that defines all of the elements that might be encountered in the current instance. /// <para />ComponentType: BBIE /// <para />DictionaryEntryName: Contract Notice. UBL Version Identifier. Identifier /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: UBL Version Identifier /// <para />RepresentationTerm: Identifier /// <para />DataType: Identifier. Type /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] IdentifierType IBaseDocument.UBLVersionID { get { if (__UBLVersionID == null) { __UBLVersionID = new IdentifierType(); } return __UBLVersionID; } set { __UBLVersionID = value; } } /// <summary> /// Identifies a user-defined customization of UBL for a specific use. /// <para />ComponentType: BBIE /// <para />DictionaryEntryName: Contract Notice. Customization Identifier. Identifier /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Customization Identifier /// <para />RepresentationTerm: Identifier /// <para />DataType: Identifier. Type /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] IdentifierType IBaseDocument.CustomizationID { get { if (__CustomizationID == null) { __CustomizationID = new IdentifierType(); } return __CustomizationID; } set { __CustomizationID = value; } } /// <summary> /// Identifies a user-defined profile of the customization of UBL being used. /// <para />ComponentType: BBIE /// <para />DictionaryEntryName: Contract Notice. Profile Identifier. Identifier /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Profile Identifier /// <para />RepresentationTerm: Identifier /// <para />DataType: Identifier. Type /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] IdentifierType IBaseDocument.ProfileID { get { if (__ProfileID == null) { __ProfileID = new IdentifierType(); } return __ProfileID; } set { __ProfileID = value; } } /// <summary> /// Identifies an instance of executing a profile, to associate all transactions in a collaboration. /// <para />ComponentType: BBIE /// <para />DictionaryEntryName: Contract Notice. Profile Execution Identifier. Identifier /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Profile Execution Identifier /// <para />RepresentationTerm: Identifier /// <para />DataType: Identifier. Type /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] IdentifierType IBaseDocument.ProfileExecutionID { get { if (__ProfileExecutionID == null) { __ProfileExecutionID = new IdentifierType(); } return __ProfileExecutionID; } set { __ProfileExecutionID = value; } } /// <summary> /// An identifier for this document, assigned by the sender. /// <para />ComponentType: BBIE /// <para />DictionaryEntryName: Contract Notice. Identifier /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Identifier /// <para />RepresentationTerm: Identifier /// <para />DataType: Identifier. Type /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] IdentifierType IBaseDocument.ID { get { if (__ID == null) { __ID = new IdentifierType(); } return __ID; } set { __ID = value; } } /// <summary> /// Indicates whether this document is a copy (true) or not (false). /// <para />ComponentType: BBIE /// <para />DictionaryEntryName: Contract Notice. Copy_ Indicator. Indicator /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTermQualifier: Copy /// <para />PropertyTerm: Indicator /// <para />RepresentationTerm: Indicator /// <para />DataType: Indicator. Type /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public IndicatorType CopyIndicator { get { if (__CopyIndicator == null) { __CopyIndicator = new IndicatorType(); } return __CopyIndicator; } set { __CopyIndicator = value; } } /// <summary> /// A universally unique identifier for an instance of this document. /// <para />ComponentType: BBIE /// <para />DictionaryEntryName: Contract Notice. UUID. Identifier /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: UUID /// <para />RepresentationTerm: Identifier /// <para />DataType: Identifier. Type /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] IdentifierType IBaseDocument.UUID { get { if (__UUID == null) { __UUID = new IdentifierType(); } return __UUID; } set { __UUID = value; } } /// <summary> /// An identifier, assigned by the sender, for the process file (i.e., record) to which this document belongs. /// <para />ComponentType: BBIE /// <para />DictionaryEntryName: Contract Notice. Contract Folder Identifier. Identifier /// <para />Cardinality: 1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Contract Folder Identifier /// <para />RepresentationTerm: Identifier /// <para />DataType: Identifier. Type /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public IdentifierType ContractFolderID { get { if (__ContractFolderID == null) { __ContractFolderID = new IdentifierType(); } return __ContractFolderID; } set { __ContractFolderID = value; } } /// <summary> /// The date, assigned by the sender, on which this document was issued. /// <para />ComponentType: BBIE /// <para />DictionaryEntryName: Contract Notice. Issue Date. Date /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Issue Date /// <para />RepresentationTerm: Date /// <para />DataType: Date. Type /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public DateType IssueDate { get { if (__IssueDate == null) { __IssueDate = new DateType(); } return __IssueDate; } set { __IssueDate = value; } } /// <summary> /// The time, assigned by the sender, at which this document was issued. /// <para />ComponentType: BBIE /// <para />DictionaryEntryName: Contract Notice. Issue Time. Time /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Issue Time /// <para />RepresentationTerm: Time /// <para />DataType: Time. Type /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public TimeType IssueTime { get { if (__IssueTime == null) { __IssueTime = new TimeType(); } return __IssueTime; } set { __IssueTime = value; } } /// <summary> /// The requested publication date for this Contract Notice. /// <para />ComponentType: BBIE /// <para />DictionaryEntryName: Contract Notice. Requested_ Publication Date. Date /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTermQualifier: Requested /// <para />PropertyTerm: Publication Date /// <para />RepresentationTerm: Date /// <para />DataType: Date. Type /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public DateType RequestedPublicationDate { get { if (__RequestedPublicationDate == null) { __RequestedPublicationDate = new DateType(); } return __RequestedPublicationDate; } set { __RequestedPublicationDate = value; } } /// <summary> /// The estimated frequency of future notices. /// <para />ComponentType: ASBIE /// <para />DictionaryEntryName: Contract Notice. Frequency_ Period. Period /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTermQualifier: Frequency /// <para />PropertyTerm: Period /// <para />AssociatedObjectClass: Period /// <para />RepresentationTerm: Period /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public PeriodType FrequencyPeriod { get { if (__FrequencyPeriod == null) { __FrequencyPeriod = new PeriodType(); } return __FrequencyPeriod; } set { __FrequencyPeriod = value; } } /// <summary> /// The contracting party. /// <para />ComponentType: ASBIE /// <para />DictionaryEntryName: Contract Notice. Contracting Party /// <para />Cardinality: 1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Contracting Party /// <para />AssociatedObjectClass: Contracting Party /// <para />RepresentationTerm: Contracting Party /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public ContractingPartyType ContractingParty { get { if (__ContractingParty == null) { __ContractingParty = new ContractingPartyType(); } return __ContractingParty; } set { __ContractingParty = value; } } /// <summary> /// The party receiving this document. /// <para />ComponentType: ASBIE /// <para />DictionaryEntryName: Contract Notice. Receiver_ Party. Party /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTermQualifier: Receiver /// <para />PropertyTerm: Party /// <para />AssociatedObjectClass: Party /// <para />RepresentationTerm: Party /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public PartyType ReceiverParty { get { if (__ReceiverParty == null) { __ReceiverParty = new PartyType(); } return __ReceiverParty; } set { __ReceiverParty = value; } } /// <summary> /// The tendering terms associated with this tendering process. /// <para />ComponentType: ASBIE /// <para />DictionaryEntryName: Contract Notice. Tendering Terms /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Tendering Terms /// <para />AssociatedObjectClass: Tendering Terms /// <para />RepresentationTerm: Tendering Terms /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public TenderingTermsType TenderingTerms { get { if (__TenderingTerms == null) { __TenderingTerms = new TenderingTermsType(); } return __TenderingTerms; } set { __TenderingTerms = value; } } /// <summary> /// A description of the tendering process itself. /// <para />ComponentType: ASBIE /// <para />DictionaryEntryName: Contract Notice. Tendering Process /// <para />Cardinality: 0..1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Tendering Process /// <para />AssociatedObjectClass: Tendering Process /// <para />RepresentationTerm: Tendering Process /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public TenderingProcessType TenderingProcess { get { if (__TenderingProcess == null) { __TenderingProcess = new TenderingProcessType(); } return __TenderingProcess; } set { __TenderingProcess = value; } } /// <summary> /// An overall definition of this procurement project. /// <para />ComponentType: ASBIE /// <para />DictionaryEntryName: Contract Notice. Procurement Project /// <para />Cardinality: 1 /// <para />ObjectClass: Contract Notice /// <para />PropertyTerm: Procurement Project /// <para />AssociatedObjectClass: Procurement Project /// <para />RepresentationTerm: Procurement Project /// </summary> [System.Xml.Serialization.XmlIgnoreAttribute] public ProcurementProjectType ProcurementProject { get { if (__ProcurementProject == null) { __ProcurementProject = new ProcurementProjectType(); } return __ProcurementProject; } set { __ProcurementProject = value; } } } }
42.424451
179
0.60327
[ "MIT" ]
UblSharp/UblSharp
src/UblSharp/maindoc/UBL-ContractNotice-2.1.generated.cs
30,885
C#
namespace TheGoodBot.Entities.GuildAccounts { public class Stats { public uint AllMembersCombinedXp { get; set; } public uint AllMembersCommandsExecuted { get; set; } public uint AllMembersMessagesSent { get; set; } } }
25.7
60
0.669261
[ "MIT" ]
svr333/TheGoodBot
TheGoodBot/Entities/GuildAccounts/Stats.cs
259
C#
using FlightNode.Common.Exceptions; using FlightNode.Identity.Services.Models; using Moq; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using Xunit; namespace FlightNode.Identity.UnitTests.Controllers.UserControllerTests { public class GetAll { public class HappyPath : Fixture { private List<UserModel> list = new List<UserModel> { new UserModel() }; private HttpResponseMessage RunTest() { MockManager.Setup(x => x.FindAll()) .Returns(list); return BuildSystem().Get().ExecuteAsync(new System.Threading.CancellationToken()).Result; } [Fact] public void ConfirmHappyPathContent() { Assert.Same(list.First(), RunTest().Content.ReadAsAsync<List<UserModel>>().Result.First()); } [Fact] public void ConfirmHappyPathStatusCode() { Assert.Equal(HttpStatusCode.OK, RunTest().StatusCode); } } public class NoRecords : Fixture { private HttpResponseMessage RunTest() { MockManager.Setup(x => x.FindAll()) .Returns(new List<UserModel>()); return BuildSystem().Get().ExecuteAsync(new System.Threading.CancellationToken()).Result; } [Fact] public void ConfirmNotFoundStatusCode() { Assert.Equal(HttpStatusCode.NotFound, RunTest().StatusCode); } } public class ExceptionHandling : Fixture { private HttpResponseMessage RunTest(Exception ex) { MockManager.Setup(x => x.FindAll()) .Throws(ex); return BuildSystem().Get().ExecuteAsync(new System.Threading.CancellationToken()).Result; } [Fact] public void ConfirmHandlingOfInvalidOperation() { MockLogger.Setup(x => x.Error(It.IsAny<Exception>())); var e = new InvalidOperationException(); Assert.Equal(HttpStatusCode.InternalServerError, RunTest(e).StatusCode); } [Fact] public void ConfirmHandlingOfServerError() { MockLogger.Setup(x => x.Error(It.IsAny<Exception>())); var e = ServerException.HandleException<ExceptionHandling>(new Exception(), "asdf"); Assert.Equal(HttpStatusCode.InternalServerError, RunTest(e).StatusCode); } [Fact] public void ConfirmHandlingOfUserError() { MockLogger.Setup(x => x.Debug(It.IsAny<Exception>())); var e = new UserException("asdf"); Assert.Equal(HttpStatusCode.BadRequest, RunTest(e).StatusCode); } } } }
30.51
107
0.545395
[ "MIT" ]
FlightNode/FlightNode.Api
Identity/test/Controllers/UserControllerTests/GetAll.cs
3,053
C#
using Microsoft.Extensions.Options; using MongoDB.Driver; using MongoDB.Bson.Serialization; namespace CalBookApi { public class CalBookContext : ICalBookContext { private readonly IMongoDatabase _db; public CalBookContext(IOptions<Settings> options, IMongoClient client) { _db = client.GetDatabase(options.Value.Database); } public IMongoCollection<Appointment> Appointments => _db.GetCollection<Appointment>("Appointment"); } }
27.555556
107
0.711694
[ "MIT" ]
sidspencer/calbook
AppointmentApi/CalBookContext.cs
496
C#
//------------------------------------------------------------------------------ // <copyright file="ReadOnlyAttribute.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.ComponentModel { using System.Diagnostics; using System; /// <include file='doc\ReadOnlyAttribute.uex' path='docs/doc[@for="ReadOnlyAttribute"]/*' /> /// <devdoc> /// <para>Specifies whether the property this attribute is bound to /// is read-only or read/write.</para> /// </devdoc> [AttributeUsage(AttributeTargets.All)] public sealed class ReadOnlyAttribute : Attribute { private bool isReadOnly = false; /// <include file='doc\ReadOnlyAttribute.uex' path='docs/doc[@for="ReadOnlyAttribute.Yes"]/*' /> /// <devdoc> /// <para> /// Specifies that the property this attribute is bound to is read-only and /// cannot be modified in the server explorer. This <see langword='static '/>field is /// read-only. /// </para> /// </devdoc> public static readonly ReadOnlyAttribute Yes = new ReadOnlyAttribute(true); /// <include file='doc\ReadOnlyAttribute.uex' path='docs/doc[@for="ReadOnlyAttribute.No"]/*' /> /// <devdoc> /// <para> /// Specifies that the property this attribute is bound to is read/write and can /// be modified at design time. This <see langword='static '/>field is read-only. /// </para> /// </devdoc> public static readonly ReadOnlyAttribute No = new ReadOnlyAttribute(false); /// <include file='doc\ReadOnlyAttribute.uex' path='docs/doc[@for="ReadOnlyAttribute.Default"]/*' /> /// <devdoc> /// <para> /// Specifies the default value for the <see cref='System.ComponentModel.ReadOnlyAttribute'/> , which is <see cref='System.ComponentModel.ReadOnlyAttribute.No'/>, that is, /// the property this attribute is bound to is read/write. This <see langword='static'/> field is read-only. /// </para> /// </devdoc> public static readonly ReadOnlyAttribute Default = No; /// <include file='doc\ReadOnlyAttribute.uex' path='docs/doc[@for="ReadOnlyAttribute.ReadOnlyAttribute"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.ReadOnlyAttribute'/> class. /// </para> /// </devdoc> public ReadOnlyAttribute(bool isReadOnly) { this.isReadOnly = isReadOnly; } /// <include file='doc\ReadOnlyAttribute.uex' path='docs/doc[@for="ReadOnlyAttribute.IsReadOnly"]/*' /> /// <devdoc> /// <para> /// Gets a value indicating whether the property this attribute is bound to is /// read-only. /// </para> /// </devdoc> public bool IsReadOnly { get { return isReadOnly; } } /// <include file='doc\ReadOnlyAttribute.uex' path='docs/doc[@for="ReadOnlyAttribute.Equals"]/*' /> /// <internalonly/> /// <devdoc> /// </devdoc> public override bool Equals(object value) { if (this == value) { return true; } ReadOnlyAttribute other = value as ReadOnlyAttribute; return other != null && other.IsReadOnly == IsReadOnly; } /// <include file='doc\ReadOnlyAttribute.uex' path='docs/doc[@for="ReadOnlyAttribute.GetHashCode"]/*' /> /// <devdoc> /// <para> /// Returns the hashcode for this object. /// </para> /// </devdoc> public override int GetHashCode() { return base.GetHashCode(); } /// <include file='doc\ReadOnlyAttribute.uex' path='docs/doc[@for="ReadOnlyAttribute.IsDefaultAttribute"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Determines if this attribute is the default. /// </para> /// </devdoc> public override bool IsDefaultAttribute() { return (this.IsReadOnly == Default.IsReadOnly); } } }
40.421053
186
0.523003
[ "Unlicense" ]
bestbat/Windows-Server
com/netfx/src/framework/compmod/system/componentmodel/readonlyattribute.cs
4,608
C#
using System; using Autofac; using RP_Server_Scripts.Authentication; using RP_Server_Scripts.Autofac; using RP_Server_Scripts.Character.AccountComponent; using RP_Server_Scripts.Character.MessageHandler; using RP_Server_Scripts.Character.MessageHandler.InformationWriter; using RP_Server_Scripts.Character.Transaction; using RP_Server_Scripts.Character.Transaction.SaveCharacter; using RP_Server_Scripts.Component; using RP_Server_Scripts.Network; namespace RP_Server_Scripts.Character { public sealed class CharacterModule : Module { protected override void Load(ContainerBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } var allConstructorFinder = new AllConstructorFinder(); builder.RegisterType<CharacterVisualsWriter>().AsSelf().SingleInstance().FindConstructorsWith(allConstructorFinder); builder.RegisterType<DefaultSpawnPointProvider>().As<ISpawnPointProvider>().SingleInstance().FindConstructorsWith(allConstructorFinder); builder.RegisterType<CharacterTemplateSelector>().As<ICharacterTemplateSelector>().SingleInstance().FindConstructorsWith(allConstructorFinder); builder.RegisterType<CharacterBuilder>().AsSelf().SingleInstance().FindConstructorsWith(allConstructorFinder); //Transactions(Encapsulations of database code heavy actions that can be triggered via the CharacterService) builder.RegisterType<CreateHumanPlayerCharacterTransaction>().AsSelf().SingleInstance().FindConstructorsWith(allConstructorFinder); builder.RegisterType<CheckCharacterExistsTransaction>().AsSelf().SingleInstance().FindConstructorsWith(allConstructorFinder); builder.RegisterType<AddCharacterOwnerShipTransaction>().AsSelf().SingleInstance().FindConstructorsWith(allConstructorFinder); builder.RegisterType<GetAccountOwnedCharactersTransaction>().AsSelf().SingleInstance().FindConstructorsWith(allConstructorFinder); builder.RegisterType<SetAccountActiveCharacterTransaction>().AsSelf().SingleInstance().FindConstructorsWith(allConstructorFinder); builder.RegisterType<GetAccountActiveCharacterTransaction>().AsSelf().SingleInstance().FindConstructorsWith(allConstructorFinder); builder.RegisterType<GetCharacterOwnershipsCountTransaction>().AsSelf().SingleInstance().FindConstructorsWith(allConstructorFinder); builder.RegisterType<SaveCharacterTransaction>().AsSelf().SingleInstance().FindConstructorsWith(allConstructorFinder); // Account components builder.RegisterType<CharacterListLocator>().As<IComponentLocator<Account>>().SingleInstance(); //Register the service. This is a somewhat more complicated than because of the possible circular references with the transaction classes. builder.Register(context => new CharacterService() { }).OnActivated(args => { args.Instance.AddCharacterOwnerShipTransaction = args.Context.Resolve<AddCharacterOwnerShipTransaction>(); args.Instance.GetAccountOwnedCharactersTransaction = args.Context.Resolve<GetAccountOwnedCharactersTransaction>(); args.Instance.CharacterExistsTransaction = args.Context.Resolve<CheckCharacterExistsTransaction>(); args.Instance.CreateHumanPlayerCharacterTransaction = args.Context.Resolve<CreateHumanPlayerCharacterTransaction>(); args.Instance.SetAccountActiveCharacterTransaction = args.Context.Resolve<SetAccountActiveCharacterTransaction>(); args.Instance.GetAccountActiveCharacterTransaction = args.Context.Resolve<GetAccountActiveCharacterTransaction>(); args.Instance.GetCharacterOwnershipsCountTransaction = args.Context.Resolve<GetCharacterOwnershipsCountTransaction>(); args.Instance.SaveCharacterTransaction = args.Context.Resolve<SaveCharacterTransaction>(); args.Instance.AuthenticationService = args.Context.Resolve<AuthenticationService>(); //Initialize the service. args.Instance.Init(); }).AsSelf() .SingleInstance(); //Message Handling builder.RegisterType<CharacterCreationMessageHandler>().As<IScriptMessageHandler>().SingleInstance().FindConstructorsWith(allConstructorFinder); builder.RegisterType<RequestCharacterListMessageHandler>().As<IScriptMessageHandler>().SingleInstance().FindConstructorsWith(allConstructorFinder); builder.RegisterType<JoinGameMessageHandler>().As<IScriptMessageHandler>().SingleInstance().FindConstructorsWith(allConstructorFinder); builder.RegisterType<LeaveGameMessageHandler>().As<IScriptMessageHandler>().SingleInstance().FindConstructorsWith(allConstructorFinder); //Database initialization builder.RegisterType<CharacterItemsInitialization>().AsSelf().SingleInstance().AutoActivate().FindConstructorsWith(allConstructorFinder); //Other initializations builder.RegisterType<AccountLogoutHandling>().AsSelf().SingleInstance().AutoActivate(); } } }
61.954545
159
0.727806
[ "BSD-2-Clause" ]
JulianVo/SumpfkrautOnline-Khorinis
RP_Server_Scripts.Character/CharacterModule.cs
5,454
C#
// ************************************************************* // project: graphql-aspnet // -- // repo: https://github.com/graphql-aspnet // docs: https://graphql-aspnet.github.io // -- // License: MIT // ************************************************************* namespace GraphQL.AspNet.Interfaces.Execution { /// <summary> /// An extended field invocation context with additional properties related to subscriptions. /// </summary> public interface IGraphSubscriptionFieldInvocationContext : IGraphFieldInvocationContext { /// <summary> /// Gets the name of the event that maps to this field. /// </summary> /// <value>The name of the event.</value> string EventName { get; } } }
34.318182
97
0.537748
[ "MIT" ]
NET1211/aspnet-archive-tools
src/graphql-aspnet-subscriptions/Interfaces/Execution/IGraphSubscriptionFieldInvocationContext.cs
757
C#
using Microsoft.AspNetCore.Http; using Newtonsoft.Json; public static class SessionExtensions { public static void SetObject(this ISession session, string key, object value) { session.SetString(key, JsonConvert.SerializeObject(value)); } public static T GetObject<T>(this ISession session, string key) { var value = session.GetString(key); return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value); } }
29.4375
84
0.700637
[ "MIT" ]
billkoul/TrackPi
application/MVC/Config/User/SessionExtensions.cs
473
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using AfterburnerDataHandler.Servers.Serial; using AfterburnerDataHandler.Servers.Logger; namespace AfterburnerDataHandler.Projects { class ProjectsManager { public static SerialPortServer SerialPortServer { get; set; } public static LoggerServer LoggerServer { get; set; } public static bool IsSerialPortServerSaved { get { return !SerialPortServer?.Settings?.IsDirty ?? true; } } public static bool IsLoggerServerSaved { get { return !LoggerServer?.Settings?.IsDirty ?? true; } } public static bool LoadLastSerialPortProject() { string projectPath = Properties.Settings.Default.SerialPort_LastProject; if (File.Exists(projectPath)) { SerialPortProject newProject = null; ProjectsUtils.LoadProject(projectPath, ref newProject); if (SerialPortServer != null && ProjectsUtils.LoadProject(projectPath, ref newProject)) { SerialPortServer.Settings = newProject; return true; } } return false; } public static bool LoadLastLoggerProject() { string projectPath = Properties.Settings.Default.Logger_LastProject; if (File.Exists(projectPath)) { LoggerProject newProject = null; ProjectsUtils.LoadProject(projectPath, ref newProject); if (LoggerServer != null && ProjectsUtils.LoadProject(projectPath, ref newProject)) { LoggerServer.Settings = newProject; return true; } } return false; } } }
27.310811
103
0.564572
[ "MIT" ]
busayn/Afterburner-Data-Handler
Projects/ProjectsManager.cs
2,023
C#
namespace P01_HospitalDatabase.Data.Models { using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public class Patient { public Patient() { this.Prescriptions = new HashSet<PatientMedicament>(); this.Visitations = new HashSet<Visitation>(); this.Diagnoses = new HashSet<Diagnose>(); } [Key] public int PatientId { get; set; } [Required] [MaxLength(50)] public string FirstName { get; set; } [Required] [MaxLength(50)] public string LastName { get; set; } [Required] [MaxLength(250)] public string Address { get; set; } [Required] [MaxLength(80)] public string Email { get; set; } public bool HasInsurance { get; set; } public virtual ICollection<PatientMedicament> Prescriptions { get; set; } public virtual ICollection<Visitation> Visitations { get; set; } public virtual ICollection<Diagnose> Diagnoses { get; set; } } }
25.209302
81
0.590406
[ "MIT" ]
ivanov-mi/SoftUni-Training
05EntityFrameworkCore/05LINQ/P01_HospitalDatabase/Data/Models/Patient.cs
1,086
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; namespace System.ComponentModel.Design { /// <summary> /// Provides access to get and set option values for a designer. /// </summary> public interface IDesignerOptionService { /// <summary> /// Gets the value of an option defined in this package. /// </summary> [RequiresUnreferencedCode("The option value's Type cannot be statically discovered.")] object GetOptionValue(string pageName, string valueName); /// <summary> /// Sets the value of an option defined in this package. /// </summary> [RequiresUnreferencedCode("The option value's Type cannot be statically discovered.")] void SetOptionValue(string pageName, string valueName, object value); } }
36.076923
94
0.676972
[ "MIT" ]
Alex-ABPerson/runtime
src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/IDesignerOptionService.cs
938
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GenderColors.WinPhone81")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GenderColors.WinPhone81")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
36.655172
84
0.745061
[ "Apache-2.0" ]
NoleHealth/xamarin-forms-book-preview-2
Chapter23/GenderColors/GenderColors/GenderColors.WinPhone81/Properties/AssemblyInfo.cs
1,066
C#
using Newtonsoft.Json; using NUnit.Framework; using RxTelegram.Bot.Interface.BaseTypes.Enums; using RxTelegram.Bot.Interface.Passport.Enum; namespace RxTelegram.Bot.UnitTests.JsonConverters { [TestFixture] public class StringEnumConverterTest : BaseConverterTest { [Test] public void SerializeElementType() { var objectToSerialize = new { elementType = ElementType.BankStatement }; var json = JsonConvert.SerializeObject(objectToSerialize); Assert.NotNull(json); Assert.True(json.Contains("bank_statement")); } [Test] public void SerializeParseMode() { var objectToSerialize = new { parse = ParseMode.Markdown }; var json = JsonConvert.SerializeObject(objectToSerialize); Assert.NotNull(json); Assert.True(json.Contains("markdown")); } } }
30.131579
79
0.518777
[ "MIT" ]
RxTelegram/RxTelegram.Bot
src/UnitTests/JsonConverters/StringEnumConverterTest.cs
1,147
C#
using System; using System.Collections.Generic; using System.IO; using System.Web.Http; using Facility.ConformanceApi; using Facility.ConformanceApi.Testing; using Microsoft.Owin.Hosting; using Owin; namespace WebApiControllerServer { public static class WebApiControllerServerApp { public static void Main() { const string url = "http://localhost:4117"; using (WebApp.Start<Startup>(url)) { Console.WriteLine($"Server started: {url}"); Console.WriteLine("Press a key to stop."); Console.ReadKey(); } } public static readonly IConformanceApi Service = new ConformanceApiService(LoadTests()); private sealed class Startup { public void Configuration(IAppBuilder app) { var configuration = new HttpConfiguration(); configuration.MapHttpAttributeRoutes(); app.UseWebApi(configuration); } } private static IReadOnlyList<ConformanceTestInfo> LoadTests() { using (var testsJsonReader = new StreamReader(typeof(WebApiControllerServerApp).Assembly.GetManifestResourceStream("WebApiControllerServer.ConformanceTests.json"))) return ConformanceTestsInfo.FromJson(testsJsonReader.ReadToEnd()).Tests!; } } }
26.704545
167
0.754894
[ "MIT" ]
jzbrooks/FacilityAspNet
conformance/WebApiControllerServer/WebApiControllerServerApp.cs
1,175
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Health : MonoBehaviour, IDamageable { [SerializeField] protected int maxHealth = 100; [SerializeField] private int health; public event Action OnDied; private void Awake() { health = maxHealth; } public void TakeDamage(int amount) { health -= amount; if (health <= 0) { health = 0; Died(); //invoke died event } UIHealthBar.instance.SetValue(health / (float)maxHealth); // invoke damaged event } public void Heal(int amount) { health += amount; if (health >= maxHealth) { health = maxHealth; } UIHealthBar.instance.SetValue(health / (float)maxHealth); // invoke recovery event } public float GetHealthPercent() { return health / (float)maxHealth; } private void Died() { Destroy(gameObject); OnDied?.Invoke(); LevelManager.instance.Respawn(); } public float GetMaxHealth() { return maxHealth; } }
19.616667
65
0.575191
[ "MIT" ]
arsoljon/Senior-Project-4390
Senior Project/Assets/Scripts/Entities/Health.cs
1,177
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class PlayerMovement_sb : MonoBehaviour { public float velocidad; public float salto; float siguienteSalto = 0f; public float cadenciaSalto; public bool movimiento; public bool saltando; public bool saltoEnable; public bool Izquierda; public bool Derecha; // Use this for initialization void Start () { Derecha = true; } // Update is called once per frame void Update () { if (((Input.GetKey(KeyCode.A)) || (Input.GetKey(KeyCode.D))) && (movimiento == true)) { if (Input.GetKey(KeyCode.A)) { Derecha = false; Izquierda = true; gameObject.GetComponent<Transform>().Translate(Vector2.left * velocidad); gameObject.GetComponent<Animator>().SetBool("Movimiento", true); } if (Input.GetKey(KeyCode.D)) { Izquierda = false; Derecha = true; gameObject.GetComponent<Transform>().Translate(Vector2.right * velocidad); gameObject.GetComponent<Animator>().SetBool("Movimiento", true); } } else { gameObject.GetComponent<Animator>().SetBool("Movimiento", false); } if (Input.GetKey(KeyCode.K)) { gameObject.GetComponent<Animator>().SetBool("Baile", true); } else { gameObject.GetComponent<Animator>().SetBool("Baile", false); } if (Input.GetKey(KeyCode.L)) { gameObject.GetComponent<Animator>().SetBool("Saludo", true); } else { gameObject.GetComponent<Animator>().SetBool("Saludo", false); } if ((Input.GetKey(KeyCode.LeftShift)) && (Input.GetKey(KeyCode.I))) { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } if((Input.GetKey(KeyCode.Space)) && (saltoEnable == true) && (Time.time > siguienteSalto)) { siguienteSalto = Time.time + cadenciaSalto; saltoEnable = false; gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, salto)); } if(Izquierda == true) { gameObject.GetComponent<Transform>().localScale = new Vector3(-0.592f, 0.592f, 0.592f); } if (Derecha == true) { gameObject.GetComponent<Transform>().localScale = new Vector3(0.592f, 0.592f, 0.592f); } if(saltando == true) { gameObject.GetComponent<Animator>().SetBool("Salto", true); } } void OnCollisionStay2D(Collision2D coliSt) { if(coliSt.gameObject.tag == "Plataforma") { saltando = false; saltoEnable = true; movimiento = true; gameObject.GetComponent<Animator>().SetBool("Salto", false); } if((coliSt.gameObject.tag == "Enemigo") && (coliSt.gameObject.GetComponent<EnemyManager>().Dañable == false)) { Debug.Log("Se puede empujar"); gameObject.GetComponent<Animator>().SetBool("Empujar", true); } else { gameObject.GetComponent<Animator>().SetBool("Empujar", false); } if ((coliSt.gameObject.tag == "Enemigo") && (coliSt.gameObject.GetComponent<EnemyManager>().Dañable == false) && (Input.GetKey(KeyCode.K))) { coliSt.gameObject.GetComponent<EnemyManager>().Curable = false; coliSt.gameObject.GetComponent<EnemyManager>().IzquierdaPelota = true; } } void OnCollisionEnter2D(Collision2D coll) { if ((coll.gameObject.tag == "Enemigo") && (coll.gameObject.GetComponent<EnemyManager>().Dañable == false)) { Debug.Log("Se puede empujar"); gameObject.GetComponent<Animator>().SetBool("Empujar", true); } else { gameObject.GetComponent<Animator>().SetBool("Empujar", false); } } void OnCollisionExit2D(Collision2D coliEx) { if(coliEx.gameObject.tag == "Plataforma") { saltando = true; saltoEnable = false; } } }
30.381944
147
0.561829
[ "Apache-2.0" ]
inhart/Demo
Assets/Scripts/sb/PlayerMovement_sb.cs
4,380
C#
#region License /** * HinabitaYo * * Copyright (c) 2015 @inujini_ (https://twitter.com/inujini_) * * This software is released under the MIT License. * http://opensource.org/licenses/mit-license.php */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Net.Http; using System.Configuration; using System.Web; using log4net; namespace HinabitterYo { class Yo : IDisposable { private static readonly ILog _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private const string URI_YO_ALL = "http://api.justyo.co/yoall/"; private readonly string API_KEY; private readonly HttpClient _client; public Yo() { _client = new HttpClient(); _client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0"); API_KEY = ConfigurationManager.AppSettings["YoKey"]; } public void YoAll(List<IYoItem> items) { foreach (var item in items) { var query = HttpUtility.ParseQueryString(""); query["api_token"] = API_KEY; query["link"] = item.Link; _client.PostAsync(URI_YO_ALL, new StringContent(query.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded")) .ContinueWith(t => { if (t.Exception != null) { foreach (var e in t.Exception.InnerExceptions) { _logger.Fatal("yo is failed.", e); } return; } var r = t.Result; if (r.IsSuccessStatusCode) { _logger.InfoFormat("{0}: sent yo. id:{1}", item.FromAccount.GetAccountName(), item.ID); } else { _logger.Error(string.Format("yo is failed. status code:{0} return message:{1}" , r.StatusCode, r.Content.ReadAsStringAsync().Result)); } }); Thread.Sleep(TimeSpan.FromMinutes(1)); } } #region IDisposable Support private bool disposedValue = false; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _client.Dispose(); } disposedValue = true; } } public void Dispose() { Dispose(true); } #endregion } }
28.990291
134
0.475887
[ "MIT" ]
tumbling-dice/HinabitterYo
HinabitterYo/Yo.cs
2,988
C#
namespace TileMapEditor.Forms { partial class frm_OutputPictureMap { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.txtWidth = new System.Windows.Forms.NumericUpDown(); this.label8 = new System.Windows.Forms.Label(); this.txtHeight = new System.Windows.Forms.NumericUpDown(); this.label7 = new System.Windows.Forms.Label(); this.txtOutputPath = new TileMapEditor.Controls.ControlsEx.PromptTextBox(); this.btnBrowse = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.cbbFormat = new System.Windows.Forms.ComboBox(); this.btnConfirm = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.txtWidth)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtHeight)).BeginInit(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // txtWidth // this.txtWidth.Location = new System.Drawing.Point(74, 80); this.txtWidth.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.txtWidth.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.txtWidth.Name = "txtWidth"; this.txtWidth.Size = new System.Drawing.Size(80, 21); this.txtWidth.TabIndex = 19; this.txtWidth.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label8.Location = new System.Drawing.Point(39, 85); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(29, 12); this.label8.TabIndex = 18; this.label8.Text = "宽度"; // // txtHeight // this.txtHeight.Location = new System.Drawing.Point(74, 107); this.txtHeight.Maximum = new decimal(new int[] { 9999, 0, 0, 0}); this.txtHeight.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.txtHeight.Name = "txtHeight"; this.txtHeight.Size = new System.Drawing.Size(80, 21); this.txtHeight.TabIndex = 21; this.txtHeight.Value = new decimal(new int[] { 1, 0, 0, 0}); // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label7.Location = new System.Drawing.Point(39, 111); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(29, 12); this.label7.TabIndex = 20; this.label7.Text = "高度"; // // txtOutputPath // this.txtOutputPath.ForeColor = System.Drawing.Color.Gray; this.txtOutputPath.Location = new System.Drawing.Point(74, 26); this.txtOutputPath.Name = "txtOutputPath"; this.txtOutputPath.PromptText = ""; this.txtOutputPath.Size = new System.Drawing.Size(234, 21); this.txtOutputPath.TabIndex = 8; // // btnBrowse // this.btnBrowse.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnBrowse.Font = new System.Drawing.Font("微软雅黑", 7.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.btnBrowse.Location = new System.Drawing.Point(314, 25); this.btnBrowse.Name = "btnBrowse"; this.btnBrowse.Size = new System.Drawing.Size(37, 22); this.btnBrowse.TabIndex = 5; this.btnBrowse.Text = "浏览"; this.btnBrowse.UseVisualStyleBackColor = true; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label4.Location = new System.Drawing.Point(15, 30); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(53, 12); this.label4.TabIndex = 1; this.label4.Text = "导出位置"; // // groupBox1 // this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.txtHeight); this.groupBox1.Controls.Add(this.txtWidth); this.groupBox1.Controls.Add(this.label7); this.groupBox1.Controls.Add(this.cbbFormat); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.txtOutputPath); this.groupBox1.Controls.Add(this.label8); this.groupBox1.Controls.Add(this.btnBrowse); this.groupBox1.Location = new System.Drawing.Point(6, 8); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(361, 140); this.groupBox1.TabIndex = 27; this.groupBox1.TabStop = false; this.groupBox1.Text = "导出设置"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label3.Location = new System.Drawing.Point(155, 111); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(41, 12); this.label3.TabIndex = 24; this.label3.Text = "(像素)"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label2.Location = new System.Drawing.Point(155, 85); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(41, 12); this.label2.TabIndex = 23; this.label2.Text = "(像素)"; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label1.Location = new System.Drawing.Point(15, 58); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(53, 12); this.label1.TabIndex = 22; this.label1.Text = "图片格式"; // // cbbFormat // this.cbbFormat.FormattingEnabled = true; this.cbbFormat.Items.AddRange(new object[] { "PNG", "BMP", "JPEG"}); this.cbbFormat.Location = new System.Drawing.Point(74, 54); this.cbbFormat.Name = "cbbFormat"; this.cbbFormat.Size = new System.Drawing.Size(121, 20); this.cbbFormat.TabIndex = 9; // // btnConfirm // this.btnConfirm.Location = new System.Drawing.Point(211, 154); this.btnConfirm.Name = "btnConfirm"; this.btnConfirm.Size = new System.Drawing.Size(75, 23); this.btnConfirm.TabIndex = 28; this.btnConfirm.Text = "确 定"; this.btnConfirm.UseVisualStyleBackColor = true; // // btnCancel // this.btnCancel.Location = new System.Drawing.Point(292, 154); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 23); this.btnCancel.TabIndex = 29; this.btnCancel.Text = "取 消"; this.btnCancel.UseVisualStyleBackColor = true; // // frm_OutputPictureMap // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(373, 181); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnConfirm); this.Controls.Add(this.groupBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frm_OutputPictureMap"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "图片格式导出地图"; ((System.ComponentModel.ISupportInitialize)(this.txtWidth)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtHeight)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.NumericUpDown txtWidth; private System.Windows.Forms.Label label8; private System.Windows.Forms.NumericUpDown txtHeight; private System.Windows.Forms.Label label7; private TileMapEditor.Controls.ControlsEx.PromptTextBox txtOutputPath; private System.Windows.Forms.Button btnBrowse; private System.Windows.Forms.Label label4; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.ComboBox cbbFormat; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnConfirm; private System.Windows.Forms.Button btnCancel; } }
43.847909
156
0.563129
[ "MIT" ]
alistuff/Hweny.2DTileMapEditor
2DTileMapEditor/TileMapEditor/Forms/frm_OutputPictureMap.Designer.cs
11,634
C#
using System; using System.Linq; using UnityEditor.Tilemaps; using UnityEngine; using UnityEngine.Tilemaps; using Object = UnityEngine.Object; namespace UnityEditor { [CustomGridBrush(true, false, false, "GameObject Brush")] public class GameObjectBrush : GridBrushBase { [SerializeField] [HideInInspector] private BrushCell[] m_Cells; [SerializeField] [HideInInspector] private Vector3Int m_Size; [SerializeField] [HideInInspector] private Vector3Int m_Pivot; public Vector3Int size { get { return m_Size; } set { m_Size = value; SizeUpdated(); } } public Vector3Int pivot { get { return m_Pivot; } set { m_Pivot = value; } } public BrushCell[] cells { get { return m_Cells; } } public int cellCount { get { return m_Cells != null ? m_Cells.Length : 0; } } public GameObjectBrush() { Init(Vector3Int.one, Vector3Int.zero); SizeUpdated(); } public void Init(Vector3Int size) { Init(size, Vector3Int.zero); SizeUpdated(); } public void Init(Vector3Int size, Vector3Int pivot) { m_Size = size; m_Pivot = pivot; SizeUpdated(); } public override void Paint(GridLayout gridLayout, GameObject brushTarget, Vector3Int position) { // Do not allow editing palettes if (brushTarget.layer == 31) return; Vector3Int min = position - pivot; BoundsInt bounds = new BoundsInt(min, m_Size); BoxFill(gridLayout, brushTarget, bounds); } private void PaintCell(GridLayout grid, Vector3Int position, Transform parent, BrushCell cell) { if (cell.gameObject != null) { SetSceneCell(grid, parent, position, cell.gameObject, cell.offset, cell.scale, cell.orientation); } } public override void Erase(GridLayout gridLayout, GameObject brushTarget, Vector3Int position) { // Do not allow editing palettes if (brushTarget.layer == 31) return; Vector3Int min = position - pivot; BoundsInt bounds = new BoundsInt(min, m_Size); BoxErase(gridLayout, brushTarget, bounds); } private void EraseCell(GridLayout grid, Vector3Int position, Transform parent) { ClearSceneCell(grid, parent, position); } public override void BoxFill(GridLayout gridLayout, GameObject brushTarget, BoundsInt position) { // Do not allow editing palettes if (brushTarget.layer == 31) return; if (brushTarget == null) return; foreach (Vector3Int location in position.allPositionsWithin) { Vector3Int local = location - position.min; BrushCell cell = m_Cells[GetCellIndexWrapAround(local.x, local.y, local.z)]; PaintCell(gridLayout, location, brushTarget.transform, cell); } } public override void BoxErase(GridLayout gridLayout, GameObject brushTarget, BoundsInt position) { // Do not allow editing palettes if (brushTarget.layer == 31) return; if (brushTarget == null) return; foreach (Vector3Int location in position.allPositionsWithin) { EraseCell(gridLayout, location, brushTarget.transform); } } public override void FloodFill(GridLayout gridLayout, GameObject brushTarget, Vector3Int position) { Debug.LogWarning("FloodFill not supported"); } public override void Rotate(RotationDirection direction, Grid.CellLayout layout) { Vector3Int oldSize = m_Size; BrushCell[] oldCells = m_Cells.Clone() as BrushCell[]; size = new Vector3Int(oldSize.y, oldSize.x, oldSize.z); BoundsInt oldBounds = new BoundsInt(Vector3Int.zero, oldSize); foreach (Vector3Int oldPos in oldBounds.allPositionsWithin) { int newX = direction == RotationDirection.Clockwise ? oldSize.y - oldPos.y - 1 : oldPos.y; int newY = direction == RotationDirection.Clockwise ? oldPos.x : oldSize.x - oldPos.x - 1; int toIndex = GetCellIndex(newX, newY, oldPos.z); int fromIndex = GetCellIndex(oldPos.x, oldPos.y, oldPos.z, oldSize.x, oldSize.y, oldSize.z); m_Cells[toIndex] = oldCells[fromIndex]; } int newPivotX = direction == RotationDirection.Clockwise ? oldSize.y - pivot.y - 1 : pivot.y; int newPivotY = direction == RotationDirection.Clockwise ? pivot.x : oldSize.x - pivot.x - 1; pivot = new Vector3Int(newPivotX, newPivotY, pivot.z); Matrix4x4 rotation = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0f, 0f, direction == RotationDirection.Clockwise ? 90f : -90f), Vector3.one); Quaternion orientation = Quaternion.Euler(0f, 0f, direction == RotationDirection.Clockwise ? 90f : -90f); foreach (BrushCell cell in m_Cells) { cell.offset = rotation * cell.offset; cell.orientation = cell.orientation * orientation; } } public override void Flip(FlipAxis flip, Grid.CellLayout layout) { if (flip == FlipAxis.X) FlipX(); else FlipY(); } public override void Pick(GridLayout gridLayout, GameObject brushTarget, BoundsInt position, Vector3Int pickStart) { // Do not allow editing palettes if (brushTarget.layer == 31) return; Reset(); UpdateSizeAndPivot(new Vector3Int(position.size.x, position.size.y, 1), new Vector3Int(pickStart.x, pickStart.y, 0)); foreach (Vector3Int pos in position.allPositionsWithin) { Vector3Int brushPosition = new Vector3Int(pos.x - position.x, pos.y - position.y, 0); PickCell(pos, brushPosition, gridLayout, brushTarget.transform); } } private void PickCell(Vector3Int position, Vector3Int brushPosition, GridLayout grid, Transform parent) { if (parent != null) { Vector3 cellCenter = grid.LocalToWorld(grid.CellToLocalInterpolated(position + new Vector3(.5f, .5f, .5f))); GameObject go = GetObjectInCell(grid, parent, position); if (go != null) { Object prefab = PrefabUtility.GetCorrespondingObjectFromSource(go); if (prefab) { SetGameObject(brushPosition, (GameObject) prefab); } else { GameObject newInstance = Instantiate(go); newInstance.hideFlags = HideFlags.HideAndDontSave; SetGameObject(brushPosition, newInstance); } SetOffset(brushPosition, go.transform.position - cellCenter); SetScale(brushPosition, go.transform.localScale); SetOrientation(brushPosition, go.transform.localRotation); } } } public override void MoveStart(GridLayout gridLayout, GameObject brushTarget, BoundsInt position) { // Do not allow editing palettes if (brushTarget.layer == 31) return; Reset(); UpdateSizeAndPivot(new Vector3Int(position.size.x, position.size.y, 1), Vector3Int.zero); if (brushTarget != null) { foreach (Vector3Int pos in position.allPositionsWithin) { Vector3Int brushPosition = new Vector3Int(pos.x - position.x, pos.y - position.y, 0); PickCell(pos, brushPosition, gridLayout, brushTarget.transform); ClearSceneCell(gridLayout, brushTarget.transform, brushPosition); } } } public override void MoveEnd(GridLayout gridLayout, GameObject brushTarget, BoundsInt position) { // Do not allow editing palettes if (brushTarget.layer == 31) return; Paint(gridLayout, brushTarget, position.min); Reset(); } public void Reset() { foreach (var cell in m_Cells) { if (cell.gameObject != null && !EditorUtility.IsPersistent(cell.gameObject)) { DestroyImmediate(cell.gameObject); } } UpdateSizeAndPivot(Vector3Int.one, Vector3Int.zero); } private void FlipX() { BrushCell[] oldCells = m_Cells.Clone() as BrushCell[]; BoundsInt oldBounds = new BoundsInt(Vector3Int.zero, m_Size); foreach (Vector3Int oldPos in oldBounds.allPositionsWithin) { int newX = m_Size.x - oldPos.x - 1; int toIndex = GetCellIndex(newX, oldPos.y, oldPos.z); int fromIndex = GetCellIndex(oldPos); m_Cells[toIndex] = oldCells[fromIndex]; } int newPivotX = m_Size.x - pivot.x - 1; pivot = new Vector3Int(newPivotX, pivot.y, pivot.z); Matrix4x4 flip = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(-1f, 1f, 1f)); Quaternion orientation = Quaternion.Euler(0f, 0f, -180f); foreach (BrushCell cell in m_Cells) { Vector3 oldOffset = cell.offset; cell.offset = flip * oldOffset; cell.orientation = cell.orientation*orientation; } } private void FlipY() { BrushCell[] oldCells = m_Cells.Clone() as BrushCell[]; BoundsInt oldBounds = new BoundsInt(Vector3Int.zero, m_Size); foreach (Vector3Int oldPos in oldBounds.allPositionsWithin) { int newY = m_Size.y - oldPos.y - 1; int toIndex = GetCellIndex(oldPos.x, newY, oldPos.z); int fromIndex = GetCellIndex(oldPos); m_Cells[toIndex] = oldCells[fromIndex]; } int newPivotY = m_Size.y - pivot.y - 1; pivot = new Vector3Int(pivot.x, newPivotY, pivot.z); Matrix4x4 flip = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1f, -1f, 1f)); Quaternion orientation = Quaternion.Euler(0f, 0f, -180f); foreach (BrushCell cell in m_Cells) { Vector3 oldOffset = cell.offset; cell.offset = flip * oldOffset; cell.orientation = cell.orientation * orientation; } } public void UpdateSizeAndPivot(Vector3Int size, Vector3Int pivot) { m_Size = size; m_Pivot = pivot; SizeUpdated(); } public void SetGameObject(Vector3Int position, GameObject go) { if (ValidateCellPosition(position)) m_Cells[GetCellIndex(position)].gameObject = go; } public void SetOffset(Vector3Int position, Vector3 offset) { if (ValidateCellPosition(position)) m_Cells[GetCellIndex(position)].offset = offset; } public void SetOrientation(Vector3Int position, Quaternion orientation) { if (ValidateCellPosition(position)) m_Cells[GetCellIndex(position)].orientation = orientation; } public void SetScale(Vector3Int position, Vector3 scale) { if (ValidateCellPosition(position)) m_Cells[GetCellIndex(position)].scale = scale; } public int GetCellIndex(Vector3Int brushPosition) { return GetCellIndex(brushPosition.x, brushPosition.y, brushPosition.z); } public int GetCellIndex(int x, int y, int z) { return x + m_Size.x * y + m_Size.x * m_Size.y * z; } public int GetCellIndex(int x, int y, int z, int sizex, int sizey, int sizez) { return x + sizex * y + sizex * sizey * z; } public int GetCellIndexWrapAround(int x, int y, int z) { return (x % m_Size.x) + m_Size.x * (y % m_Size.y) + m_Size.x * m_Size.y * (z % m_Size.z); } private static GameObject GetObjectInCell(GridLayout grid, Transform parent, Vector3Int position) { int childCount = parent.childCount; Vector3 min = grid.LocalToWorld(grid.CellToLocalInterpolated(position)); Vector3 max = grid.LocalToWorld(grid.CellToLocalInterpolated(position + Vector3Int.one)); // Infinite bounds on Z for 2D convenience min = new Vector3(min.x, min.y, float.MinValue); max = new Vector3(max.x, max.y, float.MaxValue); Bounds bounds = new Bounds((max + min) * .5f, max - min); for (int i = 0; i < childCount; i++) { Transform child = parent.GetChild(i); if (bounds.Contains(child.position)) return child.gameObject; } return null; } private bool ValidateCellPosition(Vector3Int position) { var valid = position.x >= 0 && position.x < size.x && position.y >= 0 && position.y < size.y && position.z >= 0 && position.z < size.z; if (!valid) throw new ArgumentException(string.Format("Position {0} is an invalid cell position. Valid range is between [{1}, {2}).", position, Vector3Int.zero, size)); return valid; } private void SizeUpdated() { m_Cells = new BrushCell[m_Size.x * m_Size.y * m_Size.z]; BoundsInt bounds = new BoundsInt(Vector3Int.zero, m_Size); foreach (Vector3Int pos in bounds.allPositionsWithin) { m_Cells[GetCellIndex(pos)] = new BrushCell(); } } private static void SetSceneCell(GridLayout grid, Transform parent, Vector3Int position, GameObject go, Vector3 offset, Vector3 scale, Quaternion orientation) { if (parent == null || go == null) return; GameObject instance = null; if (PrefabUtility.IsPartOfPrefabAsset(go)) { instance = (GameObject) PrefabUtility.InstantiatePrefab(go); } else { instance = Instantiate(go); instance.hideFlags = HideFlags.None; instance.name = go.name; } Undo.RegisterCreatedObjectUndo(instance, "Paint GameObject"); instance.transform.SetParent(parent); instance.transform.position = grid.LocalToWorld(grid.CellToLocalInterpolated(new Vector3Int(position.x, position.y, position.z) + new Vector3(.5f, .5f, .5f))); instance.transform.localRotation = orientation; instance.transform.localScale = scale; instance.transform.Translate(offset); } private static void ClearSceneCell(GridLayout grid, Transform parent, Vector3Int position) { if (parent == null) return; GameObject erased = GetObjectInCell(grid, parent, new Vector3Int(position.x, position.y, position.z)); if (erased != null) Undo.DestroyObjectImmediate(erased); } public override int GetHashCode() { int hash = 0; unchecked { foreach (var cell in cells) { hash = hash * 33 + cell.GetHashCode(); } } return hash; } [Serializable] public class BrushCell { public GameObject gameObject { get { return m_GameObject; } set { m_GameObject = value; } } public Vector3 offset { get { return m_Offset; } set { m_Offset = value; } } public Vector3 scale { get { return m_Scale; } set { m_Scale = value; } } public Quaternion orientation { get { return m_Orientation; } set { m_Orientation = value; } } [SerializeField] private GameObject m_GameObject; [SerializeField] Vector3 m_Offset = Vector3.zero; [SerializeField] Vector3 m_Scale = Vector3.one; [SerializeField] Quaternion m_Orientation = Quaternion.identity; public override int GetHashCode() { int hash = 0; unchecked { hash = gameObject != null ? gameObject.GetInstanceID() : 0; hash = hash * 33 + m_Offset.GetHashCode(); hash = hash * 33 + m_Scale.GetHashCode(); hash = hash * 33 + m_Orientation.GetHashCode(); } return hash; } } } [CustomEditor(typeof(GameObjectBrush))] public class GameObjectBrushEditor : GridBrushEditorBase { public GameObjectBrush brush { get { return target as GameObjectBrush; } } public override void OnPaintSceneGUI(GridLayout gridLayout, GameObject brushTarget, BoundsInt position, GridBrushBase.Tool tool, bool executing) { BoundsInt gizmoRect = position; if (tool == GridBrushBase.Tool.Paint || tool == GridBrushBase.Tool.Erase) gizmoRect = new BoundsInt(position.min - brush.pivot, brush.size); base.OnPaintSceneGUI(gridLayout, brushTarget, gizmoRect, tool, executing); } public override void OnPaintInspectorGUI() { GUILayout.Label("Pick, paint and erase GameObject(s) in the scene."); GUILayout.Label("Limited to children of the currently selected GameObject."); } } }
37.85336
172
0.560583
[ "MIT" ]
AntonioPGR/Untitled-Game
Rpg creator/Assets/Creator Kit - RPG/Scripts/Tiles/Brushes/GameObject Brush/Scripts/Editor/GameObjectBrush.cs
18,586
C#
using Newtonsoft.Json; namespace Microsoft.ProjectOxford.Text.Language { /// <summary> /// Language detected by the Text Analytics API. /// </summary> public class DetectedLanguage { #region Properties /// <summary> /// Gets or sets the name of the language. /// </summary> /// <value> /// The name of the lanuage. /// </value> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// Gets or sets ISO 639-1 name of the language. /// </summary> /// <value> /// The ISO 639-1 name of the language. /// </value> [JsonProperty("iso6391Name")] public string Iso639Name { get; set; } /// <summary> /// Gets or sets the confidence score of the identified language. /// </summary> /// <value> /// The confidence score of the identified language.. /// </value> [JsonProperty("score")] public float Score { get; set; } #endregion Properties } }
22.425926
73
0.476466
[ "MIT" ]
MangoPieface/CognitiveAbstractSearch
ClientLibrary/Microsoft.ProjectOxford.Text/Languages/DetectedLanguage.cs
1,213
C#
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; /// <summary> /// Convert object-value into specified type /// </summary> public interface IPropertyTypeConverter { /// <summary> /// Parses the input value and converts into the wanted type /// </summary> /// <param name="propertyValue">Input Value</param> /// <param name="propertyType">Wanted Type</param> /// <param name="format">Format to use when parsing</param> /// <param name="formatProvider">Culture to use when parsing</param> /// <returns>Output value with wanted type</returns> object Convert(object propertyValue, Type propertyType, string format, IFormatProvider formatProvider); } }
44.518519
111
0.72005
[ "BSD-3-Clause" ]
AlanLiu90/NLog
src/NLog/Config/IPropertyTypeConverter.cs
2,404
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace QUIZ.Coding { public partial class thankyou { /// <summary> /// form1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// Label1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label Label1; } }
32.264706
85
0.465816
[ "MIT" ]
Sachinmanoj/QUIZ-application
QUIZ/Coding/thankyou.aspx.designer.cs
1,099
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Linq; using System.Threading.Tasks; namespace GameManagerFileSystem { public class FileGameDatabase : FileGameDatabase { public FileGameDatabase(string filename) { if (filename == null) throw new ArgumentNullException(nameof(filename)); if (filename == "") throw new ArgumentException("Filename cannot be empty.", nameof(filename)); _filename = filename; } private readonly string _filename; protected override IEnumerable<Game> GetAllCore() { if (File.Exists(_filename)) { //Read all at once foreach (var line in File.ReadAllLines(_filename)) { var game = LoadGame(line); if (game != null) yield return game; }; }; } private Game LoadGame(string line ) { if (string.IsNullOrEmpty(line)) return null; var fields = line.Split(','); if (fields.Length != 3) return null; return new Game { Id = Int32.Parse(fields[0]), Name = fields[1], Description = fields[2], }; } private string SaveGame(Game game ) { return String.Join(",", game.Id, game.Name, game.description); } private void SaveGames(IEnumerable<Game> game ) { //Use LINQ luke var lines = from game in SaveGames select SaveGame(game); } protected override Game AddCore(Game game ) { var games = GetAllCore().ToList(); //Find the largest Id and increment by 1 if (games.Any()) game.Id = games.Max(x => x.Id) + 1; else game.Id = 1; //Add to list games.Add(game); // save the games SaveGames(games); return game; } protected override Game GetCore(int id) { if (!File.Exists(_filename)) return null; //Strems are very low level //var stream = File.Open; //Use a reder/writer var reader = File.OpenText(_filename); StreamReader readerAnother = File.OpenText(_filename); // same as previous line but in this one we use Streamreader while (!reader.EndOfStream) { var line = reader.ReadLine(); var game = LoadGame(line); if (game.Id == id) return game; }; reader.Close(); return null; } protected override void Deletecore(int id) { var games = GetAllCore().ToList(); var game = games.FirstOrDefault(x => x.Id == id); if(game != null) { games.Remove(game); SaveGames(game); } } protected override void Updatecore( int id ) { var games = GetAllCore().ToList(); //Replace old game with new one var existing = games.FirstOrDefault(x => x.Id == id); if(existing != null) { games.Remove(existing); newGame.Id = id; games.Add(newGame); SaveGame(games); }; return newGame; } } } /* April 3, 2019 - Files, using statement * File is static class you do not create instcances * file is on System.IO * with file there are Directory and Path * Path = "C:\temp\test.txt"; * Path; * GetDirectoryName(path) it gives a string -- C:\Temp * GetFileName(path) gives a string -- test.txt * GetExtension(path->String -- .txt * GetFileNameWithoutextension(path)->string -- .test * * File; * Exists(path) -> bool * file read and write are HIGH LEVEL * if you want to read a file- ReadAllLines(str)-> String[] for text file * - ReadText(str)->string( whole document in new line as a string) for text file * - ReadAllBytes(str)->byte[] for binary file * if you want to write a file- WriteAllLines(str, String[]) * - WriteText(str,str) * - WriteAllBytes(str,Bytes[]) * if you want to open a file - Open(str,...)->stream * - OpenText(str)-> streamReader * stream is series of byte( stream of byte) * stream and streamReader are work with text file * streams are VERY VERY LOW LEVEL objects so they are very easy to mess them up * streams - File - stream reader/writer, network - binary stream reader/writer, IPC, Memory * streams has to be close when you are done with i. there is .Close() method * * using statement requires an expression; using(expr){statements;} =(equivilant to) try{}finally{Close()} * using statement is designed for cleanup */ /*April 8, 2019 - IDisposable, ADO.NET, Connection, Command * IDisposable interface only one method has void Dispose(); * this does not have close() method * reader.Close() - NEVER DO THIS * close() method is simply this - close(){Dispose()}. so you do not need to use Close() method in dispose(); * if you do not know this, do not use. because it easily can get trouble * *DataBase * Table - columns represent what and rows represent data * in .NET world table is like Type, columns is like porperties, rows is like instances * Products - Id - int, Name - text, Price - money * in .NET Product - Id, Name, Price * ADO.NET stands for Active Data Objects .NET * * SQL deploy when F5 clicks output gets a one successful * DB connection is a generic connection and it is sql connection and it is IDisposable * DB command is another sqlCommand and it is also IDisposable * To execute command. there are several methods - Execunuqueery() - this is does not care about the result * and executeScaler() execute and return back one value * * * Example; * Create a cannection to "MyDB" * var cs = ConfigurationManager.Conn str["MyDB"]; * using var conn = new SqlConnection(cs.ConnectionString); * * Create a cmd(command) to call proc "GetEmployee" * var cmd = conn.CreateCommand(); * cmd.CommandText = "GetEmployee"; * cmd.CommandType = CommandType.StoredProcedur; * * Add param Id with value 10 * cmd.Parameters.AddWithValue("@id",10); */
32.887255
127
0.563869
[ "MIT" ]
vibhavicharm/itse1430
Classwork/GameManager.Host.Winforms/GameManagerFileSystem/FileGameDatabase.cs
6,711
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BinF6")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BinF6")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("334c48bb-72c5-4bf0-b641-5c88f94f13b0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.378378
84
0.742589
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
naomijub/BinaryF6
BinF6/Properties/AssemblyInfo.cs
1,386
C#
using System.Collections.Generic; using System.Linq; using GW2EIEvtcParser.EIData; using GW2EIEvtcParser.EncounterLogic; using GW2EIEvtcParser.Exceptions; using GW2EIEvtcParser.Extensions; using GW2EIEvtcParser.ParsedData; namespace GW2EIEvtcParser { public class ParsedEvtcLog { public LogData LogData { get; } public FightData FightData { get; } public AgentData AgentData { get; } public SkillData SkillData { get; } public CombatData CombatData { get; } public IReadOnlyList<Player> PlayerList { get; } public IReadOnlyList<AbstractSingleActor> Friendlies { get; } public IReadOnlyCollection<AgentItem> PlayerAgents { get; } public IReadOnlyCollection<AgentItem> FriendlyAgents { get; } public bool IsBenchmarkMode => FightData.Logic.Mode == FightLogic.ParseMode.Benchmark; public IReadOnlyDictionary<ParserHelper.Spec, List<AbstractSingleActor>> FriendliesListBySpec { get; } public DamageModifiersContainer DamageModifiers { get; } public BuffsContainer Buffs { get; } public EvtcParserSettings ParserSettings { get; } public bool CanCombatReplay => ParserSettings.ParseCombatReplay && CombatData.HasMovementData; public MechanicData MechanicData { get; } public StatisticsHelper StatisticsHelper { get; } private readonly ParserController _operation; private Dictionary<AgentItem, AbstractSingleActor> _agentToActorDictionary; internal ParsedEvtcLog(int evtcVersion, FightData fightData, AgentData agentData, SkillData skillData, List<CombatItem> combatItems, List<Player> playerList, IReadOnlyDictionary<uint, AbstractExtensionHandler> extensions, long evtcLogDuration, EvtcParserSettings parserSettings, ParserController operation) { FightData = fightData; AgentData = agentData; SkillData = skillData; PlayerList = playerList; ParserSettings = parserSettings; _operation = operation; // _operation.UpdateProgressWithCancellationCheck("Creating GW2EI Combat Events"); CombatData = new CombatData(combatItems, FightData, AgentData, SkillData, PlayerList, operation, extensions, evtcVersion); // operation.UpdateProgressWithCancellationCheck("Checking CM"); FightData.SetCM(CombatData, AgentData); operation.UpdateProgressWithCancellationCheck("Setting Fight Name"); FightData.SetFightName(CombatData, AgentData); // var friendlies = new List<AbstractSingleActor>(); friendlies.AddRange(PlayerList); friendlies.AddRange(fightData.Logic.NonPlayerFriendlies); Friendlies = friendlies; FriendliesListBySpec = friendlies.GroupBy(x => x.Spec).ToDictionary(x => x.Key, x => x.ToList()); PlayerAgents = new HashSet<AgentItem>(PlayerList.Select(x => x.AgentItem)); FriendlyAgents = new HashSet<AgentItem>(Friendlies.Select(x => x.AgentItem)); // _operation.UpdateProgressWithCancellationCheck("Checking Success"); FightData.Logic.CheckSuccess(CombatData, AgentData, FightData, PlayerAgents); if (FightData.FightDuration <= ParserSettings.TooShortLimit) { throw new TooShortException(FightData.FightDuration, ParserSettings.TooShortLimit); } if (ParserSettings.SkipFailedTries && !FightData.Success) { throw new SkipException(); } _operation.UpdateProgressWithCancellationCheck("Creating GW2EI Log Meta Data"); LogData = new LogData(evtcVersion, CombatData, evtcLogDuration, playerList, extensions, operation); // _operation.UpdateProgressWithCancellationCheck("Creating Buff Container"); Buffs = new BuffsContainer(LogData.GW2Build, CombatData, operation); _operation.UpdateProgressWithCancellationCheck("Creating Damage Modifier Container"); DamageModifiers = new DamageModifiersContainer(LogData.GW2Build, fightData.Logic.Mode, parserSettings); _operation.UpdateProgressWithCancellationCheck("Creating Mechanic Data"); MechanicData = FightData.Logic.GetMechanicData(); _operation.UpdateProgressWithCancellationCheck("Creating General Statistics Container"); StatisticsHelper = new StatisticsHelper(CombatData, PlayerList, Buffs); } public void UpdateProgressWithCancellationCheck(string status) { _operation.UpdateProgressWithCancellationCheck(status); } private void AddToDictionary(AbstractSingleActor actor) { _agentToActorDictionary[actor.AgentItem] = actor; /*foreach (Minions minions in actor.GetMinions(this).Values) { foreach (NPC npc in minions.MinionList) { AddToDictionary(npc); } }*/ } private void InitActorDictionaries() { if (_agentToActorDictionary == null) { _operation.UpdateProgressWithCancellationCheck("Initializing Actor dictionary"); _agentToActorDictionary = new Dictionary<AgentItem, AbstractSingleActor>(); foreach (AbstractSingleActor p in Friendlies) { AddToDictionary(p); } foreach (AbstractSingleActor npc in FightData.Logic.Targets) { AddToDictionary(npc); } foreach (NPC npc in FightData.Logic.TrashMobs) { AddToDictionary(npc); } } } /// <summary> /// Find the corresponding actor, creates one otherwise /// </summary> /// <param name="agentItem"><see cref="AgentItem"/> to find an <see cref="AbstractSingleActor"/> for</param> /// <param name="excludePlayers">returns null if true and agentItem is a player or has a player master</param> /// <returns></returns> public AbstractSingleActor FindActor(AgentItem agentItem, bool excludePlayers = false) { if (agentItem == null || (excludePlayers && agentItem.GetFinalMaster().Type == AgentItem.AgentType.Player)) { return null; } InitActorDictionaries(); if (!_agentToActorDictionary.TryGetValue(agentItem, out AbstractSingleActor actor)) { if (agentItem.Type == AgentItem.AgentType.Player) { actor = new Player(agentItem, true); _operation.UpdateProgressWithCancellationCheck("Found player " + actor.Character + " not in player list"); } else if (agentItem.Type == AgentItem.AgentType.NonSquadPlayer) { actor = new PlayerNonSquad(agentItem); } else { actor = new NPC(agentItem); } _agentToActorDictionary[agentItem] = actor; //throw new EIException("Requested actor with id " + a.ID + " and name " + a.Name + " is missing"); } return actor; } } }
47.138365
219
0.628286
[ "MIT" ]
Zerthox/GW2-Elite-Insights-Parser
GW2EIEvtcParser/ParsedEvtcLog.cs
7,497
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Conventions; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore { internal static class HttpContextDatabaseContextDetailsExtensions { public static async ValueTask<DatabaseContextDetails?> GetContextDetailsAsync( this HttpContext httpContext, Type dbcontextType, ILogger logger ) { var context = (DbContext?)httpContext.RequestServices.GetService(dbcontextType); if (context == null) { logger.ContextNotRegisteredDatabaseErrorPageMiddleware(dbcontextType.FullName!); return null; } var relationalDatabaseCreator = context.GetService<IDatabaseCreator>() as IRelationalDatabaseCreator; if (relationalDatabaseCreator == null) { logger.NotRelationalDatabase(); return null; } var databaseExists = await relationalDatabaseCreator.ExistsAsync(); if (databaseExists) { databaseExists = await relationalDatabaseCreator.HasTablesAsync(); } var migrationsAssembly = context.GetService<IMigrationsAssembly>(); var modelDiffer = context.GetService<IMigrationsModelDiffer>(); var snapshotModel = migrationsAssembly.ModelSnapshot?.Model; if (snapshotModel is IMutableModel mutableModel) { snapshotModel = mutableModel.FinalizeModel(); } if (snapshotModel != null) { snapshotModel = context .GetService<IModelRuntimeInitializer>() .Initialize(snapshotModel, validationLogger: null); } // HasDifferences will return true if there is no model snapshot, but if there is an existing database // and no model snapshot then we don't want to show the error page since they are most likely targeting // and existing database and have just misconfigured their model return new DatabaseContextDetails( type: dbcontextType, databaseExists: databaseExists, pendingModelChanges: (!databaseExists || migrationsAssembly.ModelSnapshot != null) && modelDiffer.HasDifferences( snapshotModel?.GetRelationalModel(), context.Model.GetRelationalModel() ), pendingMigrations: databaseExists ? await context.Database.GetPendingMigrationsAsync() : context.Database.GetMigrations() ); } } }
39.252874
115
0.647438
[ "Apache-2.0" ]
belav/aspnetcore
src/Middleware/Diagnostics.EntityFrameworkCore/src/HttpContextDatabaseContextDetailsExtensions.cs
3,415
C#
using FinanceDataMigrationApi.V1.Boundary.Response; using System.Threading.Tasks; namespace FinanceDataMigrationApi.V1.UseCase.Interfaces.Accounts { public interface IExtractAccountEntityUseCase { public Task<StepResponse> ExecuteAsync(); } }
24
64
0.784091
[ "MIT" ]
LBHackney-IT/finance-data-migration
FinanceDataMigrationApi/V1/UseCase/Interfaces/Accounts/IExtractAccountEntityUseCase.cs
264
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/ShObjIdl_core.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="IKnownFolder" /> struct.</summary> public static unsafe partial class IKnownFolderTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="IKnownFolder" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(IKnownFolder).GUID, Is.EqualTo(IID_IKnownFolder)); } /// <summary>Validates that the <see cref="IKnownFolder" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<IKnownFolder>(), Is.EqualTo(sizeof(IKnownFolder))); } /// <summary>Validates that the <see cref="IKnownFolder" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(IKnownFolder).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="IKnownFolder" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(IKnownFolder), Is.EqualTo(8)); } else { Assert.That(sizeof(IKnownFolder), Is.EqualTo(4)); } } }
34.27451
145
0.679634
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/Windows/um/ShObjIdl_core/IKnownFolderTests.cs
1,750
C#
using UnityEngine.UIElements; namespace Unity.WebRTC.Editor { public class OutboundRTPStreamGraphView { private GraphView firCountGraph = new GraphView("firCount"); private GraphView pliCountGraph = new GraphView("pliCount"); private GraphView nackCountGraph = new GraphView("nackCount"); private GraphView sliCountGraph = new GraphView("sliCount"); private GraphView qpSumGraph = new GraphView("qpSum"); private GraphView packetsSentGraph = new GraphView("packetsSent"); private GraphView retransmittedPacketsSentGraph = new GraphView("retransmittedPacketsSent"); private GraphView bytesSentGraph = new GraphView("bytesSent"); private GraphView headerBytesSentGraph = new GraphView("headerBytesSent"); private GraphView retransmittedBytesSentGraph = new GraphView("retransmittedBytesSent"); private GraphView framesDecodedGraph = new GraphView("framesDecoded"); private GraphView keyFramesDecodedGraph = new GraphView("keyFramesDecoded"); private GraphView targetBitrateGraph = new GraphView("targetBitrate"); private GraphView totalEncodeTimeGraph = new GraphView("totalEncodeTime"); private GraphView totalEncodedBytesTargetGraph = new GraphView("totalEncodedBytesTarget"); private GraphView totalPacketSendDelayGraph = new GraphView("totalPacketSendDelay"); public void AddInput(RTCOutboundRTPStreamStats input) { var timestamp = input.UtcTimeStamp; firCountGraph.AddInput(timestamp, input.firCount); pliCountGraph.AddInput(timestamp, input.pliCount); nackCountGraph.AddInput(timestamp, input.nackCount); sliCountGraph.AddInput(timestamp, input.sliCount); qpSumGraph.AddInput(timestamp, input.qpSum); packetsSentGraph.AddInput(timestamp, input.packetsSent); retransmittedPacketsSentGraph.AddInput(timestamp, input.retransmittedPacketsSent); bytesSentGraph.AddInput(timestamp, input.bytesSent); headerBytesSentGraph.AddInput(timestamp, input.headerBytesSent); retransmittedBytesSentGraph.AddInput(timestamp, input.retransmittedBytesSent); targetBitrateGraph.AddInput(timestamp, (float)input.targetBitrate); framesDecodedGraph.AddInput(timestamp, input.framesEncoded); keyFramesDecodedGraph.AddInput(timestamp, input.keyFramesEncoded); totalEncodeTimeGraph.AddInput(timestamp, (float)input.totalEncodeTime); totalEncodedBytesTargetGraph.AddInput(timestamp, input.totalEncodedBytesTarget); totalPacketSendDelayGraph.AddInput(timestamp, (float)input.totalPacketSendDelay); } public VisualElement Create() { var container = new VisualElement(); container.Add(firCountGraph.Create()); container.Add(pliCountGraph.Create()); container.Add(nackCountGraph.Create()); container.Add(sliCountGraph.Create()); container.Add(qpSumGraph.Create()); container.Add(packetsSentGraph.Create()); container.Add(retransmittedPacketsSentGraph.Create()); container.Add(bytesSentGraph.Create()); container.Add(headerBytesSentGraph.Create()); container.Add(retransmittedBytesSentGraph.Create()); container.Add(framesDecodedGraph.Create()); container.Add(keyFramesDecodedGraph.Create()); container.Add(targetBitrateGraph.Create()); container.Add(totalEncodeTimeGraph.Create()); container.Add(totalEncodedBytesTargetGraph.Create()); container.Add(totalPacketSendDelayGraph.Create()); return container; } } }
55.808824
100
0.704084
[ "MIT" ]
JesusGarciaValadez/RenderStreamingHDRP
RenderStreamingHDRP/Library/PackageCache/com.unity.webrtc@2.2.1-preview/Editor/OutboundRTPStreamGraphView.cs
3,797
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the mwaa-2020-07-01.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.MWAA { /// <summary> /// Configuration for accessing Amazon MWAA service /// </summary> public partial class AmazonMWAAConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.7.1.81"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonMWAAConfig() { this.AuthenticationServiceName = "airflow"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "airflow"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2020-07-01"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
25.7
102
0.581226
[ "Apache-2.0" ]
jamieromanowski/aws-sdk-net
sdk/src/Services/MWAA/Generated/AmazonMWAAConfig.cs
2,056
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Myrtille.MFAProviders")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Myrtille")] [assembly: AssemblyCopyright("Copyright © Olive Innovations Ltd 2017-2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3573c84d-5fd3-4bac-bf96-20b9fd0709ff")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.5.5.0")] [assembly: AssemblyFileVersion("2.5.5.0")]
38.594595
84
0.747899
[ "Apache-2.0" ]
rasata/myrtille
Myrtille.MFAProviders/Properties/AssemblyInfo.cs
1,431
C#
using System.Collections.Generic; using UnityEngine; using Phenix.Unity.AI; public class GOAPActionOrderMove : GOAPActionBase { AnimFSMEventMove _eventMove; public GOAPActionOrderMove(GOAPActionType1 actionType, Agent1 agent, List<WorldStateBitData> WSPrecondition, List<WorldStateBitDataAction> WSEffect) : base((int)actionType, agent, WSPrecondition, WSEffect) { } public override void Reset() { base.Reset(); _eventMove = null; } public override void OnEnter() { OrderData curOrder = Agent.PlayerOrder.GetCurOrder(); SendEvent((curOrder as OrderDataMove).dir.normalized); } public override void OnUpdate() { if (_eventMove.IsFinished) { return; } OrderData nextOrder = Agent.PlayerOrder.GetNextOrder(); if (nextOrder != null && nextOrder.orderType == (int)OrderType.MOVE) { PlayerOrderPool.moves.Collect(Agent.PlayerOrder.Pop() as OrderDataMove); if (_eventMove != null) { _eventMove.Release(); } SendEvent((nextOrder as OrderDataMove).dir.normalized); } else { _eventMove.IsFinished = true; } } public override void OnExit(Phenix.Unity.AI.WorldState ws) { if (_eventMove != null) { _eventMove.Release(); _eventMove = null; } base.OnExit(ws); } public override bool IsFinished() { return _eventMove != null && _eventMove.IsFinished; } void SendEvent(Vector3 dir) { _eventMove = AnimFSMEventMove.pool.Get(); _eventMove.moveDir = dir; Agent.FSMComponent.SendEvent(_eventMove); } }
25.109589
87
0.585379
[ "MIT" ]
mengtest/samurai
samurai/Assets/Scripts/GOAP1/Actions/GOAPActionOrderMove.cs
1,835
C#
using System.Collections.Generic; using System.Linq; using Content.Server.Chemistry.Components; using Content.Server.Chemistry.Components.SolutionManager; using Content.Server.Chemistry.EntitySystems; using Content.Server.Tools.Components; using Content.Server.Weapon.Melee; using Content.Shared.Audio; using Content.Shared.Examine; using Content.Shared.FixedPoint; using Content.Shared.Interaction; using Content.Shared.Item; using Content.Shared.Popups; using Content.Shared.Temperature; using Content.Shared.Tools.Components; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.GameStates; using Robust.Shared.Localization; using Robust.Shared.Player; namespace Content.Server.Tools { public partial class ToolSystem { private readonly HashSet<EntityUid> _activeWelders = new(); private const float WelderUpdateTimer = 1f; private float _welderTimer = 0f; public void InitializeWelders() { SubscribeLocalEvent<WelderComponent, ComponentStartup>(OnWelderStartup); SubscribeLocalEvent<WelderComponent, IsHotEvent>(OnWelderIsHotEvent); SubscribeLocalEvent<WelderComponent, ExaminedEvent>(OnWelderExamine); SubscribeLocalEvent<WelderComponent, SolutionChangedEvent>(OnWelderSolutionChange); SubscribeLocalEvent<WelderComponent, ActivateInWorldEvent>(OnWelderActivate); SubscribeLocalEvent<WelderComponent, AfterInteractEvent>(OnWelderAfterInteract); SubscribeLocalEvent<WelderComponent, ToolUseAttemptEvent>(OnWelderToolUseAttempt); SubscribeLocalEvent<WelderComponent, ToolUseFinishAttemptEvent>(OnWelderToolUseFinishAttempt); SubscribeLocalEvent<WelderComponent, ComponentShutdown>(OnWelderShutdown); SubscribeLocalEvent<WelderComponent, ComponentGetState>(OnWelderGetState); SubscribeLocalEvent<WelderComponent, MeleeHitEvent>(OnMeleeHit); } private void OnMeleeHit(EntityUid uid, WelderComponent component, MeleeHitEvent args) { if (!args.Handled && component.Lit) args.BonusDamage += component.LitMeleeDamageBonus; } public (FixedPoint2 fuel, FixedPoint2 capacity) GetWelderFuelAndCapacity(EntityUid uid, WelderComponent? welder = null, SolutionContainerManagerComponent? solutionContainer = null) { if (!Resolve(uid, ref welder, ref solutionContainer) || !_solutionContainerSystem.TryGetSolution(uid, welder.FuelSolution, out var fuelSolution, solutionContainer)) return (FixedPoint2.Zero, FixedPoint2.Zero); return (_solutionContainerSystem.GetReagentQuantity(uid, welder.FuelReagent), fuelSolution.MaxVolume); } public bool TryToggleWelder(EntityUid uid, EntityUid? user, WelderComponent? welder = null, SolutionContainerManagerComponent? solutionContainer = null, SharedItemComponent? item = null, PointLightComponent? light = null, SpriteComponent? sprite = null) { // Right now, we only need the welder. // So let's not unnecessarily resolve components if (!Resolve(uid, ref welder)) return false; return !welder.Lit ? TryTurnWelderOn(uid, user, welder, solutionContainer, item, light, sprite) : TryTurnWelderOff(uid, user, welder, item, light, sprite); } public bool TryTurnWelderOn(EntityUid uid, EntityUid? user, WelderComponent? welder = null, SolutionContainerManagerComponent? solutionContainer = null, SharedItemComponent? item = null, PointLightComponent? light = null, SpriteComponent? sprite = null) { if (!Resolve(uid, ref welder, ref solutionContainer)) return false; // Optional components. Resolve(uid, ref item, ref light, ref sprite); if (!_solutionContainerSystem.TryGetSolution(uid, welder.FuelSolution, out var solution, solutionContainer)) return false; var fuel = solution.GetReagentQuantity(welder.FuelReagent); // Not enough fuel to lit welder. if (fuel == FixedPoint2.Zero || fuel < welder.FuelLitCost) { if(user != null) _popupSystem.PopupEntity(Loc.GetString("welder-component-no-fuel-message"), uid, Filter.Entities(user.Value)); return false; } solution.RemoveReagent(welder.FuelReagent, welder.FuelLitCost); welder.Lit = true; if(item != null) item.EquippedPrefix = "on"; sprite?.LayerSetVisible(1, true); if (light != null) light.Enabled = true; SoundSystem.Play(Filter.Pvs(uid), welder.WelderOnSounds.GetSound(), uid, AudioHelpers.WithVariation(0.125f).WithVolume(-5f)); // TODO: Use TransformComponent directly. _atmosphereSystem.HotspotExpose(EntityManager.GetComponent<TransformComponent>(welder.Owner).Coordinates, 700, 50, true); welder.Dirty(); _activeWelders.Add(uid); return true; } public bool TryTurnWelderOff(EntityUid uid, EntityUid? user, WelderComponent? welder = null, SharedItemComponent? item = null, PointLightComponent? light = null, SpriteComponent? sprite = null) { if (!Resolve(uid, ref welder)) return false; // Optional components. Resolve(uid, ref item, ref light, ref sprite); welder.Lit = false; // TODO: Make all this use visualizers. if (item != null) item.EquippedPrefix = "off"; // Layer 1 is the flame. sprite?.LayerSetVisible(1, false); if (light != null) light.Enabled = false; SoundSystem.Play(Filter.Pvs(uid), welder.WelderOffSounds.GetSound(), uid, AudioHelpers.WithVariation(0.125f).WithVolume(-5f)); welder.Dirty(); _activeWelders.Remove(uid); return true; } private void OnWelderStartup(EntityUid uid, WelderComponent component, ComponentStartup args) { component.Dirty(); } private void OnWelderIsHotEvent(EntityUid uid, WelderComponent welder, IsHotEvent args) { args.IsHot = welder.Lit; } private void OnWelderExamine(EntityUid uid, WelderComponent welder, ExaminedEvent args) { if (welder.Lit) { args.PushMarkup(Loc.GetString("welder-component-on-examine-welder-lit-message")); } else { args.PushMarkup(Loc.GetString("welder-component-on-examine-welder-not-lit-message")); } if (args.IsInDetailsRange) { var (fuel, capacity) = GetWelderFuelAndCapacity(uid, welder); args.PushMarkup(Loc.GetString("welder-component-on-examine-detailed-message", ("colorName", fuel < capacity / FixedPoint2.New(4f) ? "darkorange" : "orange"), ("fuelLeft", fuel), ("fuelCapacity", capacity))); } } private void OnWelderSolutionChange(EntityUid uid, WelderComponent welder, SolutionChangedEvent args) { welder.Dirty(); } private void OnWelderActivate(EntityUid uid, WelderComponent welder, ActivateInWorldEvent args) { args.Handled = TryToggleWelder(uid, args.User, welder); } private void OnWelderAfterInteract(EntityUid uid, WelderComponent welder, AfterInteractEvent args) { if (args.Handled) return; if (args.Target is not {Valid: true} target || !args.CanReach) return; // TODO: Clean up this inherited oldcode. if (EntityManager.TryGetComponent(target, out ReagentTankComponent? tank) && tank.TankType == ReagentTankType.Fuel && _solutionContainerSystem.TryGetDrainableSolution(target, out var targetSolution) && _solutionContainerSystem.TryGetSolution(uid, welder.FuelSolution, out var welderSolution)) { var trans = FixedPoint2.Min(welderSolution.AvailableVolume, targetSolution.DrainAvailable); if (trans > 0) { var drained = _solutionContainerSystem.Drain(target, targetSolution, trans); _solutionContainerSystem.TryAddSolution(uid, welderSolution, drained); SoundSystem.Play(Filter.Pvs(uid), welder.WelderRefill.GetSound(), uid); target.PopupMessage(args.User, Loc.GetString("welder-component-after-interact-refueled-message")); } else { target.PopupMessage(args.User, Loc.GetString("welder-component-no-fuel-in-tank", ("owner", args.Target))); } } args.Handled = true; } private void OnWelderToolUseAttempt(EntityUid uid, WelderComponent welder, ToolUseAttemptEvent args) { if (args.Cancelled) return; if (!welder.Lit) { _popupSystem.PopupEntity(Loc.GetString("welder-component-welder-not-lit-message"), uid, Filter.Entities(args.User)); args.Cancel(); return; } var (fuel, _) = GetWelderFuelAndCapacity(uid, welder); if (FixedPoint2.New(args.Fuel) > fuel) { _popupSystem.PopupEntity(Loc.GetString("welder-component-cannot-weld-message"), uid, Filter.Entities(args.User)); args.Cancel(); return; } } private void OnWelderToolUseFinishAttempt(EntityUid uid, WelderComponent welder, ToolUseFinishAttemptEvent args) { if (args.Cancelled) return; if (!welder.Lit) { _popupSystem.PopupEntity(Loc.GetString("welder-component-welder-not-lit-message"), uid, Filter.Entities(args.User)); args.Cancel(); return; } var (fuel, _) = GetWelderFuelAndCapacity(uid, welder); var neededFuel = FixedPoint2.New(args.Fuel); if (neededFuel > fuel) { args.Cancel(); } if (!_solutionContainerSystem.TryGetSolution(uid, welder.FuelSolution, out var solution)) { args.Cancel(); return; } solution.RemoveReagent(welder.FuelReagent, neededFuel); welder.Dirty(); } private void OnWelderShutdown(EntityUid uid, WelderComponent welder, ComponentShutdown args) { _activeWelders.Remove(uid); } private void OnWelderGetState(EntityUid uid, WelderComponent welder, ref ComponentGetState args) { var (fuel, capacity) = GetWelderFuelAndCapacity(uid, welder); args.State = new WelderComponentState(capacity.Float(), fuel.Float(), welder.Lit); } private void UpdateWelders(float frameTime) { _welderTimer += frameTime; if (_welderTimer < WelderUpdateTimer) return; foreach (var tool in _activeWelders.ToArray()) { if (!EntityManager.TryGetComponent(tool, out WelderComponent? welder) || !EntityManager.TryGetComponent(tool, out SolutionContainerManagerComponent? solutionContainer)) continue; if (!_solutionContainerSystem.TryGetSolution(tool, welder.FuelSolution, out var solution, solutionContainer)) continue; // TODO: Use TransformComponent directly. _atmosphereSystem.HotspotExpose(EntityManager.GetComponent<TransformComponent>(welder.Owner).Coordinates, 700, 50, true); solution.RemoveReagent(welder.FuelReagent, welder.FuelConsumption * _welderTimer); if (solution.GetReagentQuantity(welder.FuelReagent) <= FixedPoint2.Zero) TryTurnWelderOff(tool, null, welder); welder.Dirty(); } _welderTimer -= WelderUpdateTimer; } } }
38.723404
188
0.613265
[ "MIT" ]
AzzyIsNotHere/space-station-14
Content.Server/Tools/ToolSystem.Welder.cs
12,742
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.490) // Version 5.490.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Drawing; using System.ComponentModel; using System.Diagnostics; namespace ComponentFactory.Krypton.Toolkit { /// <summary> /// Draw a solid color block inside a context menu color column. /// </summary> public class ViewDrawMenuColorBlock : ViewLeaf { #region Instance Fields private readonly IContextMenuProvider _provider; private readonly Size _blockSize; private readonly bool _first; private readonly bool _last; #endregion #region Identity /// <summary> /// Initialize a new instance of the ViewDrawMenuColorBlock class. /// </summary> /// <param name="provider">Reference to provider.</param> /// <param name="colorColumns">Reference to owning color columns entry.</param> /// <param name="color">Drawing color for the block.</param> /// <param name="first">Is this element first in column.</param> /// <param name="last">Is this element last in column.</param> /// <param name="enabled">Is this column enabled</param> public ViewDrawMenuColorBlock(IContextMenuProvider provider, KryptonContextMenuColorColumns colorColumns, Color color, bool first, bool last, bool enabled) { _provider = provider; KryptonContextMenuColorColumns = colorColumns; Color = color; _first = first; _last = last; ItemEnabled = enabled; _blockSize = colorColumns.BlockSize; // Use context menu specific version of the radio button controller MenuColorBlockController mcbc = new MenuColorBlockController(provider.ProviderViewManager, this, this, provider.ProviderNeedPaintDelegate); mcbc.Click += OnClick; MouseController = mcbc; KeyController = mcbc; } /// <summary> /// Obtains the String representation of this instance. /// </summary> /// <returns>User readable name of the instance.</returns> public override string ToString() { // Return the class name and instance identifier return "ViewDrawMenuColorBlock:" + Id; } #endregion #region ItemEnabled /// <summary> /// Gets the enabled state of the item. /// </summary> public bool ItemEnabled { get; } #endregion #region KryptonContextMenuColorColumns /// <summary> /// Gets access to the actual color columns definiton. /// </summary> public KryptonContextMenuColorColumns KryptonContextMenuColorColumns { get; } #endregion #region CanCloseMenu /// <summary> /// Gets a value indicating if the menu is capable of being closed. /// </summary> public bool CanCloseMenu => _provider.ProviderCanCloseMenu; #endregion #region Closing /// <summary> /// Raises the Closing event on the provider. /// </summary> /// <param name="cea">A CancelEventArgs containing the event data.</param> public void Closing(CancelEventArgs cea) { _provider.OnClosing(cea); } #endregion #region Close /// <summary> /// Raises the Close event on the provider. /// </summary> /// <param name="e">A CancelEventArgs containing the event data.</param> public void Close(CloseReasonEventArgs e) { _provider.OnClose(e); } #endregion #region Color /// <summary> /// Gets the color associated with the block. /// </summary> public Color Color { get; } #endregion #region Layout /// <summary> /// Discover the preferred size of the element. /// </summary> /// <param name="context">Layout context.</param> /// <exception cref="ArgumentNullException"></exception> public override Size GetPreferredSize(ViewLayoutContext context) { Debug.Assert(context != null); // Validate incoming reference if (context == null) { throw new ArgumentNullException(nameof(context)); } return _blockSize; } /// <summary> /// Perform a layout of the elements. /// </summary> /// <param name="context">Layout context.</param> /// <exception cref="ArgumentNullException"></exception> public override void Layout(ViewLayoutContext context) { Debug.Assert(context != null); // Validate incoming reference if (context == null) { throw new ArgumentNullException(nameof(context)); } // We take on all the available display area ClientRectangle = context.DisplayRectangle; } #endregion #region Paint /// <summary> /// Perform rendering before child elements are rendered. /// </summary> /// <param name="context">Rendering context.</param> /// <exception cref="ArgumentNullException"></exception> public override void RenderBefore(RenderContext context) { Debug.Assert(context != null); // Validate incoming reference if (context == null) { throw new ArgumentNullException(nameof(context)); } // Start with the full client rectangle Rectangle drawRect = ClientRectangle; // Do not draw over the left and right lines drawRect.X += 1; drawRect.Width -= 2; // Do we need to prevent drawing over top line? if (_first) { drawRect.Y += 1; drawRect.Height -= 1; } // Do we need to prevent drawing over last line? if (_last) { drawRect.Height -= 1; } // Draw ourself in the designated color using (SolidBrush brush = new SolidBrush(Color)) { context.Graphics.FillRectangle(brush, drawRect); } } /// <summary> /// Perform rendering after child elements are rendered. /// </summary> /// <param name="context">Rendering context.</param> /// <exception cref="ArgumentNullException"></exception> public override void RenderAfter(RenderContext context) { Debug.Assert(context != null); // Validate incoming reference if (context == null) { throw new ArgumentNullException(nameof(context)); } // If not in normal state, then need to adorn display Color outside = Color.Empty; Color inside = Color.Empty; // Is this element selected? bool selected = (KryptonContextMenuColorColumns.SelectedColor != null) && (KryptonContextMenuColorColumns.SelectedColor.Equals(Color)); switch (ElementState) { case PaletteState.Tracking: if (ItemEnabled) { outside = _provider.ProviderStateChecked.ItemImage.Border.GetBorderColor1(PaletteState.CheckedNormal); inside = _provider.ProviderStateChecked.ItemImage.Back.GetBackColor1(PaletteState.CheckedNormal); } else { outside = _provider.ProviderStateHighlight.ItemHighlight.Border.GetBorderColor1(PaletteState.Disabled); inside = _provider.ProviderStateHighlight.ItemHighlight.Back.GetBackColor1(PaletteState.Disabled); } break; case PaletteState.Pressed: case PaletteState.Normal: if (selected || (ElementState == PaletteState.Pressed)) { outside = _provider.ProviderStateChecked.ItemImage.Border.GetBorderColor1(PaletteState.CheckedNormal); inside = _provider.ProviderStateChecked.ItemImage.Back.GetBackColor1(PaletteState.CheckedNormal); } break; } if (!outside.IsEmpty && !inside.IsEmpty) { // Draw the outside and inside areas of the block using (Pen outsidePen = new Pen(outside), insidePen = new Pen(inside)) { context.Graphics.DrawRectangle(outsidePen, ClientLocation.X, ClientLocation.Y, ClientWidth - 1, ClientHeight - 1); context.Graphics.DrawRectangle(insidePen, ClientLocation.X + 1, ClientLocation.Y + 1, ClientWidth - 3, ClientHeight - 3); } } } #endregion #region Private private void OnClick(object sender, EventArgs e) { KryptonContextMenuColorColumns.SelectedColor = Color; } #endregion } }
36.5
157
0.555284
[ "BSD-3-Clause" ]
Carko/Krypton-Toolkit-Suite-NET-Core
Source/Krypton Components/ComponentFactory.Krypton.Toolkit/View Draw/ViewDrawMenuColorBlock.cs
10,223
C#
using System; using System.Collections.Generic; using System.Diagnostics; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Engines; using BenchmarkDotNet.Running; namespace BenchmarkDotNet.Loggers { internal class SynchronousProcessOutputLoggerWithDiagnoser { private readonly ILogger logger; private readonly Process process; private readonly Benchmark benchmark; private readonly IDiagnoser diagnoser; private bool diagnosticsAlreadyRun = false; public SynchronousProcessOutputLoggerWithDiagnoser(ILogger logger, Process process, IDiagnoser diagnoser, Benchmark benchmark) { if (!process.StartInfo.RedirectStandardOutput) { throw new NotSupportedException("set RedirectStandardOutput to true first"); } this.logger = logger; this.process = process; this.diagnoser = diagnoser; this.benchmark = benchmark; Lines = new List<string>(); } internal List<string> Lines { get; } internal void ProcessInput() { string line; while ((line = process.StandardOutput.ReadLine()) != null) { logger.WriteLine(LogKind.Default, line); if (!line.StartsWith("//") && !string.IsNullOrEmpty(line)) { Lines.Add(line); } // This is important so the Diagnoser can know the [Benchmark] methods will have run and (e.g.) it can do a Memory Dump if (diagnosticsAlreadyRun || !line.StartsWith(IterationMode.MainWarmup.ToString())) { continue; } try { diagnoser?.AfterBenchmarkHasRun(benchmark, process); } finally { // Always set this, even if something went wrong, otherwise we will try on every run of a benchmark batch diagnosticsAlreadyRun = true; } } } } }
32.484848
135
0.569496
[ "MIT" ]
jcansdale/BenchmarkDotNet
src/BenchmarkDotNet.Core/Loggers/SynchronousProcessOutputLoggerWithDiagnoser.cs
2,146
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.StreamAnalytics.V20160301.Inputs { /// <summary> /// Describes an Event Hub output data source. /// </summary> public sealed class EventHubOutputDataSourceArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the Event Hub. Required on PUT (CreateOrReplace) requests. /// </summary> [Input("eventHubName")] public Input<string>? EventHubName { get; set; } /// <summary> /// The key/column that is used to determine to which partition to send event data. /// </summary> [Input("partitionKey")] public Input<string>? PartitionKey { get; set; } /// <summary> /// The namespace that is associated with the desired Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. /// </summary> [Input("serviceBusNamespace")] public Input<string>? ServiceBusNamespace { get; set; } /// <summary> /// The shared access policy key for the specified shared access policy. Required on PUT (CreateOrReplace) requests. /// </summary> [Input("sharedAccessPolicyKey")] public Input<string>? SharedAccessPolicyKey { get; set; } /// <summary> /// The shared access policy name for the Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. /// </summary> [Input("sharedAccessPolicyName")] public Input<string>? SharedAccessPolicyName { get; set; } /// <summary> /// Indicates the type of data source output will be written to. Required on PUT (CreateOrReplace) requests. /// Expected value is 'Microsoft.ServiceBus/EventHub'. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; public EventHubOutputDataSourceArgs() { } } }
37.75
159
0.636645
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/StreamAnalytics/V20160301/Inputs/EventHubOutputDataSourceArgs.cs
2,265
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Compute.Inputs { /// <summary> /// Optional. Allows users to provide customer managed keys for encrypting the OS and data disks in the gallery artifact. /// </summary> public sealed class EncryptionImagesArgs : Pulumi.ResourceArgs { [Input("dataDiskImages")] private InputList<Inputs.DataDiskImageEncryptionArgs>? _dataDiskImages; /// <summary> /// A list of encryption specifications for data disk images. /// </summary> public InputList<Inputs.DataDiskImageEncryptionArgs> DataDiskImages { get => _dataDiskImages ?? (_dataDiskImages = new InputList<Inputs.DataDiskImageEncryptionArgs>()); set => _dataDiskImages = value; } /// <summary> /// Contains encryption settings for an OS disk image. /// </summary> [Input("osDiskImage")] public Input<Inputs.OSDiskImageEncryptionArgs>? OsDiskImage { get; set; } public EncryptionImagesArgs() { } } }
32.97561
125
0.661982
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Compute/Inputs/EncryptionImagesArgs.cs
1,352
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Aspose" file="ShapeType.cs"> // Copyright (c) 2018 Aspose.Slides for Cloud // </copyright> // <summary> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // </summary> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Xml.Serialization; namespace Aspose.Slides.Cloud.Sdk.Model { /// <summary> /// Shape type /// </summary> /// <value>Shape type</value> [JsonConverter(typeof(StringEnumConverter))] public enum ShapeType { /// <summary> /// Enum Shape for "Shape" /// </summary> Shape, /// <summary> /// Enum Chart for "Chart" /// </summary> Chart, /// <summary> /// Enum Table for "Table" /// </summary> Table, /// <summary> /// Enum PictureFrame for "PictureFrame" /// </summary> PictureFrame, /// <summary> /// Enum VideoFrame for "VideoFrame" /// </summary> VideoFrame, /// <summary> /// Enum AudioFrame for "AudioFrame" /// </summary> AudioFrame, /// <summary> /// Enum SmartArt for "SmartArt" /// </summary> SmartArt, /// <summary> /// Enum OleObjectFrame for "OleObjectFrame" /// </summary> OleObjectFrame, /// <summary> /// Enum GroupShape for "GroupShape" /// </summary> GroupShape, /// <summary> /// Enum GraphicalObject for "GraphicalObject" /// </summary> GraphicalObject, /// <summary> /// Enum Connector for "Connector" /// </summary> Connector, /// <summary> /// Enum SmartArtShape for "SmartArtShape" /// </summary> SmartArtShape, /// <summary> /// Enum ZoomFrame for "ZoomFrame" /// </summary> ZoomFrame, /// <summary> /// Enum SectionZoomFrame for "SectionZoomFrame" /// </summary> SectionZoomFrame, /// <summary> /// Enum SummaryZoomFrame for "SummaryZoomFrame" /// </summary> SummaryZoomFrame, /// <summary> /// Enum SummaryZoomSection for "SummaryZoomSection" /// </summary> SummaryZoomSection } }
30.409449
119
0.542983
[ "MIT" ]
aspose-slides-cloud/aspose-cells-cloud-dotnet
Aspose.Slides.Cloud.Sdk/Model/ShapeType.cs
3,862
C#
// -------------------------------------------------------------------------------------------------- // <auto-generated> // This code was generated by a tool. // Script: ./scripts/cldr-relative-time.csx // // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. // </auto-generated> // -------------------------------------------------------------------------------------------------- using Alrev.Intl.Abstractions; using Alrev.Intl.Abstractions.PluralRules; using Alrev.Intl.Abstractions.RelativeTime; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; namespace Alrev.Intl.RelativeTime.Resources { /// <summary> /// Relative Time Units resource for 'English (Philippines)' [en-ph] /// </summary> public class EnPhRelativeTimeResource : ReadOnlyDictionary<RelativeTimeUnitValues, IReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>>, IRelativeTimeUnitsResource { /// <summary> /// The <see cref="IIntlResource"/> culture /// </summary> public CultureInfo Culture { get; } /// <summary> /// The class constructor /// </summary> public EnPhRelativeTimeResource() : base(new Dictionary<RelativeTimeUnitValues, IReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>>() { { RelativeTimeUnitValues.Year, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last year" }, { 0, "this year" }, { 1, "next year" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} year ago" }, { PluralRulesValues.Other, "{0} years ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} year" }, { PluralRulesValues.Other, "in {0} years" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last yr" }, { 0, "this yr" }, { 1, "next yr" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} yr ago" }, { PluralRulesValues.Other, "{0} yr ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} yr" }, { PluralRulesValues.Other, "in {0} yr" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last yr" }, { 0, "this yr" }, { 1, "next yr" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} yr ago" }, { PluralRulesValues.Other, "{0} yr ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} yr" }, { PluralRulesValues.Other, "in {0} yr" } }) } }) }, { RelativeTimeUnitValues.Quarter, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last quarter" }, { 0, "this quarter" }, { 1, "next quarter" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} quarter ago" }, { PluralRulesValues.Other, "{0} quarters ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} quarter" }, { PluralRulesValues.Other, "in {0} quarters" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last qtr." }, { 0, "this qtr." }, { 1, "next qtr." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} qtr ago" }, { PluralRulesValues.Other, "{0} qtr ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} qtr" }, { PluralRulesValues.Other, "in {0} qtr" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last qtr." }, { 0, "this qtr." }, { 1, "next qtr." } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} qtr ago" }, { PluralRulesValues.Other, "{0} qtr ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} qtr" }, { PluralRulesValues.Other, "in {0} qtr" } }) } }) }, { RelativeTimeUnitValues.Month, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last month" }, { 0, "this month" }, { 1, "next month" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} month ago" }, { PluralRulesValues.Other, "{0} months ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} month" }, { PluralRulesValues.Other, "in {0} months" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last mo" }, { 0, "this mo" }, { 1, "next mo" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} mo ago" }, { PluralRulesValues.Other, "{0} mo ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} mo" }, { PluralRulesValues.Other, "in {0} mo" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last mo" }, { 0, "this mo" }, { 1, "next mo" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} mo ago" }, { PluralRulesValues.Other, "{0} mo ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} mo" }, { PluralRulesValues.Other, "in {0} mo" } }) } }) }, { RelativeTimeUnitValues.Week, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last week" }, { 0, "this week" }, { 1, "next week" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} week ago" }, { PluralRulesValues.Other, "{0} weeks ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} week" }, { PluralRulesValues.Other, "in {0} weeks" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last wk" }, { 0, "this wk" }, { 1, "next wk" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} wk ago" }, { PluralRulesValues.Other, "{0} wk ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} wk" }, { PluralRulesValues.Other, "in {0} wk" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last wk" }, { 0, "this wk" }, { 1, "next wk" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} wk ago" }, { PluralRulesValues.Other, "{0} wk ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} wk" }, { PluralRulesValues.Other, "in {0} wk" } }) } }) }, { RelativeTimeUnitValues.Day, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "yesterday" }, { 0, "today" }, { 1, "tomorrow" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} day ago" }, { PluralRulesValues.Other, "{0} days ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} day" }, { PluralRulesValues.Other, "in {0} days" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "yesterday" }, { 0, "today" }, { 1, "tomorrow" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} day ago" }, { PluralRulesValues.Other, "{0} days ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} day" }, { PluralRulesValues.Other, "in {0} days" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "yesterday" }, { 0, "today" }, { 1, "tomorrow" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} day ago" }, { PluralRulesValues.Other, "{0} days ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} day" }, { PluralRulesValues.Other, "in {0} days" } }) } }) }, { RelativeTimeUnitValues.Sunday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Sunday" }, { 0, "this Sunday" }, { 1, "next Sunday" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Sunday ago" }, { PluralRulesValues.Other, "{0} Sundays ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Sunday" }, { PluralRulesValues.Other, "in {0} Sundays" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Sun" }, { 0, "this Sun" }, { 1, "next Sun" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Sun ago" }, { PluralRulesValues.Other, "{0} Sun ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Sun" }, { PluralRulesValues.Other, "in {0} Sun" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Su" }, { 0, "this Su" }, { 1, "next Su" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Su ago" }, { PluralRulesValues.Other, "{0} Su ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Su" }, { PluralRulesValues.Other, "in {0} Su" } }) } }) }, { RelativeTimeUnitValues.Monday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Monday" }, { 0, "this Monday" }, { 1, "next Monday" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Monday ago" }, { PluralRulesValues.Other, "{0} Mondays ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Monday" }, { PluralRulesValues.Other, "in {0} Mondays" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Mon" }, { 0, "this Mon" }, { 1, "next Mon" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Mon ago" }, { PluralRulesValues.Other, "{0} Mon ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Mon" }, { PluralRulesValues.Other, "in {0} Mon" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last M" }, { 0, "this M" }, { 1, "next M" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} M ago" }, { PluralRulesValues.Other, "{0} M ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} M" }, { PluralRulesValues.Other, "in {0} M" } }) } }) }, { RelativeTimeUnitValues.Tuesday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Tuesday" }, { 0, "this Tuesday" }, { 1, "next Tuesday" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Tuesday ago" }, { PluralRulesValues.Other, "{0} Tuesdays ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Tuesday" }, { PluralRulesValues.Other, "in {0} Tuesdays" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Tue" }, { 0, "this Tue" }, { 1, "next Tue" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Tue ago" }, { PluralRulesValues.Other, "{0} Tue ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Tue" }, { PluralRulesValues.Other, "in {0} Tue" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Tu" }, { 0, "this Tu" }, { 1, "next Tu" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Tu ago" }, { PluralRulesValues.Other, "{0} Tu ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Tu" }, { PluralRulesValues.Other, "in {0} Tu" } }) } }) }, { RelativeTimeUnitValues.Wednesday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Wednesday" }, { 0, "this Wednesday" }, { 1, "next Wednesday" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Wednesday ago" }, { PluralRulesValues.Other, "{0} Wednesdays ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Wednesday" }, { PluralRulesValues.Other, "in {0} Wednesdays" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Wed" }, { 0, "this Wed" }, { 1, "next Wed" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Wed ago" }, { PluralRulesValues.Other, "{0} Wed ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Wed" }, { PluralRulesValues.Other, "in {0} Wed" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last W" }, { 0, "this W" }, { 1, "next W" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} W ago" }, { PluralRulesValues.Other, "{0} W ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} W" }, { PluralRulesValues.Other, "in {0} W" } }) } }) }, { RelativeTimeUnitValues.Thursday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Thursday" }, { 0, "this Thursday" }, { 1, "next Thursday" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Thursday ago" }, { PluralRulesValues.Other, "{0} Thursdays ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Thursday" }, { PluralRulesValues.Other, "in {0} Thursdays" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Thu" }, { 0, "this Thu" }, { 1, "next Thu" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Thu ago" }, { PluralRulesValues.Other, "{0} Thu ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Thu" }, { PluralRulesValues.Other, "in {0} Thu" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Th" }, { 0, "this Th" }, { 1, "next Th" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Th ago" }, { PluralRulesValues.Other, "{0} Th ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Th" }, { PluralRulesValues.Other, "in {0} Th" } }) } }) }, { RelativeTimeUnitValues.Friday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Friday" }, { 0, "this Friday" }, { 1, "next Friday" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Friday ago" }, { PluralRulesValues.Other, "{0} Fridays ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Friday" }, { PluralRulesValues.Other, "in {0} Fridays" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Fri" }, { 0, "this Fri" }, { 1, "next Fri" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Fri ago" }, { PluralRulesValues.Other, "{0} Fri ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Fri" }, { PluralRulesValues.Other, "in {0} Fri" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last F" }, { 0, "this F" }, { 1, "next F" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} F ago" }, { PluralRulesValues.Other, "{0} F ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} F" }, { PluralRulesValues.Other, "in {0} F" } }) } }) }, { RelativeTimeUnitValues.Saturday, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Saturday" }, { 0, "this Saturday" }, { 1, "next Saturday" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Saturday ago" }, { PluralRulesValues.Other, "{0} Saturdays ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Saturday" }, { PluralRulesValues.Other, "in {0} Saturdays" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Sat" }, { 0, "this Sat" }, { 1, "next Sat" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Sat ago" }, { PluralRulesValues.Other, "{0} Sat ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Sat" }, { PluralRulesValues.Other, "in {0} Sat" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { -1, "last Sa" }, { 0, "this Sa" }, { 1, "next Sa" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} Sa ago" }, { PluralRulesValues.Other, "{0} Sa ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} Sa" }, { PluralRulesValues.Other, "in {0} Sa" } }) } }) }, { RelativeTimeUnitValues.Hour, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { 0, "this hour" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} hour ago" }, { PluralRulesValues.Other, "{0} hours ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} hour" }, { PluralRulesValues.Other, "in {0} hours" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { 0, "this hour" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} hr ago" }, { PluralRulesValues.Other, "{0} hr ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} hr" }, { PluralRulesValues.Other, "in {0} hr" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { 0, "this hour" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} hr ago" }, { PluralRulesValues.Other, "{0} hr ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} hr" }, { PluralRulesValues.Other, "in {0} hr" } }) } }) }, { RelativeTimeUnitValues.Minute, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { 0, "this minute" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} minute ago" }, { PluralRulesValues.Other, "{0} minutes ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} minute" }, { PluralRulesValues.Other, "in {0} minutes" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { 0, "this minute" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} min ago" }, { PluralRulesValues.Other, "{0} min ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} min" }, { PluralRulesValues.Other, "in {0} min" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { 0, "this minute" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} min ago" }, { PluralRulesValues.Other, "{0} min ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} min" }, { PluralRulesValues.Other, "in {0} min" } }) } }) }, { RelativeTimeUnitValues.Second, new ReadOnlyDictionary<IntlStyleValues, IRelativeTimeResource>( new Dictionary<IntlStyleValues, IRelativeTimeResource>() { { IntlStyleValues.Long, new RelativeTimeResource( new Dictionary<int, string> { { 0, "now" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} second ago" }, { PluralRulesValues.Other, "{0} seconds ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} second" }, { PluralRulesValues.Other, "in {0} seconds" } }) }, { IntlStyleValues.Short, new RelativeTimeResource( new Dictionary<int, string> { { 0, "now" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} sec ago" }, { PluralRulesValues.Other, "{0} sec ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} sec" }, { PluralRulesValues.Other, "in {0} sec" } }) }, { IntlStyleValues.Narrow, new RelativeTimeResource( new Dictionary<int, string> { { 0, "now" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "{0} sec ago" }, { PluralRulesValues.Other, "{0} sec ago" } }, new Dictionary<PluralRulesValues, string> { { PluralRulesValues.One, "in {0} sec" }, { PluralRulesValues.Other, "in {0} sec" } }) } }) } }) { this.Culture = new CultureInfo("en-ph"); } } }
54.477124
172
0.605039
[ "MIT" ]
pointnet/alrev-intl
packages/Alrev.Intl.RelativeTime/Resources/EnPhRelativeTimeResource.intl.cs
25,005
C#
using System; using System.Collections; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.DynamicData; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; namespace WebApplicationAssignmnet.DynamicData.FieldTemplates { public partial class BackButton : System.Web.UI.UserControl { public string Url { get; set; } protected void Page_Load(object sender, EventArgs e) { } protected void Back_Click(object sender, EventArgs e) { Response.Redirect(Url); } } }
24.625
64
0.687817
[ "MIT" ]
Mevicca/Artwork-sales-system
WebApplicationAssignmnet/DynamicData/FieldTemplates/BackButton.ascx.cs
790
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Dms.Ambulance.V2100</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Dms.Ambulance.V2100 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute(Namespace="urn:hl7-org:v3")] public partial class CV_Consent : CV { private static System.Xml.Serialization.XmlSerializer serializer; private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(CV_Consent)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current CV_Consent object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an CV_Consent object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output CV_Consent object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out CV_Consent obj, out System.Exception exception) { exception = null; obj = default(CV_Consent); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out CV_Consent obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static CV_Consent Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((CV_Consent)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current CV_Consent object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an CV_Consent object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output CV_Consent object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out CV_Consent obj, out System.Exception exception) { exception = null; obj = default(CV_Consent); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out CV_Consent obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static CV_Consent LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this CV_Consent object /// </summary> public virtual CV_Consent Clone() { return ((CV_Consent)(this.MemberwiseClone())); } #endregion } }
45.215789
1,368
0.581772
[ "MIT" ]
Kusnaditjung/MimDms
src/Dms.Ambulance.V2100/Generated/CV_Consent.cs
8,591
C#
using UIForia.Elements; using UIForia.Rendering; using UIForia.Util; namespace Systems.SelectorSystem { public class Selector { public SelectorQuery rootQuery; public UIStyle matchStyle; public void Run(UIElement origin) { LightList<UIElement> result = LightList<UIElement>.Get(); rootQuery.Gather(origin, result); if (result.size == 0) { result.Release(); return; } if (rootQuery.next == null) { // match! for (int i = 0; i < result.size; i++) { // result.array[i].style.SetSelectorStyle(matchStyle); } result.Release(); return; } for (int i = 0; i < result.size; i++) { if (rootQuery.next.Run(origin, result.array[i])) { // result.array[i].style.SetSelectorStyle(matchStyle); } } result.Release(); } } }
24.488372
74
0.481481
[ "MIT" ]
criedel/UIForia
Packages/UIForia/Src/Systems/SelectorSystem/Selector.cs
1,053
C#
/********************************************************************************** This class is generated using Kaushik.Spot.CodeGenerator, any change to this file may lead to malfunction. **********************************************************************************/ //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Kaushik.Spot.ControllerApp { using System; using System.Net.Sockets; using Kaushik.Spot.Library; public sealed class SpotServiceTest { private string server; private short port; private short bufferSize; private int socketClientTimeout; private short chunkSize; private string serviceName; private ICryptographicServiceProvider cipher; private ISpotSocketClient socketClient; public SpotServiceTest() : this(null, "192.167.1.107", 8080, SpotSocketProvider.Tcp) { } public SpotServiceTest(ICryptographicServiceProvider cipher, string server, short port, SpotSocketProvider provider) { this.server = server; this.port = port; this.bufferSize = 5120; this.socketClientTimeout = 50000000; this.chunkSize = 500; this.serviceName = "Kaushik.Spot.MicroServer.ISpotServiceTest"; this.cipher = cipher; this.socketClient = SpotSocketFactory.GetClientProvider(server, provider, port, bufferSize, socketClientTimeout, chunkSize); } private string encrypt(string text) { if ((this.cipher == null)) { return text; } else { return this.cipher.Encrypt(text); } } private string decrypt(string text) { if ((this.cipher == null)) { return text; } else { return this.cipher.Decrypt(text); } } public int Add(int a, int b) { string request; Kaushik.Spot.Library.ServiceCommand command; Kaushik.Spot.Library.ServiceResult result; string response; int finalResult; System.Net.Sockets.Socket socket; request = null; command = new Kaushik.Spot.Library.ServiceCommand(); result = new Kaushik.Spot.Library.ServiceResult(); response = null; finalResult = default(int); socket = this.socketClient.CreateClient(); try { command.ServiceName = this.serviceName; command.Method = "Add"; command.Parameters = new object[2]; command.Parameters[0] = a; command.Parameters[1] = b; request = this.encrypt(command.Serialize()); this.socketClient.Send(request); this.socketClient.Receive(out response); result.Deserialize(this.decrypt(response)); if ((string.IsNullOrEmpty(result.Error) != true)) { throw new System.Exception(result.Error); } if ((result.Result != null)) { int.TryParse(result.Result.ToString(), out finalResult); } } finally { if ((socket != null)) { socket.Dispose(); socket = null; } } return finalResult; } public string SayHello(string name) { string request; Kaushik.Spot.Library.ServiceCommand command; Kaushik.Spot.Library.ServiceResult result; string response; string finalResult; System.Net.Sockets.Socket socket; request = null; command = new Kaushik.Spot.Library.ServiceCommand(); result = new Kaushik.Spot.Library.ServiceResult(); response = null; finalResult = default(string); socket = this.socketClient.CreateClient(); try { command.ServiceName = this.serviceName; command.Method = "SayHello"; command.Parameters = new object[1]; command.Parameters[0] = name; request = this.encrypt(command.Serialize()); this.socketClient.Send(request); this.socketClient.Receive(out response); result.Deserialize(this.decrypt(response)); if ((string.IsNullOrEmpty(result.Error) != true)) { throw new System.Exception(result.Error); } if ((result.Result != null)) { finalResult = result.Result.ToString(); } } finally { if ((socket != null)) { socket.Dispose(); socket = null; } } return finalResult; } } }
32.627907
136
0.481646
[ "MIT" ]
cwithfourplus/kaushikspotservices
Src/Kaushik.Spot.ControllerApp/ServiceProxy/SpotServiceTest.cs
5,612
C#
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Reflection; using System.Threading; using log4net; using XenAdmin.Controls; using XenAdmin.Diagnostics.Problems; using XenAdmin.Wizards.PatchingWizard.PlanActions; using XenAPI; using System.Linq; using XenAdmin.Core; using System.Text; using System.Diagnostics; using XenAdmin.Alerts; namespace XenAdmin.Wizards.PatchingWizard { public partial class PatchingWizard_AutomatedUpdatesPage : XenTabPage { protected static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private bool _thisPageIsCompleted = false; public List<Problem> ProblemsResolvedPreCheck { private get; set; } public List<Pool> SelectedPools { private get; set; } public XenServerPatchAlert UpdateAlert { private get; set; } public WizardMode WizardMode { private get; set; } public bool ApplyUpdatesToNewVersion { private get; set; } private List<PoolPatchMapping> patchMappings = new List<PoolPatchMapping>(); public Dictionary<XenServerPatch, string> AllDownloadedPatches = new Dictionary<XenServerPatch, string>(); public KeyValuePair<XenServerPatch, string> PatchFromDisk { private get; set; } private List<UpdateProgressBackgroundWorker> backgroundWorkers = new List<UpdateProgressBackgroundWorker>(); public PatchingWizard_AutomatedUpdatesPage() { InitializeComponent(); } public override string Text { get { return Messages.PATCHINGWIZARD_AUTOUPDATINGPAGE_TEXT; } } public override string PageTitle { get { return Messages.PATCHINGWIZARD_AUTOUPDATINGPAGE_TITLE; } } public override string HelpID { get { return ""; } } public override bool EnablePrevious() { return false; } private bool _nextEnabled; public override bool EnableNext() { return _nextEnabled; } private bool _cancelEnabled = true; public override bool EnableCancel() { return _cancelEnabled; } public override void PageCancelled() { if (!_thisPageIsCompleted) { backgroundWorkers.ForEach(bgw => bgw.CancelAsync()); backgroundWorkers.Clear(); } base.PageCancelled(); } protected override void PageLoadedCore(PageLoadedDirection direction) { if (_thisPageIsCompleted) { return; } Debug.Assert(WizardMode == WizardMode.AutomatedUpdates || WizardMode == WizardMode.NewVersion && UpdateAlert != null); if (WizardMode == WizardMode.AutomatedUpdates) { labelTitle.Text = Messages.PATCHINGWIZARD_UPLOAD_AND_INSTALL_TITLE_AUTOMATED_MODE; } else if (WizardMode == WizardMode.NewVersion) { labelTitle.Text = Messages.PATCHINGWIZARD_UPLOAD_AND_INSTALL_TITLE_NEW_VERSION_AUTOMATED_MODE; } foreach (var pool in SelectedPools) { var master = Helpers.GetMaster(pool.Connection); var planActions = new List<PlanAction>(); var delayedActionsByHost = new Dictionary<Host, List<PlanAction>>(); var finalActions = new List<PlanAction>(); foreach (var host in pool.Connection.Cache.Hosts) { delayedActionsByHost.Add(host, new List<PlanAction>()); } var hosts = pool.Connection.Cache.Hosts; //if any host is not licensed for automated updates bool automatedUpdatesRestricted = pool.Connection.Cache.Hosts.Any(Host.RestrictBatchHotfixApply); var us = WizardMode == WizardMode.NewVersion ? Updates.GetUpgradeSequence(pool.Connection, UpdateAlert, ApplyUpdatesToNewVersion && !automatedUpdatesRestricted) : Updates.GetUpgradeSequence(pool.Connection); Debug.Assert(us != null, "Update sequence should not be null."); if (us != null) { foreach (var patch in us.UniquePatches) { var hostsToApply = us.Where(u => u.Value.Contains(patch)).Select(u => u.Key).ToList(); hostsToApply.Sort(); planActions.Add(new DownloadPatchPlanAction(master.Connection, patch, AllDownloadedPatches, PatchFromDisk)); planActions.Add(new UploadPatchToMasterPlanAction(master.Connection, patch, patchMappings, AllDownloadedPatches, PatchFromDisk)); planActions.Add(new PatchPrechecksOnMultipleHostsInAPoolPlanAction(master.Connection, patch, hostsToApply, patchMappings)); foreach (var host in hostsToApply) { planActions.Add(new ApplyXenServerPatchPlanAction(host, patch, patchMappings)); if (patch.GuidanceMandatory) { var action = patch.after_apply_guidance == after_apply_guidance.restartXAPI && delayedActionsByHost[host].Any(a => a is RestartHostPlanAction) ? new RestartHostPlanAction(host, host.GetRunningVMs(), restartAgentFallback:true) : GetAfterApplyGuidanceAction(host, patch.after_apply_guidance); if (action != null) { planActions.Add(action); // remove all delayed actions of the same kind that has already been added // (because this action is guidance-mandatory=true, therefore // it will run immediately, making delayed ones obsolete) delayedActionsByHost[host].RemoveAll(a => action.GetType() == a.GetType()); } } else { var action = GetAfterApplyGuidanceAction(host, patch.after_apply_guidance); // add the action if it's not already in the list if (action != null && !delayedActionsByHost[host].Any(a => a.GetType() == action.GetType())) delayedActionsByHost[host].Add(action); } } //clean up master at the end: planActions.Add(new RemoveUpdateFileFromMasterPlanAction(master, patchMappings, patch)); }//patch } //add a revert pre-check action for this pool var problemsToRevert = ProblemsResolvedPreCheck.Where(p => hosts.ToList().Select(h => h.uuid).ToList().Contains(p.Check.Host.uuid)).ToList(); if (problemsToRevert.Count > 0) { finalActions.Add(new UnwindProblemsAction(problemsToRevert, string.Format(Messages.REVERTING_RESOLVED_PRECHECKS_POOL, pool.Connection.Name))); } if (planActions.Count > 0) { var bgw = new UpdateProgressBackgroundWorker(planActions, delayedActionsByHost, finalActions); backgroundWorkers.Add(bgw); } } //foreach in SelectedMasters foreach (var bgw in backgroundWorkers) { bgw.DoWork += WorkerDoWork; bgw.WorkerReportsProgress = true; bgw.ProgressChanged += WorkerProgressChanged; bgw.RunWorkerCompleted += WorkerCompleted; bgw.WorkerSupportsCancellation = true; bgw.RunWorkerAsync(); } if (backgroundWorkers.Count == 0) { _thisPageIsCompleted = true; _nextEnabled = true; OnPageUpdated(); } } #region automatic_mode private List<PlanAction> doneActions = new List<PlanAction>(); private List<PlanAction> inProgressActions = new List<PlanAction>(); private List<PlanAction> errorActions = new List<PlanAction>(); private void WorkerProgressChanged(object sender, ProgressChangedEventArgs e) { var actionsWorker = sender as BackgroundWorker; Program.Invoke(Program.MainWindow, () => { if (!actionsWorker.CancellationPending) { PlanAction action = (PlanAction)e.UserState; if (action != null) { if (e.ProgressPercentage == 0) { inProgressActions.Add(action); } else { doneActions.Add(action); inProgressActions.Remove(action); progressBar.Value += e.ProgressPercentage/backgroundWorkers.Count; //extend with error handling related numbers } } UpdateStatusTextBox(); } }); } private void UpdateStatusTextBox() { var sb = new StringBuilder(); foreach (var pa in doneActions) { if (pa.Visible) { sb.Append(pa.ProgressDescription ?? pa.ToString()); sb.AppendLine(Messages.DONE); } } foreach (var pa in errorActions) { sb.Append(pa.ProgressDescription ?? pa.ToString()); sb.AppendLine(Messages.ERROR); } foreach (var pa in inProgressActions) { if (pa.Visible) { sb.Append(pa.ProgressDescription ?? pa.ToString()); sb.AppendLine(); } } textBoxLog.Text = sb.ToString(); textBoxLog.SelectionStart = textBoxLog.Text.Length; textBoxLog.ScrollToCaret(); } private void WorkerDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { var bgw = sender as UpdateProgressBackgroundWorker; if (bgw == null) return; PlanAction action = null; try { //running actions (non-delayed) foreach (var a in bgw.PlanActions) { action = a; if (bgw.CancellationPending) { doWorkEventArgs.Cancel = true; return; } RunPlanAction(bgw, action); } // running delayed actions, but skipping the ones that should be skipped // iterating through hosts, master first var hostsOrdered = bgw.DelayedActionsByHost.Keys.ToList(); hostsOrdered.Sort(); //master first foreach (var h in hostsOrdered) { var actions = bgw.DelayedActionsByHost[h]; var restartActions = actions.Where(a => a is RestartHostPlanAction).ToList(); //run all restart-alike plan actions foreach (var a in restartActions) { action = a; if (bgw.CancellationPending) { doWorkEventArgs.Cancel = true; return; } RunPlanAction(bgw, action); } var otherActions = actions.Where(a => !(a is RestartHostPlanAction)).ToList(); //run the rest foreach (var a in otherActions) { action = a; if (bgw.CancellationPending) { doWorkEventArgs.Cancel = true; return; } // any non-restart-alike delayed action needs to be run if: // - this host is pre-Ely and there isn't any delayed restart plan action, or // - this host is Ely or above and live patching must have succeeded or there isn't any delayed restart plan action if (restartActions.Count <= 0 || (Helpers.ElyOrGreater(h) && h.Connection.TryResolveWithTimeout(new XenRef<Host>(h.opaque_ref)).updates_requiring_reboot.Count <= 0)) { RunPlanAction(bgw, action); } else { //skip running it, but still need to report progress, mainly for the progress bar action.Visible = false; bgw.ReportProgress(100/bgw.ActionsCount, action); } } } //running final actions (eg. revert pre-checks) foreach (var a in bgw.FinalActions) { action = a; if (bgw.CancellationPending) { doWorkEventArgs.Cancel = true; return; } RunPlanAction(bgw, action); } } catch (Exception e) { errorActions.Add(action); inProgressActions.Remove(action); log.Error("Failed to carry out plan.", e); log.Debug(action.Title); doWorkEventArgs.Result = new Exception(action.Title, e); //this pool failed, we will stop here, but try to remove update files at least try { var positionOfFailedAction = bgw.PlanActions.IndexOf(action); // can try to clean up the host after a failed PlanAction from bgw.PlanActions only if (positionOfFailedAction != -1 && !(action is DownloadPatchPlanAction || action is UploadPatchToMasterPlanAction)) { int pos = positionOfFailedAction; if (!(bgw.PlanActions[pos] is RemoveUpdateFileFromMasterPlanAction)) //can't do anything if the remove action has failed { while (++pos < bgw.PlanActions.Count) { if (bgw.PlanActions[pos] is RemoveUpdateFileFromMasterPlanAction) //find the next remove { bgw.PlanActions[pos].Run(); break; } } } } } catch (Exception ex2) { //already in an error case - best effort log.Error("Failed to clean up (this was a best effort attempt)", ex2); } bgw.ReportProgress(0); } } private void RunPlanAction(UpdateProgressBackgroundWorker bgw, PlanAction action) { action.OnProgressChange += action_OnProgressChange; bgw.ReportProgress(0, action); action.Run(); Thread.Sleep(1000); action.OnProgressChange -= action_OnProgressChange; bgw.ReportProgress(100/bgw.ActionsCount, action); } private void action_OnProgressChange(object sender, EventArgs e) { Program.Invoke(Program.MainWindow, UpdateStatusTextBox); } private void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { var bgw = (UpdateProgressBackgroundWorker)sender; Program.Invoke(Program.MainWindow, () => { if (!e.Cancelled) { Exception exception = e.Result as Exception; if (exception != null) { //not showing exceptions in the meantime } //if all finished if (backgroundWorkers.All(w => !w.IsBusy)) { AllWorkersFinished(); ShowErrors(); _thisPageIsCompleted = true; _cancelEnabled = false; _nextEnabled = true; } } }); OnPageUpdated(); } private PlanAction GetAfterApplyGuidanceAction(Host host, after_apply_guidance guidance) { switch (guidance) { case after_apply_guidance.restartHost: return new RestartHostPlanAction(host, host.GetRunningVMs()); case after_apply_guidance.restartXAPI: return new RestartAgentPlanAction(host); case after_apply_guidance.restartHVM: return new RebootVMsPlanAction(host, host.GetRunningHvmVMs()); case after_apply_guidance.restartPV: return new RebootVMsPlanAction(host, host.GetRunningPvVMs()); default: return null; } } #endregion private void ShowErrors() { if (ErrorMessages != null) { labelTitle.Text = Messages.PATCHINGWIZARD_AUTOUPDATINGPAGE_FAILED; labelError.Text = Messages.PATCHINGWIZARD_AUTOUPDATINGPAGE_ERROR; textBoxLog.Text += ErrorMessages; log.ErrorFormat("Error message displayed: {0}", labelError.Text); pictureBox1.Image = SystemIcons.Error.ToBitmap(); panel1.Visible = true; } } private string ErrorMessages { get { if (errorActions.Count == 0) return null; var sb = new StringBuilder(); sb.AppendLine(); sb.AppendLine(errorActions.Count > 1 ? Messages.PATCHINGWIZARD_AUTOUPDATINGPAGE_ERRORS_OCCURRED : Messages.PATCHINGWIZARD_AUTOUPDATINGPAGE_ERROR_OCCURRED); foreach (var action in errorActions) { var exception = action.Error; if (exception == null) { log.ErrorFormat("An action has failed with an empty exception. Action: {0}", action.ToString()); continue; } log.Error(exception); if (exception != null && exception.InnerException != null && exception.InnerException is Failure) { var innerEx = exception.InnerException as Failure; log.Error(innerEx); sb.AppendLine(innerEx.Message); } else { sb.AppendLine(exception.Message); } } return sb.ToString(); } } private void AllWorkersFinished() { if (WizardMode == WizardMode.AutomatedUpdates) { labelTitle.Text = Messages.PATCHINGWIZARD_UPDATES_DONE_AUTOMATED_UPDATES_MODE; } else if (WizardMode == WizardMode.NewVersion) { labelTitle.Text = Messages.PATCHINGWIZARD_UPDATES_DONE_AUTOMATED_NEW_VERSION_MODE; } progressBar.Value = 100; pictureBox1.Image = null; labelError.Text = Messages.CLOSE_WIZARD_CLICK_FINISH; } } }
38.840336
172
0.500909
[ "BSD-2-Clause" ]
CraigOrendi/xenadmin
XenAdmin/Wizards/PatchingWizard/PatchingWizard_AutomatedUpdatesPage.cs
23,112
C#
// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using Scriban.Runtime; using Zio; namespace Lunet.Api.DotNet; public class ApiDotNetProject { public string Name { get; set; } public string Path { get; set; } public ScriptObject Properties { get; set; } public UPath CachePath { get; set; } public ApitDotNetCacheState CacheState { get; set; } public ScriptObject Api { get; set; } } public enum ApitDotNetCacheState { Invalid, NotFound, Found, New, }
21.096774
69
0.674312
[ "BSD-2-Clause" ]
lunet-io/lunet
src/Lunet.Api.DotNet/ApiDotNetProject.cs
656
C#
using System; namespace CSS.Utilities.ZLib { internal static class InternalInflateConstants { internal static readonly int[] InflateMask = { 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff }; } internal sealed class InflateBlocks { internal InflateBlocks(ZlibCodec codec, object checkfn, int w) { _codec = codec; hufts = new int[MANY * 3]; window = new byte[w]; end = w; this.checkfn = checkfn; mode = InflateBlockMode.TYPE; Reset(); } enum InflateBlockMode { TYPE = 0, // get type bits (3, including end bit) LENS = 1, // get lengths for stored STORED = 2, // processing stored block TABLE = 3, // get table lengths BTREE = 4, // get bit lengths tree for a dynamic block DTREE = 5, // get length, distance trees for a dynamic block CODES = 6, // processing fixed or dynamic block DRY = 7, // output remaining window bytes DONE = 8, // finished last block, done BAD = 9 // ot a data error--stuck here } internal static readonly int[] border = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; internal ZlibCodec _codec; internal int[] bb = new int[1]; internal int bitb; internal int bitk; internal int[] blens; internal uint check; internal object checkfn; internal InflateCodes codes = new InflateCodes(); internal int end; internal int[] hufts; internal int index; internal InfTree inftree = new InfTree(); internal int last; internal int left; internal int readAt; internal int table; internal int[] tb = new int[1]; internal byte[] window; internal int writeAt; const int MANY = 1440; InflateBlockMode mode; internal int Flush(int r) { int nBytes; for (var pass = 0; pass < 2; pass++) { if (pass == 0) { // compute number of bytes to copy as far as end of window nBytes = (readAt <= writeAt ? writeAt : end) - readAt; } else { // compute bytes to copy nBytes = writeAt - readAt; } // workitem 8870 if (nBytes == 0) { if (r == ZlibConstants.Z_BUF_ERROR) r = ZlibConstants.Z_OK; return r; } if (nBytes > _codec.AvailableBytesOut) nBytes = _codec.AvailableBytesOut; if (nBytes != 0 && r == ZlibConstants.Z_BUF_ERROR) r = ZlibConstants.Z_OK; // update counters _codec.AvailableBytesOut -= nBytes; _codec.TotalBytesOut += nBytes; // update check information if (checkfn != null) _codec._Adler32 = check = Adler.Adler32(check, window, readAt, nBytes); // copy as far as end of window Array.Copy(window, readAt, _codec.OutputBuffer, _codec.NextOut, nBytes); _codec.NextOut += nBytes; readAt += nBytes; // see if more to copy at beginning of window if (readAt == end && pass == 0) { // wrap pointers readAt = 0; if (writeAt == end) writeAt = 0; } else pass++; } // done return r; } internal void Free() { Reset(); window = null; hufts = null; } internal int Process(int r) { int t; // temporary storage int b; // bit buffer int k; // bits in bit buffer int p; // input data pointer int n; // bytes available there int q; // output window write pointer int m; // bytes to end of window or read pointer // copy input/output information to locals (UPDATE macro restores) p = _codec.NextIn; n = _codec.AvailableBytesIn; b = bitb; k = bitk; q = writeAt; m = q < readAt ? readAt - q - 1 : end - q; // process input based on current state while (true) { switch (mode) { case InflateBlockMode.TYPE: while (k < 3) { if (n != 0) { r = ZlibConstants.Z_OK; } else { bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } n--; b |= (_codec.InputBuffer[p++] & 0xff) << k; k += 8; } t = b & 7; last = t & 1; switch ((uint) t >> 1) { case 0: // stored b >>= 3; k -= 3; t = k & 7; // go to byte boundary b >>= t; k -= t; mode = InflateBlockMode.LENS; // get length of stored block break; case 1: // fixed var bl = new int[1]; var bd = new int[1]; var tl = new int[1][]; var td = new int[1][]; InfTree.inflate_trees_fixed(bl, bd, tl, td, _codec); codes.Init(bl[0], bd[0], tl[0], 0, td[0], 0); b >>= 3; k -= 3; mode = InflateBlockMode.CODES; break; case 2: // dynamic b >>= 3; k -= 3; mode = InflateBlockMode.TABLE; break; case 3: // illegal b >>= 3; k -= 3; mode = InflateBlockMode.BAD; _codec.Message = "invalid block type"; r = ZlibConstants.Z_DATA_ERROR; bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } break; case InflateBlockMode.LENS: while (k < 32) { if (n != 0) { r = ZlibConstants.Z_OK; } else { bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } ; n--; b |= (_codec.InputBuffer[p++] & 0xff) << k; k += 8; } if (((~b >> 16) & 0xffff) != (b & 0xffff)) { mode = InflateBlockMode.BAD; _codec.Message = "invalid stored block lengths"; r = ZlibConstants.Z_DATA_ERROR; bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } left = b & 0xffff; b = k = 0; // dump bits mode = left != 0 ? InflateBlockMode.STORED : (last != 0 ? InflateBlockMode.DRY : InflateBlockMode.TYPE); break; case InflateBlockMode.STORED: if (n == 0) { bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } if (m == 0) { if (q == end && readAt != 0) { q = 0; m = q < readAt ? readAt - q - 1 : end - q; } if (m == 0) { writeAt = q; r = Flush(r); q = writeAt; m = q < readAt ? readAt - q - 1 : end - q; if (q == end && readAt != 0) { q = 0; m = q < readAt ? readAt - q - 1 : end - q; } if (m == 0) { bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } } } r = ZlibConstants.Z_OK; t = left; if (t > n) t = n; if (t > m) t = m; Array.Copy(_codec.InputBuffer, p, window, q, t); p += t; n -= t; q += t; m -= t; if ((left -= t) != 0) break; mode = last != 0 ? InflateBlockMode.DRY : InflateBlockMode.TYPE; break; case InflateBlockMode.TABLE: while (k < 14) { if (n != 0) { r = ZlibConstants.Z_OK; } else { bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } n--; b |= (_codec.InputBuffer[p++] & 0xff) << k; k += 8; } table = t = b & 0x3fff; if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) { mode = InflateBlockMode.BAD; _codec.Message = "too many length or distance symbols"; r = ZlibConstants.Z_DATA_ERROR; bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); if (blens == null || blens.Length < t) { blens = new int[t]; } else { Array.Clear(blens, 0, t); // for (int i = 0; i < t; i++) { blens[i] = 0; } } b >>= 14; k -= 14; index = 0; mode = InflateBlockMode.BTREE; goto case InflateBlockMode.BTREE; case InflateBlockMode.BTREE: while (index < 4 + (table >> 10)) { while (k < 3) { if (n != 0) { r = ZlibConstants.Z_OK; } else { bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } n--; b |= (_codec.InputBuffer[p++] & 0xff) << k; k += 8; } blens[border[index++]] = b & 7; b >>= 3; k -= 3; } while (index < 19) { blens[border[index++]] = 0; } bb[0] = 7; t = inftree.inflate_trees_bits(blens, bb, tb, hufts, _codec); if (t != ZlibConstants.Z_OK) { r = t; if (r == ZlibConstants.Z_DATA_ERROR) { blens = null; mode = InflateBlockMode.BAD; } bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } index = 0; mode = InflateBlockMode.DTREE; goto case InflateBlockMode.DTREE; case InflateBlockMode.DTREE: while (true) { t = table; if (!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))) { break; } int i, j, c; t = bb[0]; while (k < t) { if (n != 0) { r = ZlibConstants.Z_OK; } else { bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } n--; b |= (_codec.InputBuffer[p++] & 0xff) << k; k += 8; } t = hufts[(tb[0] + (b & InternalInflateConstants.InflateMask[t])) * 3 + 1]; c = hufts[(tb[0] + (b & InternalInflateConstants.InflateMask[t])) * 3 + 2]; if (c < 16) { b >>= t; k -= t; blens[index++] = c; } else { // c == 16..18 i = c == 18 ? 7 : c - 14; j = c == 18 ? 11 : 3; while (k < t + i) { if (n != 0) { r = ZlibConstants.Z_OK; } else { bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } n--; b |= (_codec.InputBuffer[p++] & 0xff) << k; k += 8; } b >>= t; k -= t; j += b & InternalInflateConstants.InflateMask[i]; b >>= i; k -= i; i = index; t = table; if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1)) { blens = null; mode = InflateBlockMode.BAD; _codec.Message = "invalid bit length repeat"; r = ZlibConstants.Z_DATA_ERROR; bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } c = c == 16 ? blens[i - 1] : 0; do { blens[i++] = c; } while (--j != 0); index = i; } } tb[0] = -1; { int[] bl = { 9 }; // must be <= 9 for lookahead assumptions int[] bd = { 6 }; // must be <= 9 for lookahead assumptions var tl = new int[1]; var td = new int[1]; t = table; t = inftree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl, bd, tl, td, hufts, _codec); if (t != ZlibConstants.Z_OK) { if (t == ZlibConstants.Z_DATA_ERROR) { blens = null; mode = InflateBlockMode.BAD; } r = t; bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } codes.Init(bl[0], bd[0], hufts, tl[0], hufts, td[0]); } mode = InflateBlockMode.CODES; goto case InflateBlockMode.CODES; case InflateBlockMode.CODES: bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; r = codes.Process(this, r); if (r != ZlibConstants.Z_STREAM_END) { return Flush(r); } r = ZlibConstants.Z_OK; p = _codec.NextIn; n = _codec.AvailableBytesIn; b = bitb; k = bitk; q = writeAt; m = q < readAt ? readAt - q - 1 : end - q; if (last == 0) { mode = InflateBlockMode.TYPE; break; } mode = InflateBlockMode.DRY; goto case InflateBlockMode.DRY; case InflateBlockMode.DRY: writeAt = q; r = Flush(r); q = writeAt; m = q < readAt ? readAt - q - 1 : end - q; if (readAt != writeAt) { bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } mode = InflateBlockMode.DONE; goto case InflateBlockMode.DONE; case InflateBlockMode.DONE: r = ZlibConstants.Z_STREAM_END; bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); case InflateBlockMode.BAD: r = ZlibConstants.Z_DATA_ERROR; bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); default: r = ZlibConstants.Z_STREAM_ERROR; bitb = b; bitk = k; _codec.AvailableBytesIn = n; _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; writeAt = q; return Flush(r); } } } internal uint Reset() { var oldCheck = check; mode = InflateBlockMode.TYPE; bitk = 0; bitb = 0; readAt = writeAt = 0; if (checkfn != null) _codec._Adler32 = check = Adler.Adler32(0, null, 0, 0); return oldCheck; } internal void SetDictionary(byte[] d, int start, int n) { Array.Copy(d, start, window, 0, n); readAt = writeAt = n; } // Returns true if inflate is currently at the end of a block generated by Z_SYNC_FLUSH or Z_FULL_FLUSH. internal int SyncPoint() { return mode == InflateBlockMode.LENS ? 1 : 0; } } internal sealed class InflateCodes { // if EXT or COPY, where and how much internal int bitsToGet; // bits to get for extra internal byte dbits; // dtree bits decoder per branch internal int dist; // distance back to copy from internal int[] dtree; // distance tree internal int dtree_index; internal byte lbits; // mode dependent information internal int len; // ltree bits decoded per branch internal int lit; // distance tree internal int[] ltree; // literal/length/eob tree internal int ltree_index; internal int mode; // current inflate_codes mode internal int need; internal int[] tree; // pointer into tree internal int tree_index; #region Private Fields const int BADCODE = 9; const int COPY = 5; const int DIST = 3; // i: get distance next const int DISTEXT = 4; const int END = 8; const int LEN = 1; // i: get length/literal/eob next const int LENEXT = 2; // i: getting length extra (have base) // i: getting distance extra // o: copying bytes in window, waiting for space const int LIT = 6; // waiting for "i:"=input, "o:"=output, "x:"=nothing const int START = 0; // x: set up for LEN // o: got literal, waiting for output space const int WASH = 7; #endregion Private Fields // o: got eob, possibly still output waiting // x: got eob and all data flushed // x: got error // literal/length/eob tree #region Internal Methods internal int InflateFast(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index, InflateBlocks s, ZlibCodec z) { int t; // temporary pointer int[] tp; // temporary pointer int tp_index; // temporary pointer int e; // extra bits or operation int b; // bit buffer int k; // bits in bit buffer int p; // input data pointer int n; // bytes available there int q; // output window write pointer int m; // bytes to end of window or read pointer int ml; // mask for literal/length tree int md; // mask for distance tree int c; // bytes to copy int d; // distance back to copy from int r; // copy source pointer int tp_index_t_3; // (tp_index+t)*3 // load input, output, bit values p = z.NextIn; n = z.AvailableBytesIn; b = s.bitb; k = s.bitk; q = s.writeAt; m = q < s.readAt ? s.readAt - q - 1 : s.end - q; // initialize masks ml = InternalInflateConstants.InflateMask[bl]; md = InternalInflateConstants.InflateMask[bd]; // do until not enough input or output space for fast loop do { // assume called with m >= 258 && n >= 10 get literal/length code while (k < 20) { // max bits for literal/length code n--; b |= (z.InputBuffer[p++] & 0xff) << k; k += 8; } t = b & ml; tp = tl; tp_index = tl_index; tp_index_t_3 = (tp_index + t) * 3; if ((e = tp[tp_index_t_3]) == 0) { b >>= tp[tp_index_t_3 + 1]; k -= tp[tp_index_t_3 + 1]; s.window[q++] = (byte) tp[tp_index_t_3 + 2]; m--; continue; } do { b >>= tp[tp_index_t_3 + 1]; k -= tp[tp_index_t_3 + 1]; if ((e & 16) != 0) { e &= 15; c = tp[tp_index_t_3 + 2] + (b & InternalInflateConstants.InflateMask[e]); b >>= e; k -= e; // decode distance base of block to copy while (k < 15) { // max bits for distance code n--; b |= (z.InputBuffer[p++] & 0xff) << k; k += 8; } t = b & md; tp = td; tp_index = td_index; tp_index_t_3 = (tp_index + t) * 3; e = tp[tp_index_t_3]; do { b >>= tp[tp_index_t_3 + 1]; k -= tp[tp_index_t_3 + 1]; if ((e & 16) != 0) { // get extra bits to add to distance base e &= 15; while (k < e) { // get extra bits (up to 13) n--; b |= (z.InputBuffer[p++] & 0xff) << k; k += 8; } d = tp[tp_index_t_3 + 2] + (b & InternalInflateConstants.InflateMask[e]); b >>= e; k -= e; // do the copy m -= c; if (q >= d) { // offset before dest just copy r = q - d; if (q - r > 0 && 2 > q - r) { s.window[q++] = s.window[r++]; // minimum count is three, s.window[q++] = s.window[r++]; // so unroll loop a little c -= 2; } else { Array.Copy(s.window, r, s.window, q, 2); q += 2; r += 2; c -= 2; } } else { // else offset after destination r = q - d; do { r += s.end; // force pointer in window } while (r < 0); // covers invalid distances e = s.end - r; if (c > e) { // if source crosses, c -= e; // wrapped copy if (q - r > 0 && e > q - r) { do { s.window[q++] = s.window[r++]; } while (--e != 0); } else { Array.Copy(s.window, r, s.window, q, e); q += e; r += e; e = 0; } r = 0; // copy rest from start of window } } // copy all or what's left if (q - r > 0 && c > q - r) { do { s.window[q++] = s.window[r++]; } while (--c != 0); } else { Array.Copy(s.window, r, s.window, q, c); q += c; r += c; c = 0; } break; } if ((e & 64) == 0) { t += tp[tp_index_t_3 + 2]; t += b & InternalInflateConstants.InflateMask[e]; tp_index_t_3 = (tp_index + t) * 3; e = tp[tp_index_t_3]; } else { z.Message = "invalid distance code"; c = z.AvailableBytesIn - n; c = k >> 3 < c ? k >> 3 : c; n += c; p -= c; k -= c << 3; s.bitb = b; s.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; s.writeAt = q; return ZlibConstants.Z_DATA_ERROR; } } while (true); break; } if ((e & 64) == 0) { t += tp[tp_index_t_3 + 2]; t += b & InternalInflateConstants.InflateMask[e]; tp_index_t_3 = (tp_index + t) * 3; if ((e = tp[tp_index_t_3]) == 0) { b >>= tp[tp_index_t_3 + 1]; k -= tp[tp_index_t_3 + 1]; s.window[q++] = (byte) tp[tp_index_t_3 + 2]; m--; break; } } else if ((e & 32) != 0) { c = z.AvailableBytesIn - n; c = k >> 3 < c ? k >> 3 : c; n += c; p -= c; k -= c << 3; s.bitb = b; s.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; s.writeAt = q; return ZlibConstants.Z_STREAM_END; } else { z.Message = "invalid literal/length code"; c = z.AvailableBytesIn - n; c = k >> 3 < c ? k >> 3 : c; n += c; p -= c; k -= c << 3; s.bitb = b; s.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; s.writeAt = q; return ZlibConstants.Z_DATA_ERROR; } } while (true); } while (m >= 258 && n >= 10); // not enough input or output--restore pointers and return c = z.AvailableBytesIn - n; c = k >> 3 < c ? k >> 3 : c; n += c; p -= c; k -= c << 3; s.bitb = b; s.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; s.writeAt = q; return ZlibConstants.Z_OK; } // bits needed internal void Init(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index) { mode = START; lbits = (byte) bl; dbits = (byte) bd; ltree = tl; ltree_index = tl_index; dtree = td; dtree_index = td_index; tree = null; } internal int Process(InflateBlocks blocks, int r) { int j; // temporary storage int tindex; // temporary pointer int e; // extra bits or operation var b = 0; // bit buffer var k = 0; // bits in bit buffer var p = 0; // input data pointer int n; // bytes available there int q; // output window write pointer int m; // bytes to end of window or read pointer int f; // pointer to copy strings from var z = blocks._codec; // copy input/output information to locals (UPDATE macro restores) p = z.NextIn; n = z.AvailableBytesIn; b = blocks.bitb; k = blocks.bitk; q = blocks.writeAt; m = q < blocks.readAt ? blocks.readAt - q - 1 : blocks.end - q; // process input and output based on current state while (true) { switch (mode) { // waiting for "i:"=input, "o:"=output, "x:"=nothing case START: // x: set up for LEN if (m >= 258 && n >= 10) { blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; blocks.writeAt = q; r = InflateFast(lbits, dbits, ltree, ltree_index, dtree, dtree_index, blocks, z); p = z.NextIn; n = z.AvailableBytesIn; b = blocks.bitb; k = blocks.bitk; q = blocks.writeAt; m = q < blocks.readAt ? blocks.readAt - q - 1 : blocks.end - q; if (r != ZlibConstants.Z_OK) { mode = r == ZlibConstants.Z_STREAM_END ? WASH : BADCODE; break; } } need = lbits; tree = ltree; tree_index = ltree_index; mode = LEN; goto case LEN; case LEN: // i: get length/literal/eob next j = need; while (k < j) { if (n != 0) r = ZlibConstants.Z_OK; else { blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; blocks.writeAt = q; return blocks.Flush(r); } n--; b |= (z.InputBuffer[p++] & 0xff) << k; k += 8; } tindex = (tree_index + (b & InternalInflateConstants.InflateMask[j])) * 3; b >>= tree[tindex + 1]; k -= tree[tindex + 1]; e = tree[tindex]; if (e == 0) { // literal lit = tree[tindex + 2]; mode = LIT; break; } if ((e & 16) != 0) { // length bitsToGet = e & 15; len = tree[tindex + 2]; mode = LENEXT; break; } if ((e & 64) == 0) { // next table need = e; tree_index = tindex / 3 + tree[tindex + 2]; break; } if ((e & 32) != 0) { // end of block mode = WASH; break; } mode = BADCODE; // invalid code z.Message = "invalid literal/length code"; r = ZlibConstants.Z_DATA_ERROR; blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; blocks.writeAt = q; return blocks.Flush(r); case LENEXT: // i: getting length extra (have base) j = bitsToGet; while (k < j) { if (n != 0) r = ZlibConstants.Z_OK; else { blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; blocks.writeAt = q; return blocks.Flush(r); } n--; b |= (z.InputBuffer[p++] & 0xff) << k; k += 8; } len += b & InternalInflateConstants.InflateMask[j]; b >>= j; k -= j; need = dbits; tree = dtree; tree_index = dtree_index; mode = DIST; goto case DIST; case DIST: // i: get distance next j = need; while (k < j) { if (n != 0) r = ZlibConstants.Z_OK; else { blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; blocks.writeAt = q; return blocks.Flush(r); } n--; b |= (z.InputBuffer[p++] & 0xff) << k; k += 8; } tindex = (tree_index + (b & InternalInflateConstants.InflateMask[j])) * 3; b >>= tree[tindex + 1]; k -= tree[tindex + 1]; e = tree[tindex]; if ((e & 0x10) != 0) { // distance bitsToGet = e & 15; dist = tree[tindex + 2]; mode = DISTEXT; break; } if ((e & 64) == 0) { // next table need = e; tree_index = tindex / 3 + tree[tindex + 2]; break; } mode = BADCODE; // invalid code z.Message = "invalid distance code"; r = ZlibConstants.Z_DATA_ERROR; blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; blocks.writeAt = q; return blocks.Flush(r); case DISTEXT: // i: getting distance extra j = bitsToGet; while (k < j) { if (n != 0) r = ZlibConstants.Z_OK; else { blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; blocks.writeAt = q; return blocks.Flush(r); } n--; b |= (z.InputBuffer[p++] & 0xff) << k; k += 8; } dist += b & InternalInflateConstants.InflateMask[j]; b >>= j; k -= j; mode = COPY; goto case COPY; case COPY: // o: copying bytes in window, waiting for space f = q - dist; while (f < 0) { // modulo window size-"while" instead f += blocks.end; // of "if" handles invalid distances } while (len != 0) { if (m == 0) { if (q == blocks.end && blocks.readAt != 0) { q = 0; m = q < blocks.readAt ? blocks.readAt - q - 1 : blocks.end - q; } if (m == 0) { blocks.writeAt = q; r = blocks.Flush(r); q = blocks.writeAt; m = q < blocks.readAt ? blocks.readAt - q - 1 : blocks.end - q; if (q == blocks.end && blocks.readAt != 0) { q = 0; m = q < blocks.readAt ? blocks.readAt - q - 1 : blocks.end - q; } if (m == 0) { blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; blocks.writeAt = q; return blocks.Flush(r); } } } blocks.window[q++] = blocks.window[f++]; m--; if (f == blocks.end) f = 0; len--; } mode = START; break; case LIT: // o: got literal, waiting for output space if (m == 0) { if (q == blocks.end && blocks.readAt != 0) { q = 0; m = q < blocks.readAt ? blocks.readAt - q - 1 : blocks.end - q; } if (m == 0) { blocks.writeAt = q; r = blocks.Flush(r); q = blocks.writeAt; m = q < blocks.readAt ? blocks.readAt - q - 1 : blocks.end - q; if (q == blocks.end && blocks.readAt != 0) { q = 0; m = q < blocks.readAt ? blocks.readAt - q - 1 : blocks.end - q; } if (m == 0) { blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; blocks.writeAt = q; return blocks.Flush(r); } } } r = ZlibConstants.Z_OK; blocks.window[q++] = (byte) lit; m--; mode = START; break; case WASH: // o: got eob, possibly more output if (k > 7) { // return unused byte, if any k -= 8; n++; p--; // can always return one } blocks.writeAt = q; r = blocks.Flush(r); q = blocks.writeAt; m = q < blocks.readAt ? blocks.readAt - q - 1 : blocks.end - q; if (blocks.readAt != blocks.writeAt) { blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; blocks.writeAt = q; return blocks.Flush(r); } mode = END; goto case END; case END: r = ZlibConstants.Z_STREAM_END; blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; blocks.writeAt = q; return blocks.Flush(r); case BADCODE: // x: got error r = ZlibConstants.Z_DATA_ERROR; blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; blocks.writeAt = q; return blocks.Flush(r); default: r = ZlibConstants.Z_STREAM_ERROR; blocks.bitb = b; blocks.bitk = k; z.AvailableBytesIn = n; z.TotalBytesIn += p - z.NextIn; z.NextIn = p; blocks.writeAt = q; return blocks.Flush(r); } } } #endregion Internal Methods // Called with number of bytes left to write in window at least 258 (the maximum string // length) and number of input bytes available at least ten. The ten bytes are six bytes for // the longest length/ distance pair plus four bytes for overloading the bit buffer. } internal sealed class InflateManager { #region Internal Properties internal bool HandleRfc1950HeaderBytes { get; set; } = true; #endregion Internal Properties #region Private Enums enum InflateManagerMode { METHOD = 0, // waiting for method byte FLAG = 1, // waiting for flag byte DICT4 = 2, // four dictionary check bytes to go DICT3 = 3, // three dictionary check bytes to go DICT2 = 4, // two dictionary check bytes to go DICT1 = 5, // one dictionary check byte to go DICT0 = 6, // waiting for inflateSetDictionary BLOCKS = 7, // decompressing blocks CHECK4 = 8, // four check bytes to go CHECK3 = 9, // three check bytes to go CHECK2 = 10, // two check bytes to go CHECK1 = 11, // one check byte to go DONE = 12, // finished check, done BAD = 13 // got an error--stay here } #endregion Private Enums #region Internal Fields internal ZlibCodec _codec; internal InflateBlocks blocks; // if CHECK, check values to compare internal uint computedCheck; // computed check value internal uint expectedCheck; // if BAD, inflateSync's marker bytes count internal int marker; // stream check value mode dependent information internal int method; internal int wbits; #endregion Internal Fields #region Private Fields // preset dictionary flag in zlib header const int PRESET_DICT = 0x20; const int Z_DEFLATED = 8; static readonly byte[] mark = { 0, 0, 0xff, 0xff }; // pointer back to this zlib stream // mode independent information //internal int nowrap; // flag for no wrapper // current inflate_blocks state // if FLAGS, method byte InflateManagerMode mode; #endregion Private Fields // current inflate mode log2(window size) (8..15, defaults to 15) #region Public Constructors public InflateManager() { } public InflateManager(bool expectRfc1950HeaderBytes) { HandleRfc1950HeaderBytes = expectRfc1950HeaderBytes; } #endregion Public Constructors #region Internal Methods internal int End() { if (blocks != null) blocks.Free(); blocks = null; return ZlibConstants.Z_OK; } internal int Inflate(FlushType flush) { int b; if (_codec.InputBuffer == null) throw new ZlibException("InputBuffer is null. "); // int f = (flush == FlushType.Finish) ? ZlibConstants.Z_BUF_ERROR : ZlibConstants.Z_OK; // workitem 8870 var f = ZlibConstants.Z_OK; var r = ZlibConstants.Z_BUF_ERROR; while (true) { switch (mode) { case InflateManagerMode.METHOD: if (_codec.AvailableBytesIn == 0) return r; r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; if (((method = _codec.InputBuffer[_codec.NextIn++]) & 0xf) != Z_DEFLATED) { mode = InflateManagerMode.BAD; _codec.Message = string.Format("unknown compression method (0x{0:X2})", method); marker = 5; // can't try inflateSync break; } if ((method >> 4) + 8 > wbits) { mode = InflateManagerMode.BAD; _codec.Message = string.Format("invalid window size ({0})", (method >> 4) + 8); marker = 5; // can't try inflateSync break; } mode = InflateManagerMode.FLAG; break; case InflateManagerMode.FLAG: if (_codec.AvailableBytesIn == 0) return r; r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; b = _codec.InputBuffer[_codec.NextIn++] & 0xff; if (((method << 8) + b) % 31 != 0) { mode = InflateManagerMode.BAD; _codec.Message = "incorrect header check"; marker = 5; // can't try inflateSync break; } mode = (b & PRESET_DICT) == 0 ? InflateManagerMode.BLOCKS : InflateManagerMode.DICT4; break; case InflateManagerMode.DICT4: if (_codec.AvailableBytesIn == 0) return r; r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; expectedCheck = (uint) ((_codec.InputBuffer[_codec.NextIn++] << 24) & 0xff000000); mode = InflateManagerMode.DICT3; break; case InflateManagerMode.DICT3: if (_codec.AvailableBytesIn == 0) return r; r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; expectedCheck += (uint) ((_codec.InputBuffer[_codec.NextIn++] << 16) & 0x00ff0000); mode = InflateManagerMode.DICT2; break; case InflateManagerMode.DICT2: if (_codec.AvailableBytesIn == 0) return r; r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; expectedCheck += (uint) ((_codec.InputBuffer[_codec.NextIn++] << 8) & 0x0000ff00); mode = InflateManagerMode.DICT1; break; case InflateManagerMode.DICT1: if (_codec.AvailableBytesIn == 0) return r; r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; expectedCheck += (uint) (_codec.InputBuffer[_codec.NextIn++] & 0x000000ff); _codec._Adler32 = expectedCheck; mode = InflateManagerMode.DICT0; return ZlibConstants.Z_NEED_DICT; case InflateManagerMode.DICT0: mode = InflateManagerMode.BAD; _codec.Message = "need dictionary"; marker = 0; // can try inflateSync return ZlibConstants.Z_STREAM_ERROR; case InflateManagerMode.BLOCKS: r = blocks.Process(r); if (r == ZlibConstants.Z_DATA_ERROR) { mode = InflateManagerMode.BAD; marker = 0; // can try inflateSync break; } if (r == ZlibConstants.Z_OK) r = f; if (r != ZlibConstants.Z_STREAM_END) return r; r = f; computedCheck = blocks.Reset(); if (!HandleRfc1950HeaderBytes) { mode = InflateManagerMode.DONE; return ZlibConstants.Z_STREAM_END; } mode = InflateManagerMode.CHECK4; break; case InflateManagerMode.CHECK4: if (_codec.AvailableBytesIn == 0) return r; r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; expectedCheck = (uint) ((_codec.InputBuffer[_codec.NextIn++] << 24) & 0xff000000); mode = InflateManagerMode.CHECK3; break; case InflateManagerMode.CHECK3: if (_codec.AvailableBytesIn == 0) return r; r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; expectedCheck += (uint) ((_codec.InputBuffer[_codec.NextIn++] << 16) & 0x00ff0000); mode = InflateManagerMode.CHECK2; break; case InflateManagerMode.CHECK2: if (_codec.AvailableBytesIn == 0) return r; r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; expectedCheck += (uint) ((_codec.InputBuffer[_codec.NextIn++] << 8) & 0x0000ff00); mode = InflateManagerMode.CHECK1; break; case InflateManagerMode.CHECK1: if (_codec.AvailableBytesIn == 0) return r; r = f; _codec.AvailableBytesIn--; _codec.TotalBytesIn++; expectedCheck += (uint) (_codec.InputBuffer[_codec.NextIn++] & 0x000000ff); if (computedCheck != expectedCheck) { mode = InflateManagerMode.BAD; _codec.Message = "incorrect data check"; marker = 5; // can't try inflateSync break; } mode = InflateManagerMode.DONE; return ZlibConstants.Z_STREAM_END; case InflateManagerMode.DONE: return ZlibConstants.Z_STREAM_END; case InflateManagerMode.BAD: throw new ZlibException(string.Format("Bad state ({0})", _codec.Message)); default: throw new ZlibException("Stream error."); } } } internal int Initialize(ZlibCodec codec, int w) { _codec = codec; _codec.Message = null; blocks = null; // handle undocumented nowrap option (no zlib header or check) //nowrap = 0; //if (w < 0) //{ // w = - w; // nowrap = 1; //} // set window size if (w < 8 || w > 15) { End(); throw new ZlibException("Bad window size."); //return ZlibConstants.Z_STREAM_ERROR; } wbits = w; blocks = new InflateBlocks(codec, HandleRfc1950HeaderBytes ? this : null, 1 << w); // reset state Reset(); return ZlibConstants.Z_OK; } internal int Reset() { _codec.TotalBytesIn = _codec.TotalBytesOut = 0; _codec.Message = null; mode = HandleRfc1950HeaderBytes ? InflateManagerMode.METHOD : InflateManagerMode.BLOCKS; blocks.Reset(); return ZlibConstants.Z_OK; } internal int SetDictionary(byte[] dictionary) { var index = 0; var length = dictionary.Length; if (mode != InflateManagerMode.DICT0) throw new ZlibException("Stream error."); if (Adler.Adler32(1, dictionary, 0, dictionary.Length) != _codec._Adler32) { return ZlibConstants.Z_DATA_ERROR; } _codec._Adler32 = Adler.Adler32(0, null, 0, 0); if (length >= 1 << wbits) { length = (1 << wbits) - 1; index = dictionary.Length - length; } blocks.SetDictionary(dictionary, index, length); mode = InflateManagerMode.BLOCKS; return ZlibConstants.Z_OK; } internal int Sync() { int n; // number of bytes to look at int p; // pointer to bytes int m; // number of marker bytes found in a row long r, w; // temporaries to save total_in and total_out // set up if (mode != InflateManagerMode.BAD) { mode = InflateManagerMode.BAD; marker = 0; } if ((n = _codec.AvailableBytesIn) == 0) return ZlibConstants.Z_BUF_ERROR; p = _codec.NextIn; m = marker; // search while (n != 0 && m < 4) { if (_codec.InputBuffer[p] == mark[m]) { m++; } else if (_codec.InputBuffer[p] != 0) { m = 0; } else { m = 4 - m; } p++; n--; } // restore _codec.TotalBytesIn += p - _codec.NextIn; _codec.NextIn = p; _codec.AvailableBytesIn = n; marker = m; // return no joy or set up to restart on a new block if (m != 4) { return ZlibConstants.Z_DATA_ERROR; } r = _codec.TotalBytesIn; w = _codec.TotalBytesOut; Reset(); _codec.TotalBytesIn = r; _codec.TotalBytesOut = w; mode = InflateManagerMode.BLOCKS; return ZlibConstants.Z_OK; } // Returns true if inflate is currently at the end of a block generated by Z_SYNC_FLUSH or // Z_FULL_FLUSH. This function is used by one PPP implementation to provide an additional // safety check. PPP uses Z_SYNC_FLUSH but removes the length bytes of the resulting empty // stored block. When decompressing, PPP checks that at the end of input packet, inflate is // waiting for these length bytes. internal int SyncPoint(ZlibCodec z) { return blocks.SyncPoint(); } #endregion Internal Methods } }
37.744636
125
0.319077
[ "MIT" ]
skyprolk/Clash-Of-SL
Clash SL Server [UCS 7.4.0]/Utilities/ZLib/Inflate.cs
72,130
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using Vuforia; using UnityEngine.Video; public class csButton : MonoBehaviour, IVirtualButtonEventHandler { public GameObject quad; VideoPlayer vp; public void OnButtonPressed(VirtualButtonBehaviour vb) { // throw new System.NotImplementedException(); if (vp.isPlaying) { vp.Pause(); } else { vp.Play(); } } public void OnButtonReleased(VirtualButtonBehaviour vb) { // throw new System.NotImplementedException(); Debug.Log("Btn released" + vb.name); } // Start is called before the first frame update void Start() { vp = quad.GetComponent<VideoPlayer>(); VirtualButtonBehaviour[] vbs = GetComponentsInChildren<VirtualButtonBehaviour>(); for (int i = 0; i < vbs.Length; i ++) { vbs[i].RegisterEventHandler(this); } } // Update is called once per frame void Update() { } }
24.27907
89
0.62069
[ "MIT" ]
stories2/Kangnam-AR
Tutorial/Assets/Scripts/csButton.cs
1,046
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Altinn.Platform.Register.Configuration { /// <summary> /// General configuration settings /// </summary> public class GeneralSettings { /// <summary> /// Gets or sets the bridge api endpoint /// </summary> public string BridgeApiEndpoint { get; set; } /// <summary> /// Gets or sets if the solution should use mock or not /// </summary> public bool ShouldUseMock { get; set; } /// <summary> /// Gets the api base url for sbl bridge /// </summary> /// <returns>the api base url</returns> public string GetApiBaseUrl() { return Environment.GetEnvironmentVariable("GeneralSettings__BridgeApiEndpoint") ?? BridgeApiEndpoint; } } }
27.060606
113
0.604703
[ "BSD-3-Clause" ]
matsgm/altinn-studio
src/Altinn.Platform/Altinn.Platform.Register/Register/Configuration/GeneralSettings.cs
893
C#
/* Alphora Dataphor © Copyright 2000-2009 Alphora This file is licensed under a modified BSD-license which can be found here: http://dataphor.org/dataphor_license.txt */ using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; namespace Alphora.Dataphor.DAE.REST { using Alphora.Dataphor.DAE.Runtime; using Alphora.Dataphor.DAE.Runtime.Data; using Alphora.Dataphor.DAE.Schema; using Alphora.Dataphor.DAE.Server; using NativeCLI; using System.Collections; /// <summary> /// Provides a utility class for translating values to and from /// their Native representations for use in Native CLI calls. /// </summary> public static class RESTMarshal { public static DataParam[] ArgsToDataParams(IServerProcess process, IEnumerable<KeyValuePair<string, object>> args) { DataParam[] paramsValue = null; if (args != null) { var paramsList = new List<DataParam>(); foreach (var e in args) { var value = ValueToDataValue((ServerProcess)process, e.Value); paramsList.Add(new DataParam ( e.Key, value.DataType, DAE.Language.Modifier.In, value.IsNil ? null : (value is IScalar ? value.AsNative : value) )); } paramsValue = paramsList.ToArray(); } return paramsValue; } public static DataParams ParamsArrayToDataParams(IServerProcess process, DataParam[] paramsValue) { DataParams dataParams = new DataParams(); if (paramsValue != null) { foreach (var dataParam in paramsValue) { dataParams.Add(dataParam); } } return dataParams; } public static IDataValue ValueToDataValue(ServerProcess process, object value) { // If it's a value type or String, send it through as a scalar if (value == null || value.GetType().IsValueType || value.GetType() == typeof(string)) { return new Scalar(process.ValueManager, (IScalarType)ScalarTypeNameToDataType(process.DataTypes, value.GetType().Name), value); } // If it's a JObject, send it through as a row // I really don't want to do this (JSON is part of the communication layer, shouldn't be part of the processor here) but I don't want to build yet another pass-through structure to enable it when JObject is already that... var jObject = value as JObject; if (jObject != null) { var columns = new Columns(); var values = new List<IDataValue>(); foreach (var property in jObject) { var propertyValue = ValueToDataValue(process, property.Value); columns.Add(new Column(property.Key, GetDataType(propertyValue))); values.Add(propertyValue); } return new Row(process.ValueManager, new RowType(columns)); } var jValue = value as JValue; if (jValue != null) { return ValueToDataValue(process, jValue.Value); } // If it's an array or collection, send it through as a List... if (value.GetType().IsArray || value is ICollection) // TODO: Handle list and table parameters throw new NotSupportedException("List parameters are not yet supported."); // Otherwise, send it through as a row return new Row(process.ValueManager, process.ValueManager.DataTypes.SystemRow); } public static IDataType GetDataType(object value) { Scalar scalarValue = value as Scalar; if (scalarValue != null) return scalarValue.DataType; ListValue listValue = value as ListValue; if (listValue != null) return listValue.DataType; Row rowValue = value as Row; if (rowValue != null) return rowValue.DataType; TableValue tableValue = value as TableValue; if (tableValue != null) return tableValue.DataType; throw new NotSupportedException("Non-scalar-valued attributes are not supported."); } public static IEnumerable<object> ServerCursorToValue(IServerProcess process, IServerCursor cursor) { NativeTableValue nativeTable = NativeMarshal.TableVarToNativeTableValue(process, cursor.Plan.TableVar); var table = new List<object>(); IRow currentRow = cursor.Plan.RequestRow(); try { bool[] valueTypes = new bool[nativeTable.Columns.Length]; for (int index = 0; index < nativeTable.Columns.Length; index++) valueTypes[index] = currentRow.DataType.Columns[index].DataType is IScalarType; while (cursor.Next()) { cursor.Select(currentRow); var row = new Dictionary<string, object>(); for (int index = 0; index < nativeTable.Columns.Length; index++) if (valueTypes[index]) row.Add(nativeTable.Columns[index].Name, currentRow[index]); else row.Add(nativeTable.Columns[index].Name, DataValueToValue(process, currentRow.GetValue(index))); table.Add(row); } } finally { cursor.Plan.ReleaseRow(currentRow); } return table; } public static object DataValueToValue(IServerProcess process, IDataValue dataValue) { if (dataValue == null) return null; IScalar scalar = dataValue as IScalar; if (scalar != null) { return ScalarTypeNameToValue(dataValue.DataType.Name, scalar); } ListValue list = dataValue as ListValue; if (list != null) { var listValue = new List<object>(); if (!list.IsNil) { for (int index = 0; index < list.Count(); index++) { listValue.Add(DataValueToValue(process, list.GetValue(index))); } } return listValue; } IRow row = dataValue as IRow; if (row != null) { var rowValue = new Dictionary<string, object>(); if (!row.IsNil) { for (int index = 0; index < row.DataType.Columns.Count; index++) { var data = row.GetValue(index); data.DataType.Name = NativeMarshal.DataTypeToDataTypeName(process.DataTypes, row.DataType.Columns[index].DataType); rowValue.Add(row.DataType.Columns[index].Name, DataValueToValue(process, data)); } } return rowValue; } TableValue tableValue = dataValue as TableValue; TableValueScan scan = null; try { if (tableValue != null) { scan = new TableValueScan(tableValue); scan.Open(); dataValue = scan; } ITable table = dataValue as ITable; if (table != null) { var nativeTable = new NativeTableValue(); var resultTable = new List<object>(); if (!table.BOF()) table.First(); bool[] valueTypes = new bool[table.DataType.Columns.Count]; for (int index = 0; index < table.DataType.Columns.Count; index++) valueTypes[index] = table.DataType.Columns[index].DataType is IScalarType; while (table.Next()) { using (IRow currentRow = table.Select()) { object[] nativeRow = new object[table.DataType.Columns.Count]; for (int index = 0; index < table.DataType.Columns.Count; index++) if (valueTypes[index]) resultTable.Add(currentRow[index]); else resultTable.Add(DataValueToValue(process, currentRow.GetValue(index))); } } return resultTable; } } finally { if (scan != null) scan.Dispose(); } throw new NotSupportedException(string.Format("Values of type \"{0}\" are not supported.", dataValue.DataType.Name)); } public static IDataType ScalarTypeNameToDataType(DataTypes dataTypes, string dataTypeName) { switch (dataTypeName.ToLower()) { case "byte[]": return dataTypes.SystemBinary; case "bool": case "boolean": return dataTypes.SystemBoolean; case "byte": return dataTypes.SystemByte; case "date": return dataTypes.SystemDate; case "datetime": return dataTypes.SystemDateTime; case "decimal": return dataTypes.SystemDecimal; case "exception": return dataTypes.SystemError; case "guid": return dataTypes.SystemGuid; case "int32": case "integer": return dataTypes.SystemInteger; case "int64": case "long": return dataTypes.SystemLong; case "money": return dataTypes.SystemMoney; case "int16": case "short": return dataTypes.SystemShort; case "string": return dataTypes.SystemString; case "time": return dataTypes.SystemTime; case "timespan": return dataTypes.SystemTimeSpan; default: throw new ArgumentException(string.Format("Invalid native data type name: \"{0}\".", dataTypeName)); } } public static object ScalarTypeNameToValue(string dataTypeName, IScalar dataTypeValue) { switch (dataTypeName.ToLower()) { case "byte[]": return dataTypeValue.AsByte; case "bool": case "boolean": return dataTypeValue.AsBoolean; case "byte": return dataTypeValue.AsByte; case "date": return dataTypeValue.AsDateTime; case "datetime": return dataTypeValue.AsDateTime; case "decimal": return dataTypeValue.AsDecimal; case "exception": return new ArgumentException(string.Format("Exception: \"{0}\".", dataTypeName)); case "guid": return dataTypeValue.AsGuid; case "int32": case "integer": return dataTypeValue.AsInt32; case "int64": case "long": return dataTypeValue.AsInt64; case "money": return dataTypeValue.AsDecimal; case "int16": case "short": return dataTypeValue.AsInt16; case "string": return dataTypeValue.IsNil ? null : dataTypeValue.AsString; case "time": return dataTypeValue.AsDateTime; case "timespan": return dataTypeValue.AsTimeSpan; default: throw new ArgumentException(string.Format("Invalid native data type name: \"{0}\".", dataTypeName)); } } } }
31.036304
225
0.681944
[ "BSD-3-Clause" ]
DBCG/Dataphor
Dataphor/Server/REST/RESTMarshal.cs
9,407
C#
/* * Copyright (C) 2016 Ansuria Solutions LLC & Tommy Baggett: * http://github.com/tbaggett * http://twitter.com/tbaggett * http://tommyb.com * http://ansuria.com * * The MIT License (MIT) see GitHub For more information * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Xamarin.Forms; using XFGloss; using XFGlossSample.Utils; namespace XFGlossSample.Examples.Views.CSharp { public class BackgroundGradientPage : ContentPage { bool updateGradient; Gradient rotatingGradient; TextCell rotatingCell; protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); /* This is a bit of a hack. Android's renderer for TableView always adds an empty header for a TableSection declaration, while iOS doesn't. To compensate, I'm using a Label to display info text on iOS, and the TableSection on Android since there is no easy way to get rid of it.This is a long-standing bug in the XF TableView on Android. (https://forums.xamarin.com/discussion/18037/tablesection-w-out-header) */ TableSection section; if (Device.RuntimePlatform == Device.Android) { section = new TableSection("Cell BackgroundGradient values set in C#:"); } else { section = new TableSection(); } section.Add(CreateBackgroundGradientCells()); var stack = new StackLayout(); if (Device.RuntimePlatform == Device.iOS) { stack.Children.Add(new Label { Text = "Cell BackgroundGradient values set in C#:", Margin = new Thickness(10) }); } stack.Children.Add(new TableView { Intent = TableIntent.Data, BackgroundColor = Color.Transparent, VerticalOptions = LayoutOptions.Start, HeightRequest = XFGlossDevices.OnPlatform<double>(176, 232), Root = new TableRoot { section } }); stack.Children.Add(new Label { Text = "ContentPage BackgroundGradient value set in C#:", Margin = new Thickness(10) }); Content = stack; // Set the page's background gradient ContentPageGloss.SetBackgroundGradient(this, new Gradient(Color.White, Color.FromRgb(128, 0, 0))); } protected override void OnAppearing() { base.OnAppearing(); updateGradient = true; Device.StartTimer(new TimeSpan(1000000), UpdateGradient); } protected override void OnDisappearing() { base.OnDisappearing(); updateGradient = false; } TextCell[] CreateBackgroundGradientCells() { List<TextCell> result = new List<TextCell>(); Dictionary<string, Tuple<int, Color, Color>> Colors = new Dictionary<string, Tuple<int, Color, Color>>() { { "Red", new Tuple<int, Color, Color>(Gradient.RotationTopToBottom, Color.Red, Color.Maroon) }, { "Green", new Tuple<int, Color, Color>(Gradient.RotationLeftToRight, Color.Lime, Color.Green) }, { "Blue", new Tuple<int, Color, Color>(Gradient.RotationBottomToTop, Color.Blue, Color.Navy) } }; // Iterate through the color values, creating a new text cell for each entity var colorNames = Colors.Keys; foreach (string colorName in colorNames) { var cell = new TextCell(); cell.Text = colorName; cell.TextColor = Color.White; // Assign our gloss properties - You can use the standard static setter... var cellInfo = Colors[colorName]; CellGloss.SetBackgroundGradient(cell, new Gradient(cellInfo.Item1, cellInfo.Item2, cellInfo.Item3)); // ...or instantiate an instance of the Gloss properties you want to assign values to // var gloss = new XFGloss.Views.Cell(cell); // gloss.AccessoryType = accType; // gloss.BackgroundColor = Color.Blue; // gloss.TintColor = Color.Red; // ... result.Add(cell); } // Add a multi-color gradient rotatingCell = new TextCell(); rotatingCell.Text = "All Three"; rotatingCell.TextColor = Color.White; // Manually construct a multi-color gradient at an angle of our choosing rotatingGradient = new Gradient() { Rotation = 135, Steps = new GradientStepCollection() { new GradientStep(Colors["Red"].Item2, 0), new GradientStep(Colors["Red"].Item3, .25), new GradientStep(Colors["Green"].Item2, .4), new GradientStep(Colors["Green"].Item3, .6), new GradientStep(Colors["Blue"].Item2, .75), new GradientStep(Colors["Blue"].Item3, 1), } }; // You can also initialize a multi-color gradient in code like this: //rotatingGradient = new Gradient(135); // 135 degree angle //rotatingGradient.AddStep(Colors["Red"].Item2, 0); //rotatingGradient.AddStep(Colors["Red"].Item3, .25); //rotatingGradient.AddStep(Colors["Green"].Item2, .4); //rotatingGradient.AddStep(Colors["Green"].Item3, .6); //rotatingGradient.AddStep(Colors["Blue"].Item2, .75); //rotatingGradient.AddStep(Colors["Blue"].Item3, 1); CellGloss.SetBackgroundGradient(rotatingCell, rotatingGradient); result.Add(rotatingCell); return result.ToArray(); } /****************************************** * * NOTE: This code is for gradient demonstration purposes only. I do NOT recommend you continuously update * a gradient fill in a cell or page! * ******************************************/ bool UpdateGradient() { Xamarin.Forms.Device.BeginInvokeOnMainThread(() => { if (rotatingGradient.Rotation >= 355) { rotatingGradient.Rotation = 0; } else { rotatingGradient.Rotation += 5; } }); return updateGradient; } } }
30.502646
122
0.682914
[ "MIT" ]
fireye14/xfgloss
src/XFGlossSample/Examples/Views/CSharp/BackgroundGradientPage.cs
5,767
C#
using System; using System.Threading; using NUnit.Framework; using Tailviewer.Api; namespace Tailviewer.Core.Tests.Sources.Merged { [TestFixture] public sealed class MergedLogSourceTest2 : AbstractTaskSchedulerLogFileTest { #region Overrides of AbstractTaskSchedulerLogFileTest protected override ILogSource CreateEmpty(ITaskScheduler taskScheduler) { return new MergedLogSource(taskScheduler, TimeSpan.Zero, new EmptyLogSource()); } #endregion } }
22.428571
82
0.802548
[ "MIT" ]
Rizx/Tailviewer
src/Tailviewer.Core.Tests/Sources/Merged/MergedLogSourceTest2.cs
473
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227 namespace SizedBoxView.WinApp { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // Set the default language rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; rootFrame.NavigationFailed += OnNavigationFailed; Xamarin.Forms.Forms.Init(e); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
38.133929
99
0.625146
[ "Apache-2.0" ]
NoleHealth/xamarin-forms-book-preview-2
Chapter04/SizedBoxView/SizedBoxView/SizedBoxView.WinApp/App.xaml.cs
4,273
C#
using AutoMapper; using StockTradingAnalysis.Core.Common; using StockTradingAnalysis.Domain.CQRS.Query.Queries; using StockTradingAnalysis.Interfaces.Domain; using StockTradingAnalysis.Interfaces.Queries; using StockTradingAnalysis.Interfaces.ReadModel; using StockTradingAnalysis.Web.Models; using System.Linq; namespace StockTradingAnalysis.Web.AutoMapperProfiles { /// <summary> /// The StockProfile cotains the automapper configuration for <see cref="IStock"/>. /// </summary> /// <seealso cref="Profile" /> public class StockProfile : Profile { /// <summary> /// Initializes a new instance of the <see cref="StockProfile"/> class. /// </summary> public StockProfile() { CreateMap<IStock, StockViewModel>() .ForMember(t => t.Id, source => source.MapFrom(s => s.Id)) .ForMember(t => t.OriginalVersion, source => source.MapFrom(s => s.OriginalVersion)) .ForMember(t => t.StocksDescription, source => source.MapFrom(s => s.StocksDescription)) .ForMember(t => t.StocksShortDescription, source => source.MapFrom(s => s.StocksShortDescription)) .ForMember(t => t.Name, source => source.MapFrom(s => s.Name)) .ForMember(t => t.Wkn, source => source.MapFrom(s => s.Wkn)) .ForMember(t => t.Type, source => source.MapFrom(s => s.Type)) .ForMember(t => t.LongShort, source => source.MapFrom(s => s.LongShort)) .ForMember(t => t.Performance, source => source.MapFrom(s => ResolvePerformance(s))) .ForMember(t => t.TransactionHistory, source => source.MapFrom(s => ResolveTransactionHistory(s))) .ForMember(t => t.LastestQuote, source => source.MapFrom(s => ResolveLatestQuote(s))); CreateMap<IStock, SelectionViewModel>() .ForMember(t => t.Id, source => source.MapFrom(s => s.Id)) .ForMember(t => t.Text, source => source.MapFrom(s => s.StocksShortDescription)); } /// <summary> /// Resolves the performance for the given <paramref name="stock"/> /// </summary> /// <param name="stock">The stock.</param> /// <returns>Performance</returns> private decimal ResolvePerformance(IStock stock) { if (stock == null) return default(decimal); var modelRepository = DependencyResolver.Current.GetService<IModelReaderRepository<IStockStatistics>>(); var model = modelRepository.GetById(stock.Id); return model?.Performance ?? default(decimal); } /// <summary> /// Resolves the transaction history for the given <paramref name="stock"/> /// </summary> /// <param name="stock">The stock.</param> /// <returns>Transaction history</returns> private object ResolveTransactionHistory(IStock stock) { if (stock == null) return Enumerable.Empty<TransactionHistoryViewModel>(); var queryDispatcher = DependencyResolver.Current.GetService<IQueryDispatcher>(); var transactions = queryDispatcher.Execute(new TransactionByStockIdQuery(stock.Id)); return transactions ?? Enumerable.Empty<ITransaction>(); } /// <summary> /// Resolves the latest quote for the given <paramref name="stock"/> /// </summary> /// <param name="stock">The stock.</param> /// <returns>Latest quote</returns> private IQuotation ResolveLatestQuote(IStock stock) { if (stock == null) return null; var queryDispatcher = DependencyResolver.Current.GetService<IQueryDispatcher>(); var quote = queryDispatcher.Execute(new StockQuotationsLatestByIdQuery(stock.Id)); return quote; } } }
36.677419
107
0.705365
[ "Unlicense" ]
BenjaminBest/StockTradingAnalysisWebsite
StockTradingAnalysisWebsite/StockTradingAnalysis.Web/App_Start/AutoMapperProfiles/StockProfile.cs
3,413
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable #if !NET5_0 namespace System.Runtime.Versioning { /// <summary> /// Base type for all platform-specific API attributes. /// </summary> internal abstract class OSPlatformAttribute : Attribute { private protected OSPlatformAttribute(string platformName) { PlatformName = platformName; } public string PlatformName { get; } } /// <summary> /// Records the platform that the project targeted. /// </summary> [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] internal sealed class TargetPlatformAttribute : OSPlatformAttribute { public TargetPlatformAttribute(string platformName) : base(platformName) { } } /// <summary> /// Records the operating system (and minimum version) that supports an API. Multiple attributes can be /// applied to indicate support on multiple operating systems. /// </summary> /// <remarks> /// <para>Callers can apply a <see cref="SupportedOSPlatformAttribute" /> /// or use guards to prevent calls to APIs on unsupported operating systems.</para> /// /// <para>A given platform should only be specified once.</para> /// </remarks> [AttributeUsage( AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Enum | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Module | AttributeTargets.Property | AttributeTargets.Struct, AllowMultiple = true, Inherited = false)] internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute { public SupportedOSPlatformAttribute(string platformName) : base(platformName) { } } /// <summary> /// Marks APIs that were removed in a given operating system version. /// </summary> /// <remarks> /// Primarily used by OS bindings to indicate APIs that are only available in /// earlier versions. /// </remarks> [AttributeUsage( AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Enum | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Module | AttributeTargets.Property | AttributeTargets.Struct, AllowMultiple = true, Inherited = false)] internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute { public UnsupportedOSPlatformAttribute(string platformName) : base(platformName) { } } } #endif
31.610526
107
0.655012
[ "MIT" ]
Acidburn0zzz/roslyn
src/Compilers/Core/Portable/InternalUtilities/PlatformAttributes.cs
3,005
C#
using Ship; using Upgrade; using System; using System.Linq; namespace UpgradesList.FirstEdition { public class ScavengerCrane : GenericUpgrade { public ScavengerCrane() : base() { UpgradeInfo = new UpgradeCardInfo( "Scavenger Crane", UpgradeType.Illicit, cost: 2, abilityType: typeof(Abilities.FirstEdition.ScavengerCraneAbility) ); } } } namespace Abilities.FirstEdition { public class ScavengerCraneAbility : GenericAbility { public override void ActivateAbility() { GenericShip.OnShipIsDestroyedGlobal += RegisterScavengerCraneAbility; } public override void DeactivateAbility() { GenericShip.OnShipIsDestroyedGlobal -= RegisterScavengerCraneAbility; } private void RegisterScavengerCraneAbility(GenericShip destroyedShip, bool isFled) { BoardTools.DistanceInfo distanceInfo = new BoardTools.DistanceInfo(HostShip, destroyedShip); if (distanceInfo.Range <= 2) { var recoverableUpgrades = GetRecoverableUpgrades(); if (recoverableUpgrades.Length > 0) { RegisterAbilityTrigger(TriggerTypes.OnShipIsDestroyed, AskUseScavengerCrane); } } } protected void AskUseScavengerCrane(object sender, EventArgs e) { var phase = Phases.StartTemporarySubPhaseNew<SubPhases.ScavengerCraneDecisionSubPhase>("Select upgrade to recover", Triggers.FinishTrigger); phase.hostUpgrade = HostUpgrade; phase.hostAbility = this; phase.Start(); } public GenericUpgrade[] GetRecoverableUpgrades() { var allowedTypes = new[] { UpgradeType.Torpedo, UpgradeType.Missile, UpgradeType.Bomb, UpgradeType.Cannon, UpgradeType.Turret, UpgradeType.Modification }; var discardedUpgrades = HostShip.UpgradeBar.GetUpgradesOnlyDiscarded() .Where(upgrade => allowedTypes.Any(type => upgrade.HasType(type))) .ToArray(); return discardedUpgrades; } } } namespace SubPhases { public class ScavengerCraneDecisionSubPhase : DecisionSubPhase { public GenericUpgrade hostUpgrade; public Abilities.FirstEdition.ScavengerCraneAbility hostAbility; public override void PrepareDecision(System.Action callBack) { InfoText = "Select upgrade to recover"; var discardedUpgrades = hostAbility.GetRecoverableUpgrades(); foreach (var upgrade in discardedUpgrades) { var thisUpgrade = upgrade; AddDecision(upgrade.UpgradeInfo.Name, (s, e) => RecoverUpgrade(thisUpgrade)); AddTooltip(upgrade.UpgradeInfo.Name, upgrade.ImageUrl); } AddDecision("None", (s, e) => ConfirmDecision()); DefaultDecisionName = GetDecisions().First().Name; callBack(); } protected void RecoverUpgrade(GenericUpgrade upgrade) { ConfirmDecisionNoCallback(); upgrade.TryFlipFaceUp(RollForDiscard); } protected void RollForDiscard() { var phase = Phases.StartTemporarySubPhaseNew<ScavengerCraneRollSubPhase>("Roll for discarding Scavenger Crane", () => { Phases.FinishSubPhase(typeof(ScavengerCraneRollSubPhase)); Triggers.FinishTrigger(); }); phase.scanvengerCraneUpgrade = hostUpgrade; phase.Start(); } } public class ScavengerCraneRollSubPhase : DiceRollCheckSubPhase { public GenericUpgrade scanvengerCraneUpgrade; public override void Prepare() { DiceKind = DiceKind.Attack; DiceCount = 1; Selection.ActiveShip = scanvengerCraneUpgrade.HostShip; AfterRoll = FinishAction; } protected override void FinishAction() { HideDiceResultMenu(); if (CurrentDiceRoll.DiceList[0].Side == DieSide.Blank) { Messages.ShowInfoToHuman(string.Format("{0} has to discard Scavenger Crane", scanvengerCraneUpgrade.HostShip.PilotInfo.PilotName)); scanvengerCraneUpgrade.TryDiscard(CallBack); } else { CallBack(); } } } }
32.475177
166
0.606028
[ "MIT" ]
belk/FlyCasual
Assets/Scripts/Model/Content/FirstEdition/Upgrades/Illicit/ScavengerCrane.cs
4,581
C#
using System; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; namespace Products.Api.IntegrationTests.Infrastructure { public class TestHostFixture : IDisposable { public TestHostFixture() { var host = new WebHostBuilder() .UseDefaultServiceProvider(x => { x.ValidateScopes = true; }) .UseStartup<TestStartup>(); Server = new TestServer(host); } public TestServer Server { get; } public void Dispose() { Server.Dispose(); } } }
23.035714
54
0.542636
[ "MIT" ]
hbiarge/Authorization-Workshop
src/Authorization-Workshop/test/Products.Api.IntegrationTests/Infrastructure/TestHostFixture.cs
647
C#
using System; using System.Collections.Generic; namespace zad_4 { class Program { static void Main() { var emailBook = new Dictionary<string, string>(); string[] inputArr = new string[2]; while (true) { inputArr[0] = Console.ReadLine(); if (inputArr[0].ToLower() == "stop") { foreach (var kvp in emailBook) { Console.WriteLine($"{kvp.Key} -> {kvp.Value}"); } return; } inputArr[1] = Console.ReadLine(); if (!inputArr[1].ToLower().EndsWith("us") & !inputArr[1].ToLower().EndsWith("uk")) { emailBook[inputArr[0]] = inputArr[1]; } } } } }
28.548387
98
0.40791
[ "MIT" ]
StackSmack007/Programing-Fundamentals-September-2018
Dictionaries, Lambda and LINQ-Excersises/zad_4/Program.cs
887
C#
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using wikia.Configuration; using wikia.Helper; using wikia.Models.SearchSuggestions; namespace wikia.Api { public sealed class WikiSearchSuggestions : IWikiSearchSuggestions { private readonly IWikiaHttpClient _wikiaHttpClient; private readonly string _wikiApiUrl; private const string SearchSuggestionsUrlSegment = "SearchSuggestions/List"; public WikiSearchSuggestions(string domainUrl) : this(domainUrl, WikiaSettings.ApiVersion) { } public WikiSearchSuggestions(string domainUrl, IHttpClientFactory httpClientFactory) : this(domainUrl, WikiaSettings.ApiVersion, new WikiaHttpClient(httpClientFactory)) { } public WikiSearchSuggestions(string domainUrl, string apiVersion) : this(domainUrl, apiVersion, new WikiaHttpClient()) { } public WikiSearchSuggestions(string domainUrl, string apiVersion, IWikiaHttpClient wikiaHttpClient) { _wikiaHttpClient = wikiaHttpClient; _wikiApiUrl = UrlHelper.GenerateUrl(domainUrl, apiVersion); } public async Task<SearchSuggestionsPhrases> SuggestedPhrases(string query) { if (string.IsNullOrWhiteSpace(query)) throw new ArgumentException("Search suggestion query required.", nameof(query)); var requestUrl = UrlHelper.GenerateUrl(_wikiApiUrl, SearchSuggestionsUrlSegment); var parameters = new Dictionary<string, string> { ["query"] = query }; var json = await _wikiaHttpClient.GetString(requestUrl, parameters); return JsonHelper.Deserialize<SearchSuggestionsPhrases>(json); } } }
33.796296
107
0.693151
[ "MIT" ]
fablecode/wikia-core
src/Wikia/Api/WikiSearchSuggestions.cs
1,827
C#
using System.ComponentModel.DataAnnotations; namespace EmpowerData.EntityModels { public partial class IW_BankAccountType { [Key] public int BankAccountTypeSysID { get; set; } [Required] [StringLength(100)] public string EnumValue { get; set; } } }
20.2
53
0.646865
[ "Apache-2.0" ]
HaloImageEngine/EmpowerClaim-hotfix-1.25.1
EmpowerData/EntityModels/IW_BankAccountType.cs
303
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Net.Mail; using NuGet.Services.Entities; namespace NuGetGallery { /// <summary> /// APIs that provide lightweight extensibility for the User entity. /// </summary> public static class UserExtensionsCore { /// <summary> /// Convert a User's email to a System.Net MailAddress. /// </summary> public static MailAddress ToMailAddress(this User user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } if (!user.Confirmed) { return new MailAddress(user.UnconfirmedEmailAddress, user.Username); } return new MailAddress(user.EmailAddress, user.Username); } } }
29.121212
111
0.605619
[ "Apache-2.0" ]
0xced/NuGetGallery
src/NuGetGallery.Core/Extensions/UserExtensionsCore.cs
963
C#
using Imagin.Colour.Primitives; using Imagin.Common; using Imagin.Common.Media; namespace Imagin.Colour.Controls.Models { /// <summary> /// /// </summary> public class HWBViewModel : ColorModel<HWB> { /// <summary> /// /// </summary> public HWBViewModel() : base(new HComponent(), new WComponent(), new BComponent()) { } /// <summary> /// /// </summary> public abstract class HWBComponent : VisualComponent<HWB> { /// <summary> /// /// </summary> public sealed override Vector GetMaximum() => HWB.Maximum; /// <summary> /// /// </summary> /// <returns></returns> public sealed override Vector GetMinimum() => HWB.Minimum; } /// <summary> /// /// </summary> public sealed class HComponent : HWBComponent, IComponentA { /// <summary> /// /// </summary> /// <returns></returns> public override string Label => "H"; /// <summary> /// /// </summary> /// <returns></returns> public override double Maximum => HWB.Maximum[0]; /// <summary> /// /// </summary> /// <returns></returns> public override double Minimum => HWB.Minimum[0]; /// <summary> /// /// </summary> public override ComponentUnit Unit => ComponentUnit.Degrees; } /// <summary> /// /// </summary> public sealed class WComponent : HWBComponent, IComponentB { /// <summary> /// /// </summary> /// <returns></returns> public override string Label => "W"; /// <summary> /// /// </summary> /// <returns></returns> public override double Maximum => HWB.Maximum[1]; /// <summary> /// /// </summary> /// <returns></returns> public override double Minimum => HWB.Minimum[1]; /// <summary> /// /// </summary> public override ComponentUnit Unit => ComponentUnit.Percent; } /// <summary> /// /// </summary> public sealed class BComponent : HWBComponent, IComponentC { /// <summary> /// /// </summary> /// <returns></returns> public override string Label => "B"; /// <summary> /// /// </summary> /// <returns></returns> public override double Maximum => HWB.Maximum[2]; /// <summary> /// /// </summary> /// <returns></returns> public override double Minimum => HWB.Minimum[2]; /// <summary> /// /// </summary> public override ComponentUnit Unit => ComponentUnit.Percent; } } }
26.421488
94
0.427901
[ "BSD-2-Clause" ]
OkumaScott/Imagin.NET
Imagin.Colour.WPF/Models/_Models/HWB.cs
3,199
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Maps.V20210701Preview.Outputs { /// <summary> /// Creator resource properties /// </summary> [OutputType] public sealed class CreatorPropertiesResponse { /// <summary> /// The state of the resource provisioning, terminal states: Succeeded, Failed, Canceled /// </summary> public readonly string ProvisioningState; /// <summary> /// The storage units to be allocated. Integer values from 1 to 100, inclusive. /// </summary> public readonly int StorageUnits; [OutputConstructor] private CreatorPropertiesResponse( string provisioningState, int storageUnits) { ProvisioningState = provisioningState; StorageUnits = storageUnits; } } }
29.102564
96
0.65022
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Maps/V20210701Preview/Outputs/CreatorPropertiesResponse.cs
1,135
C#
using Application.Common.Dtos; using Application.Common.Models; using Application.StudentPortal.Categories.Commands.SetPreferences; using System.Collections.Generic; using System.Threading.Tasks; namespace Client.App.Infrastructure.WebServices { public interface ICategoryWebService : IWebService { Task<IResult<List<CategoryDto>>> GetPreferencesAsync(string accessToken); Task<IResult> SetPreferencesAsync(SetCategoryPreferencesCommand request, string accessToken); } }
35.714286
101
0.804
[ "MIT" ]
mecvillarina/TernerAcademy
src/student-portal/Client.App.Infrastucture/WebServices/Interfaces/ICategoryWebService.cs
502
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SDKDocGenerator.UnitTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SDKDocGenerator.UnitTests")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("884c59bf-05f7-49da-bf20-6bc6de5c737d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.432432
85
0.729952
[ "Apache-2.0" ]
philasmar/aws-sdk-net
docgenerator/SDKDocGenerator.UnitTests/Properties/AssemblyInfo.cs
1,462
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Linq; using ICSharpCode.NRefactory.Semantics; using ICSharpCode.NRefactory.TypeSystem; using NUnit.Framework; namespace ICSharpCode.NRefactory.CSharp.Resolver { [TestFixture] public class AnonymousTypeTests : ResolverTestBase { const string programStart = @"using System; using System.Collections.Generic; using System.Linq; class Test { void M(IEnumerable<string> list1, IEnumerable<int> list2) { "; const string programEnd = " } }"; [Test] public void Zip() { string program = programStart + "$var$ q = list1.Zip(list2, (a,b) => new { a, b });" + programEnd; var rr = Resolve<TypeResolveResult>(program); Assert.AreEqual("System.Collections.Generic.IEnumerable", rr.Type.FullName); var type = (AnonymousType)((ParameterizedType)rr.Type).TypeArguments.Single(); Assert.AreEqual(TypeKind.Anonymous, type.Kind); Assert.AreEqual(2, type.Properties.Count); Assert.AreEqual("a", type.Properties[0].Name); Assert.AreEqual("b", type.Properties[1].Name); Assert.AreEqual("System.String", type.Properties[0].ReturnType.ReflectionName); Assert.AreEqual("System.Int32", type.Properties[1].ReturnType.ReflectionName); } [Test] public void ZipItem1() { string program = programStart + "var q = list1.Zip(list2, (a,b) => new { $Item1 = a$, Item2 = b });" + programEnd; var rr = Resolve<MemberResolveResult>(program); Assert.AreEqual(TypeKind.Anonymous, rr.Member.DeclaringType.Kind); Assert.AreEqual("Item1", rr.Member.Name); Assert.AreEqual(EntityType.Property, rr.Member.EntityType); Assert.AreEqual("System.String", rr.Member.ReturnType.FullName); } } }
42.861538
117
0.742283
[ "MIT" ]
AlexAlbala/Alter-Native
NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Resolver/AnonymousTypeTests.cs
2,788
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20180701.Outputs { [OutputType] public sealed class AzureFirewallApplicationRuleCollectionResponse { /// <summary> /// The action type of a rule collection /// </summary> public readonly Outputs.AzureFirewallRCActionResponse? Action; /// <summary> /// Gets a unique read-only string that changes whenever the resource is updated. /// </summary> public readonly string Etag; /// <summary> /// Resource ID. /// </summary> public readonly string? Id; /// <summary> /// Gets name of the resource that is unique within a resource group. This name can be used to access the resource. /// </summary> public readonly string? Name; /// <summary> /// Priority of the application rule collection resource. /// </summary> public readonly int? Priority; /// <summary> /// The provisioning state of the resource. /// </summary> public readonly string ProvisioningState; /// <summary> /// Collection of rules used by a application rule collection. /// </summary> public readonly ImmutableArray<Outputs.AzureFirewallApplicationRuleResponse> Rules; [OutputConstructor] private AzureFirewallApplicationRuleCollectionResponse( Outputs.AzureFirewallRCActionResponse? action, string etag, string? id, string? name, int? priority, string provisioningState, ImmutableArray<Outputs.AzureFirewallApplicationRuleResponse> rules) { Action = action; Etag = etag; Id = id; Name = name; Priority = priority; ProvisioningState = provisioningState; Rules = rules; } } }
31.309859
123
0.610886
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Network/V20180701/Outputs/AzureFirewallApplicationRuleCollectionResponse.cs
2,223
C#
using System; using EPiServer.Data; namespace Forte.Migrations.EPiServer { public class MigrationsLogEntry { public Identity Id { get; set; } public string MigrationName { get; set; } public string MigrationId { get; set; } public DateTime MigrationAppliedOn { get; set; } public MigrationsLogEntry() { this.Id = Identity.NewIdentity(); } } }
22.421053
56
0.610329
[ "MIT" ]
fortedigital/Migrations
Migrations.EPiServer/MigrationsLogEntry.cs
428
C#
using System.Threading.Tasks; namespace FoodPal.Orders.MessageBroker.Contracts { public interface IMessageBroker { Task SendMessageAsync<TMessage>(string queueName, TMessage message); } }
19.5
70
0.8
[ "MIT" ]
RalucaMihalcea-dev/foodpal-orders
src/FoodPal.Orders.MessageBroker.Contracts/IMessageBroker.cs
197
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Storage; namespace Microsoft.EntityFrameworkCore.InMemory.Query.Internal { public partial class InMemoryShapedQueryCompilingExpressionVisitor { private sealed class InMemoryProjectionBindingRemovingExpressionVisitor : ExpressionVisitor { private readonly IDictionary<ParameterExpression, (IDictionary<IProperty, int> IndexMap, ParameterExpression valueBuffer)> _materializationContextBindings = new Dictionary<ParameterExpression, (IDictionary<IProperty, int> IndexMap, ParameterExpression valueBuffer)>(); protected override Expression VisitBinary(BinaryExpression binaryExpression) { if (binaryExpression.NodeType == ExpressionType.Assign && binaryExpression.Left is ParameterExpression parameterExpression && parameterExpression.Type == typeof(MaterializationContext)) { var newExpression = (NewExpression)binaryExpression.Right; var projectionBindingExpression = (ProjectionBindingExpression)newExpression.Arguments[0]; var queryExpression = (InMemoryQueryExpression)projectionBindingExpression.QueryExpression; _materializationContextBindings[parameterExpression] = ((IDictionary<IProperty, int>)GetProjectionIndex(queryExpression, projectionBindingExpression), ((InMemoryQueryExpression)projectionBindingExpression.QueryExpression).CurrentParameter); var updatedExpression = Expression.New( newExpression.Constructor, Expression.Constant(ValueBuffer.Empty), newExpression.Arguments[1]); return Expression.MakeBinary(ExpressionType.Assign, binaryExpression.Left, updatedExpression); } if (binaryExpression.NodeType == ExpressionType.Assign && binaryExpression.Left is MemberExpression memberExpression && memberExpression.Member is FieldInfo fieldInfo && fieldInfo.IsInitOnly) { return memberExpression.Assign(Visit(binaryExpression.Right)); } return base.VisitBinary(binaryExpression); } protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression) { if (methodCallExpression.Method.IsGenericMethod && methodCallExpression.Method.GetGenericMethodDefinition() == EntityMaterializerSource.TryReadValueMethod) { var property = (IProperty)((ConstantExpression)methodCallExpression.Arguments[2]).Value; var (indexMap, valueBuffer) = _materializationContextBindings[ (ParameterExpression)((MethodCallExpression)methodCallExpression.Arguments[0]).Object]; return Expression.Call( methodCallExpression.Method, valueBuffer, Expression.Constant(indexMap[property]), methodCallExpression.Arguments[2]); } return base.VisitMethodCall(methodCallExpression); } protected override Expression VisitExtension(Expression extensionExpression) { if (extensionExpression is ProjectionBindingExpression projectionBindingExpression) { var queryExpression = (InMemoryQueryExpression)projectionBindingExpression.QueryExpression; var projectionIndex = (int)GetProjectionIndex(queryExpression, projectionBindingExpression); var valueBuffer = queryExpression.CurrentParameter; return Expression.Call( EntityMaterializerSource.TryReadValueMethod.MakeGenericMethod(projectionBindingExpression.Type), valueBuffer, Expression.Constant(projectionIndex), Expression.Constant(InferPropertyFromInner(queryExpression.Projection[projectionIndex]), typeof(IPropertyBase))); } return base.VisitExtension(extensionExpression); } private IPropertyBase InferPropertyFromInner(Expression expression) { if (expression is MethodCallExpression methodCallExpression && methodCallExpression.Method.IsGenericMethod && methodCallExpression.Method.GetGenericMethodDefinition() == EntityMaterializerSource.TryReadValueMethod) { return (IPropertyBase)((ConstantExpression)methodCallExpression.Arguments[2]).Value; } return null; } private object GetProjectionIndex( InMemoryQueryExpression queryExpression, ProjectionBindingExpression projectionBindingExpression) { return projectionBindingExpression.ProjectionMember != null ? ((ConstantExpression)queryExpression.GetMappedProjection(projectionBindingExpression.ProjectionMember)).Value : (projectionBindingExpression.Index != null ? (object)projectionBindingExpression.Index : projectionBindingExpression.IndexMap); } } } }
51.050847
137
0.6416
[ "Apache-2.0" ]
Pankraty/EntityFrameworkCore
src/EFCore.InMemory/Query/Internal/InMemoryShapedQueryCompilingExpressionVisitor.InMemoryProjectionBindingRemovingExpressionVisitor.cs
6,024
C#
using Cobble.Core.Managers; using UnityEngine; namespace Cobble.SpyHunter.Player { [RequireComponent(typeof(ScoreHandler))] public class LifeHandler : MonoBehaviour { [Tooltip("The amount of time at once the player starts moving that the player has unlimited lives.")] public int LeadInCount = 1000; public int DecrementDelay = 10; public int MaxLives = 5; public int PointsForLife = 10000; [Tooltip("The number of extra cars that the player has.")] [SerializeField] private int _extraLives; private int _delayCount; private int _lastLifeScore = -1; [SerializeField] private ScoreHandler _scoreHandler; public int ExtraLives { get { return _extraLives; } } private void Start() { if (!_scoreHandler) _scoreHandler = GetComponent<ScoreHandler>(); } private void Update() { if (GameManager.Instance.IsPaused) return; if (LeadInCount > 0) { if (_delayCount >= DecrementDelay) { LeadInCount--; _delayCount = 0; } } else { if (_lastLifeScore == -1) { _lastLifeScore = _scoreHandler.PlayerScore; } else if (_scoreHandler.PlayerScore >= _lastLifeScore + PointsForLife){ AddLives(); _lastLifeScore = _scoreHandler.PlayerScore; } } _delayCount++; } public void AddLives(int amount = 1) { _extraLives = Mathf.Clamp(_extraLives + amount, 0, MaxLives); } public void RemoveLives(int amount = 1) { if (LeadInCount <= 0) _extraLives = Mathf.Clamp(_extraLives - amount, 0, MaxLives); } public bool HasExtraLife() { return LeadInCount > 0 || ExtraLives > 0; } } }
30.287879
109
0.547774
[ "MIT" ]
Cobbleopolis/SpyHunter
Assets/Scripts/Cobble/SpyHunter/Player/LifeHandler.cs
2,001
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _2.Practice_Integer_Numbers { class PracticeIntegerNumbers { static void Main(string[] args) { sbyte num1 = -100; byte num2 = 128; short num3 = -3540; ushort num4 = 64876; uint num5 = 2147483648; int num6 = -1141583228; long num7 = -1223372036854775808; Console.WriteLine(num1); Console.WriteLine(num2); Console.WriteLine(num3); Console.WriteLine(num4); Console.WriteLine(num5); Console.WriteLine(num6); Console.WriteLine(num7); } } }
24.774194
45
0.565104
[ "MIT" ]
msotiroff/Softuni-learning
Tech Module/Programming Fundamentals/HomeWorks/Data Types and Variables/2. Practice Integer Numbers/Program.cs
770
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using UnityEngine.Events; using UnityEngine.EventSystems; using UnityEngine.UI.CoroutineTween; // @cond doxygen ignore namespace UnityEngine.UI { /// <summary> /// <para>A standard dropdown that presents a list of options when clicked, of which one can be chosen.</para> /// </summary> //[AddComponentMenu("UI/Dropdown", 35), RequireComponent(typeof(RectTransform))] public class DropdownWithColor : Selectable, IEventSystemHandler, IPointerClickHandler, ISubmitHandler, ICancelHandler { protected internal class DropdownItem : MonoBehaviour, IEventSystemHandler, IPointerEnterHandler, ICancelHandler { [SerializeField] private Text m_Text; [SerializeField] private Image m_Image; [SerializeField] private RectTransform m_RectTransform; [SerializeField] private Toggle m_Toggle; public Text text { get { return this.m_Text; } set { this.m_Text = value; } } public Image image { get { return this.m_Image; } set { this.m_Image = value; } } public RectTransform rectTransform { get { return this.m_RectTransform; } set { this.m_RectTransform = value; } } public Toggle toggle { get { return this.m_Toggle; } set { this.m_Toggle = value; } } public virtual void OnPointerEnter(PointerEventData eventData) { EventSystem.current.SetSelectedGameObject(base.gameObject); } public virtual void OnCancel(BaseEventData eventData) { Dropdown componentInParent = base.GetComponentInParent<Dropdown>(); if (componentInParent) { componentInParent.Hide(); } } } /// <summary> /// <para>Class to store the text and/or image of a single option in the dropdown list.</para> /// </summary> [Serializable] public class OptionData { [SerializeField] private string m_Text; [SerializeField] private Sprite m_Image; [SerializeField] private Color m_Color; /// <summary> /// <para>The text associated with the option.</para> /// </summary> public string text { get { return this.m_Text; } set { this.m_Text = value; } } /// <summary> /// <para>The image associated with the option.</para> /// </summary> public Sprite image { get { return this.m_Image; } set { this.m_Image = value; } } /// <summary> /// <para>The color associated with the option.</para> /// </summary> public Color color { get { return this.m_Color; } set { this.m_Color = value; } } /// <summary> /// <para>Create an object representing a single option for the dropdown list.</para> /// </summary> public OptionData() { } /// <summary> /// <para>Create an object representing a single option for the dropdown list.</para> /// </summary> /// <param name="text">Optional text for the option.</param> public OptionData(string text) { this.text = text; } /// <summary> /// <para>Create an object representing a single option for the dropdown list.</para> /// </summary> /// <param name="image">Optional image for the option.</param> public OptionData(Sprite image) { this.image = image; } /// <summary> /// <para>Create an object representing a single option for the dropdown list.</para> /// </summary> /// <param name="color">Optional color for the option.</param> public OptionData(Color color) { this.color = color; } /// <summary> /// <para>Create an object representing a single option for the dropdown list.</para> /// </summary> /// <param name="text">Optional text for the option.</param> /// <param name="image">Optional image for the option.</param> public OptionData(string text, Sprite image) { this.text = text; this.image = image; } /// <summary> /// <para>Create an object representing a single option for the dropdown list.</para> /// </summary> /// <param name="text">Optional text for the option.</param> /// <param name="color">Optional color for the option.</param> public OptionData(string text, Color color) { this.text = text; this.color = color; } /// <summary> /// <para>Create an object representing a single option for the dropdown list.</para> /// </summary> /// <param name="image">Optional image for the option.</param> /// <param name="color">Optional color for the option.</param> public OptionData(Sprite image, Color color) { this.image = image; this.color = color; } /// <summary> /// <para>Create an object representing a single option for the dropdown list.</para> /// </summary> /// <param name="text">Optional text for the option.</param> /// <param name="image">Optional image for the option.</param> /// <param name="color">Optional color for the option.</param> public OptionData(string text, Sprite image, Color color) { this.text = text; this.image = image; this.color = color; } } /// <summary> /// <para>Class used internally to store the list of options for the dropdown list.</para> /// </summary> [Serializable] public class OptionDataList { [SerializeField] private List<DropdownWithColor.OptionData> m_Options; /// <summary> /// <para>The list of options for the dropdown list.</para> /// </summary> public List<DropdownWithColor.OptionData> options { get { return this.m_Options; } set { this.m_Options = value; } } public OptionDataList() { this.options = new List<DropdownWithColor.OptionData>(); } } /// <summary> /// <para>UnityEvent callback for when a dropdown current option is changed.</para> /// </summary> [Serializable] public class DropdownEvent : UnityEvent<int> { } [SerializeField] private RectTransform m_Template; [SerializeField] private Text m_CaptionText; [SerializeField] private Image m_CaptionImage; [SerializeField, Space] private Text m_ItemText; [SerializeField] private Image m_ItemImage; [SerializeField, Space] private int m_Value; [SerializeField, Space] private DropdownWithColor.OptionDataList m_Options = new DropdownWithColor.OptionDataList(); [SerializeField, Space] private DropdownWithColor.DropdownEvent m_OnValueChanged = new DropdownWithColor.DropdownEvent(); private GameObject m_Dropdown; private GameObject m_Blocker; private List<DropdownWithColor.DropdownItem> m_Items = new List<DropdownWithColor.DropdownItem>(); // private TweenRunner<FloatTween> m_AlphaTweenRunner; private bool validTemplate; private static DropdownWithColor.OptionData s_NoOptionData = new DropdownWithColor.OptionData(); /// <summary> /// <para>The Rect Transform of the template for the dropdown list.</para> /// </summary> public RectTransform template { get { return this.m_Template; } set { this.m_Template = value; this.RefreshShownValue(); } } /// <summary> /// <para>The Text component to hold the text of the currently selected option.</para> /// </summary> public Text captionText { get { return this.m_CaptionText; } set { this.m_CaptionText = value; this.RefreshShownValue(); } } /// <summary> /// <para>The Image component to hold the image of the currently selected option.</para> /// </summary> public Image captionImage { get { return this.m_CaptionImage; } set { this.m_CaptionImage = value; this.RefreshShownValue(); } } /// <summary> /// <para>The Text component to hold the text of the item.</para> /// </summary> public Text itemText { get { return this.m_ItemText; } set { this.m_ItemText = value; this.RefreshShownValue(); } } /// <summary> /// <para>The Image component to hold the image of the item.</para> /// </summary> public Image itemImage { get { return this.m_ItemImage; } set { this.m_ItemImage = value; this.RefreshShownValue(); } } /// <summary> /// <para>The list of possible options. A text string and an image can be specified for each option.</para> /// </summary> public List<DropdownWithColor.OptionData> options { get { return this.m_Options.options; } set { this.m_Options.options = value; this.RefreshShownValue(); } } /// <summary> /// <para>A UnityEvent that is invoked when when a user has clicked one of the options in the dropdown list.</para> /// </summary> public DropdownWithColor.DropdownEvent onValueChanged { get { return this.m_OnValueChanged; } set { this.m_OnValueChanged = value; } } /// <summary> /// <para>The index of the currently selected option. 0 is the first option, 1 is the second, and so on.</para> /// </summary> public int value { get { return this.m_Value; } set { if (Application.isPlaying && (value == this.m_Value || this.options.Count == 0)) { return; } this.m_Value = Mathf.Clamp(value, 0, this.options.Count - 1); this.RefreshShownValue(); this.m_OnValueChanged.Invoke(this.m_Value); } } protected DropdownWithColor() { } protected override void Awake() { if (!Application.isPlaying) { return; } //this.m_AlphaTweenRunner = new TweenRunner<FloatTween>(); //this.m_AlphaTweenRunner.Init(this); if (this.m_CaptionImage) { this.m_CaptionImage.enabled = (this.m_CaptionImage.sprite != null); } if (this.m_Template) { this.m_Template.gameObject.SetActive(false); } } #if UNITY_EDITOR protected new void OnValidate() { //This doesn't work on WebGL as there is no OnValidate in Selectable on that platform base.OnValidate(); if (!this.IsActive()) { return; } this.RefreshShownValue(); } #endif /// <summary> /// <para>Refreshes the text and image (if available) of the currently selected option. /// /// If you have modified the list of options, you should call this method afterwards to ensure that the visual state of the dropdown corresponds to the updated options.</para> /// </summary> public void RefreshShownValue() { DropdownWithColor.OptionData optionData = DropdownWithColor.s_NoOptionData; if (this.options.Count > 0) { optionData = this.options[Mathf.Clamp(this.m_Value, 0, this.options.Count - 1)]; } if (this.m_CaptionText) { if (optionData != null && optionData.text != null) { this.m_CaptionText.text = optionData.text; } else { this.m_CaptionText.text = string.Empty; } } if (this.m_CaptionImage) { if (optionData != null) { this.m_CaptionImage.sprite = optionData.image; this.m_CaptionImage.color = optionData.color; } else { this.m_CaptionImage.sprite = null; } this.m_CaptionImage.enabled = (this.m_CaptionImage.sprite != null); } } public void AddOptions(List<DropdownWithColor.OptionData> options) { this.options.AddRange(options); this.RefreshShownValue(); } public void AddOptions(List<string> options) { for (int i = 0; i < options.Count; i++) { this.options.Add(new DropdownWithColor.OptionData(options[i])); } this.RefreshShownValue(); } public void AddOptions(List<Sprite> options) { for (int i = 0; i < options.Count; i++) { this.options.Add(new DropdownWithColor.OptionData(options[i])); } this.RefreshShownValue(); } /// <summary> /// <para>Clear the list of options in the DropdownWithColor.</para> /// </summary> public void ClearOptions() { this.options.Clear(); this.RefreshShownValue(); } private void SetupTemplate() { this.validTemplate = false; if (!this.m_Template) { Debug.LogError("The dropdown template is not assigned. The template needs to be assigned and must have a child GameObject with a Toggle component serving as the item.", this); return; } GameObject gameObject = this.m_Template.gameObject; gameObject.SetActive(true); Toggle componentInChildren = this.m_Template.GetComponentInChildren<Toggle>(); this.validTemplate = true; if (!componentInChildren || componentInChildren.transform == this.template) { this.validTemplate = false; Debug.LogError("The dropdown template is not valid. The template must have a child GameObject with a Toggle component serving as the item.", this.template); } else if (!(componentInChildren.transform.parent is RectTransform)) { this.validTemplate = false; Debug.LogError("The dropdown template is not valid. The child GameObject with a Toggle component (the item) must have a RectTransform on its parent.", this.template); } else if (this.itemText != null && !this.itemText.transform.IsChildOf(componentInChildren.transform)) { this.validTemplate = false; Debug.LogError("The dropdown template is not valid. The Item Text must be on the item GameObject or children of it.", this.template); } else if (this.itemImage != null && !this.itemImage.transform.IsChildOf(componentInChildren.transform)) { this.validTemplate = false; Debug.LogError("The dropdown template is not valid. The Item Image must be on the item GameObject or children of it.", this.template); } if (!this.validTemplate) { gameObject.SetActive(false); return; } DropdownWithColor.DropdownItem dropdownItem = componentInChildren.gameObject.AddComponent<DropdownWithColor.DropdownItem>(); dropdownItem.text = this.m_ItemText; dropdownItem.image = this.m_ItemImage; dropdownItem.toggle = componentInChildren; dropdownItem.rectTransform = (RectTransform)componentInChildren.transform; Canvas orAddComponent = DropdownWithColor.GetOrAddComponent<Canvas>(gameObject); orAddComponent.overrideSorting = true; orAddComponent.sortingOrder = 30000; DropdownWithColor.GetOrAddComponent<GraphicRaycaster>(gameObject); DropdownWithColor.GetOrAddComponent<CanvasGroup>(gameObject); gameObject.SetActive(false); this.validTemplate = true; } private static T GetOrAddComponent<T>(GameObject go) where T : Component { T t = go.GetComponent<T>(); if (!t) { t = go.AddComponent<T>(); } return t; } /// <summary> /// <para>Handling for when the dropdown is 'clicked'.</para> /// </summary> /// <param name="eventData">Current event.</param> public virtual void OnPointerClick(PointerEventData eventData) { this.Show(); } /// <summary> /// <para>What to do when the event system sends a submit Event.</para> /// </summary> /// <param name="eventData">Current event.</param> public virtual void OnSubmit(BaseEventData eventData) { this.Show(); } /// <summary> /// <para>Called by a BaseInputModule when a Cancel event occurs.</para> /// </summary> /// <param name="eventData"></param> public virtual void OnCancel(BaseEventData eventData) { this.Hide(); } /// <summary> /// <para>Show the dropdown list.</para> /// </summary> public void Show() { if (!this.IsActive() || !this.IsInteractable() || this.m_Dropdown != null) { return; } if (!this.validTemplate) { this.SetupTemplate(); if (!this.validTemplate) { return; } } List<Canvas> list = MyListPool<Canvas>.Get(); base.gameObject.GetComponentsInParent<Canvas>(false, list); if (list.Count == 0) { return; } Canvas canvas = list[0]; MyListPool<Canvas>.Release(list); this.m_Template.gameObject.SetActive(true); this.m_Dropdown = this.CreateDropdownList(this.m_Template.gameObject); this.m_Dropdown.name = "Dropdown List"; this.m_Dropdown.SetActive(true); RectTransform rectTransform = this.m_Dropdown.transform as RectTransform; rectTransform.SetParent(this.m_Template.transform.parent, false); DropdownWithColor.DropdownItem componentInChildren = this.m_Dropdown.GetComponentInChildren<DropdownWithColor.DropdownItem>(); GameObject gameObject = componentInChildren.rectTransform.parent.gameObject; RectTransform rectTransform2 = gameObject.transform as RectTransform; componentInChildren.rectTransform.gameObject.SetActive(true); Rect rect = rectTransform2.rect; Rect rect2 = componentInChildren.rectTransform.rect; Vector2 vector = rect2.min - rect.min + (Vector2)componentInChildren.rectTransform.localPosition; Vector2 vector2 = rect2.max - rect.max + (Vector2)componentInChildren.rectTransform.localPosition; Vector2 size = rect2.size; this.m_Items.Clear(); Toggle toggle = null; for (int i = 0; i < this.options.Count; i++) { DropdownWithColor.OptionData data = this.options[i]; DropdownWithColor.DropdownItem item = this.AddItem(data, this.value == i, componentInChildren, this.m_Items); if (!(item == null)) { item.toggle.isOn = (this.value == i); item.toggle.onValueChanged.AddListener(delegate (bool x) { this.OnSelectItem(item.toggle); }); if (item.toggle.isOn) { item.toggle.Select(); } if (toggle != null) { Navigation navigation = toggle.navigation; Navigation navigation2 = item.toggle.navigation; navigation.mode = Navigation.Mode.Explicit; navigation2.mode = Navigation.Mode.Explicit; navigation.selectOnDown = item.toggle; navigation.selectOnRight = item.toggle; navigation2.selectOnLeft = toggle; navigation2.selectOnUp = toggle; toggle.navigation = navigation; item.toggle.navigation = navigation2; } toggle = item.toggle; } } Vector2 sizeDelta = rectTransform2.sizeDelta; sizeDelta.y = size.y * (float)this.m_Items.Count + vector.y - vector2.y; rectTransform2.sizeDelta = sizeDelta; float num = rectTransform.rect.height - rectTransform2.rect.height; if (num > 0f) { rectTransform.sizeDelta = new Vector2(rectTransform.sizeDelta.x, rectTransform.sizeDelta.y - num); } Vector3[] array = new Vector3[4]; rectTransform.GetWorldCorners(array); RectTransform rectTransform3 = canvas.transform as RectTransform; Rect rect3 = rectTransform3.rect; for (int j = 0; j < 2; j++) { bool flag = false; for (int k = 0; k < 4; k++) { Vector3 vector3 = rectTransform3.InverseTransformPoint(array[k]); if (vector3[j] < rect3.min[j] || vector3[j] > rect3.max[j]) { flag = true; break; } } if (flag) { RectTransformUtility.FlipLayoutOnAxis(rectTransform, j, false, false); } } for (int l = 0; l < this.m_Items.Count; l++) { RectTransform rectTransform4 = this.m_Items[l].rectTransform; rectTransform4.anchorMin = new Vector2(rectTransform4.anchorMin.x, 0f); rectTransform4.anchorMax = new Vector2(rectTransform4.anchorMax.x, 0f); rectTransform4.anchoredPosition = new Vector2(rectTransform4.anchoredPosition.x, vector.y + size.y * (float)(this.m_Items.Count - 1 - l) + size.y * rectTransform4.pivot.y); rectTransform4.sizeDelta = new Vector2(rectTransform4.sizeDelta.x, size.y); } //this.AlphaFadeList(0.15f, 0f, 1f); this.m_Template.gameObject.SetActive(false); componentInChildren.gameObject.SetActive(false); this.m_Blocker = this.CreateBlocker(canvas); } /// <summary> /// <para>Override this method to implement a different way to obtain a blocker GameObject.</para> /// </summary> /// <param name="rootCanvas">The root canvas the dropdown is under.</param> /// <returns> /// <para>The obtained blocker.</para> /// </returns> protected virtual GameObject CreateBlocker(Canvas rootCanvas) { GameObject gameObject = new GameObject("Blocker"); RectTransform rectTransform = gameObject.AddComponent<RectTransform>(); rectTransform.SetParent(rootCanvas.transform, false); rectTransform.anchorMin = Vector3.zero; rectTransform.anchorMax = Vector3.one; rectTransform.sizeDelta = Vector2.zero; Canvas canvas = gameObject.AddComponent<Canvas>(); canvas.overrideSorting = true; Canvas component = this.m_Dropdown.GetComponent<Canvas>(); canvas.sortingLayerID = component.sortingLayerID; canvas.sortingOrder = component.sortingOrder - 1; gameObject.AddComponent<GraphicRaycaster>(); Image image = gameObject.AddComponent<Image>(); image.color = Color.clear; Button button = gameObject.AddComponent<Button>(); button.onClick.AddListener(new UnityAction(this.Hide)); return gameObject; } /// <summary> /// <para>Override this method to implement a different way to dispose of a blocker GameObject that blocks clicks to other controls while the dropdown list is open.</para> /// </summary> /// <param name="blocker">The blocker to dispose of.</param> protected virtual void DestroyBlocker(GameObject blocker) { Object.Destroy(blocker); } /// <summary> /// <para>Override this method to implement a different way to obtain a dropdown list GameObject.</para> /// </summary> /// <param name="template">The template to create the dropdown list from.</param> /// <returns> /// <para>The obtained dropdown list.</para> /// </returns> protected virtual GameObject CreateDropdownList(GameObject template) { return Object.Instantiate<GameObject>(template); } /// <summary> /// <para>Override this method to implement a different way to dispose of a dropdown list GameObject.</para> /// </summary> /// <param name="dropdownList">The dropdown list to dispose of.</param> protected virtual void DestroyDropdownList(GameObject dropdownList) { Object.Destroy(dropdownList); } protected virtual DropdownWithColor.DropdownItem CreateItem(DropdownWithColor.DropdownItem itemTemplate) { return Object.Instantiate<DropdownWithColor.DropdownItem>(itemTemplate); } protected virtual void DestroyItem(DropdownWithColor.DropdownItem item) { } private DropdownWithColor.DropdownItem AddItem(DropdownWithColor.OptionData data, bool selected, DropdownWithColor.DropdownItem itemTemplate, List<DropdownWithColor.DropdownItem> items) { DropdownWithColor.DropdownItem dropdownItem = this.CreateItem(itemTemplate); dropdownItem.rectTransform.SetParent(itemTemplate.rectTransform.parent, false); dropdownItem.gameObject.SetActive(true); dropdownItem.gameObject.name = "Item " + items.Count + ((data.text == null) ? string.Empty : (": " + data.text)); if (dropdownItem.toggle != null) { dropdownItem.toggle.isOn = false; } if (dropdownItem.text) { dropdownItem.text.text = data.text; } if (dropdownItem.image) { dropdownItem.image.sprite = data.image; dropdownItem.image.enabled = (dropdownItem.image.sprite != null); dropdownItem.image.color = data.color; } items.Add(dropdownItem); return dropdownItem; } /*private void AlphaFadeList(float duration, float alpha) { CanvasGroup component = this.m_Dropdown.GetComponent<CanvasGroup>(); this.AlphaFadeList(duration, component.alpha, alpha); } private void AlphaFadeList(float duration, float start, float end) { if (end.Equals(start)) { return; } FloatTween info = new FloatTween { duration = duration, startValue = start, targetValue = end }; info.AddOnChangedCallback(new UnityAction<float>(this.SetAlpha)); info.ignoreTimeScale = true; this.m_AlphaTweenRunner.StartTween(info); } private void SetAlpha(float alpha) { if (!this.m_Dropdown) { return; } CanvasGroup component = this.m_Dropdown.GetComponent<CanvasGroup>(); component.alpha = alpha; }*/ /// <summary> /// <para>Hide the dropdown list.</para> /// </summary> public void Hide() { if (this.m_Dropdown != null) { //this.AlphaFadeList(0.15f, 0f); base.StartCoroutine(this.DelayedDestroyDropdownList(0.15f)); } if (this.m_Blocker != null) { this.DestroyBlocker(this.m_Blocker); } this.m_Blocker = null; this.Select(); } [DebuggerHidden] private IEnumerator DelayedDestroyDropdownList(float delay) { /*Dropdown.< DelayedDestroyDropdownList > c__Iterator2 < DelayedDestroyDropdownList > c__Iterator = new Dropdown.< DelayedDestroyDropdownList > c__Iterator2(); < DelayedDestroyDropdownList > c__Iterator.delay = delay; < DelayedDestroyDropdownList > c__Iterator.<$> delay = delay; < DelayedDestroyDropdownList > c__Iterator.<> f__this = this; return < DelayedDestroyDropdownList > c__Iterator;*/ yield return new WaitForSeconds(delay); DestroyDropdownList(this.m_Dropdown); } private void OnSelectItem(Toggle toggle) { if (!toggle.isOn) { toggle.isOn = true; } int num = -1; Transform transform = toggle.transform; Transform parent = transform.parent; for (int i = 0; i < parent.childCount; i++) { if (parent.GetChild(i) == transform) { num = i - 1; break; } } if (num < 0) { return; } this.value = num; this.Hide(); } } } // @endcond
35.552575
193
0.516674
[ "MIT" ]
Minamiyama/UMA
UMAProject/Assets/UMA/Examples/Extensions Examples/DynamicCharacterSystem/Scripts/Scene2and3/DropdownWithColor.cs
33,137
C#
using System.Collections.Generic; using System.Linq; namespace IdentityServerAngular.Domain.Common { // Learn more: https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/implement-value-objects public abstract class ValueObject { protected static bool EqualOperator(ValueObject left, ValueObject right) { if (left is null ^ right is null) { return false; } return left?.Equals(right) != false; } protected static bool NotEqualOperator(ValueObject left, ValueObject right) { return !(EqualOperator(left, right)); } protected abstract IEnumerable<object> GetEqualityComponents(); public override bool Equals(object obj) { if (obj == null || obj.GetType() != GetType()) { return false; } var other = (ValueObject)obj; return GetEqualityComponents().SequenceEqual(other.GetEqualityComponents()); } public override int GetHashCode() { return GetEqualityComponents() .Select(x => x != null ? x.GetHashCode() : 0) .Aggregate((x, y) => x ^ y); } } }
29.311111
149
0.576194
[ "MIT" ]
Diana1997/IdentityServerAngular
src/Domain/Common/ValueObject.cs
1,321
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace WinformsControlsTest { partial class ScalingBeforeChanges { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.checkBox1 = new WinformsControlsTest.MyCheckBox(); this.SuspendLayout(); // // checkBox1 // this.checkBox1.AutoSize = true; this.checkBox1.Location = new System.Drawing.Point(39, 73); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(80, 17); this.checkBox1.TabIndex = 0; this.checkBox1.Text = "checkBox1"; this.checkBox1.UseVisualStyleBackColor = true; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.ClientSize = new System.Drawing.Size(284, 261); this.Controls.Add(this.checkBox1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private MyCheckBox checkBox1; } }
34.015385
107
0.570782
[ "MIT" ]
15835229565/winforms-1
src/System.Windows.Forms/tests/IntegrationTests/WinformsControlsTest/ScalingBeforeChanges.Designer.cs
2,213
C#
/** * Copyright (c) 2008-2020 Bryan Biedenkapp., All Rights Reserved. * MIT Open Source. Use is subject to license terms. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. */ /* * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // // Based on code from the C# WebServer project. (http://webserver.codeplex.com/) // Copyright (c) 2012 Jonas Gauffin // Licensed under the Apache 2.0 License (http://opensource.org/licenses/Apache-2.0) // using System; namespace TridentFramework.RPC.Http.HttpMessages.Parser { /// <summary> /// A response have been received. /// </summary> public class FactoryResponseEventArgs : EventArgs { /* ** Properties */ /// <summary> /// Gets or sets response. /// </summary> public IResponse Response { get; private set; } /* ** Methods */ /// <summary> /// Initializes a new instance of the <see cref="FactoryResponseEventArgs"/> class. /// </summary> /// <param name="response">The response.</param> public FactoryResponseEventArgs(IResponse response) { Response = response; } } // public class FactoryResponseEventArgs : EventArgs } // namespace TridentFramework.RPC.Http.HttpMessages.Parser
42.218182
208
0.693798
[ "MIT" ]
gatekeep/Trident.RPC
Http/HttpMessages/Parser/FactoryResponseEventArgs.cs
2,322
C#
// ----------------------------------------------------------------------- // <copyright file="PartitionConfig.cs" company="Asynkron AB"> // Copyright (C) 2015-2022 Asynkron AB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; namespace Proto.Cluster.Partition { public record PartitionConfig( bool DeveloperLogging, int HandoverChunkSize, TimeSpan RebalanceRequestTimeout, PartitionIdentityLookup.Mode Mode = PartitionIdentityLookup.Mode.Pull, PartitionIdentityLookup.Send Send = PartitionIdentityLookup.Send.Full ); }
38.117647
78
0.561728
[ "Apache-2.0" ]
rickevry/protoactor-dotnet
src/Proto.Cluster/Partition/PartitionConfig.cs
648
C#
// Descending Ticks // ScottPlot will always display data where X values ascend from left to right. To simulate an inverted axis (where numbers decrease from left to right) plot data in the negative space, then invert the sign of tick labels. var plt = new ScottPlot.Plot(600, 400); // plot the positive data in the negative space double[] values = DataGen.Sin(50); var sig = plt.AddSignal(values); sig.OffsetX = -50; // then invert the sign of the axis tick labels plt.XAxis.TickLabelNotation(invertSign: true); plt.YAxis.TickLabelNotation(invertSign: true); plt.SaveFig("ticks_descending.png");
42.785714
222
0.767947
[ "MIT" ]
bclehmann/Website
src/cookbooks/4.1.4-beta/source/ticks_descending.cs
599
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Skinning { public class LegacyManiaSkinConfigurationLookup { public readonly int Keys; public readonly LegacyManiaSkinConfigurationLookups Lookup; public readonly int? TargetColumn; public LegacyManiaSkinConfigurationLookup(int keys, LegacyManiaSkinConfigurationLookups lookup, int? targetColumn = null) { Keys = keys; Lookup = lookup; TargetColumn = targetColumn; } } public enum LegacyManiaSkinConfigurationLookups { ColumnWidth, ColumnSpacing, LightImage, LeftLineWidth, RightLineWidth, HitPosition, LightPosition, HitTargetImage, ShowJudgementLine, KeyImage, KeyImageDown, NoteImage, HoldNoteHeadImage, HoldNoteTailImage, HoldNoteBodyImage, ExplosionImage, ExplosionScale, ColumnLineColour, JudgementLineColour, ColumnBackgroundColour, ColumnLightColour, MinimumColumnWidth, LeftStageImage, RightStageImage, BottomStageImage, Hit300g, Hit300, Hit200, Hit100, Hit50, Hit0, } }
26.563636
130
0.599589
[ "MIT" ]
HDragonHR/osu
osu.Game/Skinning/LegacyManiaSkinConfigurationLookup.cs
1,407
C#
namespace api.Models { public class UrlToken { public int ID { get; set; } public string RandomGeneratedString { get; set; } // ID reference of the subscriber public int Subscriber { get; set; } } }
24.2
57
0.595041
[ "MIT" ]
AmineAML/thermopolia-api
api/Models/UrlToken.cs
242
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FractalWorkbench.Explorer { public partial class MainWindow : Form { public MainWindow() { InitializeComponent(); var fractal = new JuliaSet.JuliSetFractal(new System.Numerics.Complex(-0.70176, -0.3842)); var fractalImage = new FractalImage(fractal); Controls.Add(fractalImage); fractalImage.Dock = DockStyle.Fill; } } }
24.769231
102
0.675466
[ "MIT" ]
lukebuehler/FractalWorkbench
Src/FractalWorkbench.Explorer/MainWindow.cs
646
C#
using Scalar.Tests.Should; using System.Diagnostics; using System.IO; namespace Scalar.FunctionalTests.Tools { public class ScalarProcess { private const int SuccessExitCode = 0; private const int ExitCodeShouldNotBeZero = -1; private const int DoNotCheckExitCode = -2; private readonly string pathToScalar; private readonly string enlistmentRoot; private readonly string localCacheRoot; public ScalarProcess(ScalarFunctionalTestEnlistment enlistment) : this(ScalarTestConfig.PathToScalar, enlistment.EnlistmentRoot, Path.Combine(enlistment.EnlistmentRoot, ".scalarCache")) { } public ScalarProcess(string pathToScalar, string enlistmentRoot, string localCacheRoot) { this.pathToScalar = pathToScalar; this.enlistmentRoot = enlistmentRoot; this.localCacheRoot = localCacheRoot; } public void Clone(string repositorySource, string branchToCheckout, bool skipFetchCommitsAndTrees, bool fullClone = true) { // TODO: consider sparse clone for functional tests string args = string.Format( "clone \"{0}\" \"{1}\" {2} --branch \"{3}\" --local-cache-path \"{4}\" {5}", repositorySource, this.enlistmentRoot, fullClone ? "--full-clone" : string.Empty, branchToCheckout, this.localCacheRoot, skipFetchCommitsAndTrees ? "--no-fetch-commits-and-trees" : string.Empty); this.CallScalar(args, expectedExitCode: SuccessExitCode); } public string RunVerb(string task, long? batchSize = null, bool failOnError = true, bool asService = false) { string batchArg = batchSize == null ? string.Empty : $"--batch-size={batchSize}"; string serviceArg = asService ? "{\"StartedByService\":\"true\"}" : null; return this.CallScalar( $"run {task} \"{this.enlistmentRoot}\" {batchArg}", failOnError ? SuccessExitCode : DoNotCheckExitCode, standardInput: null, internalParameter: serviceArg); } public void Repair(bool confirm) { string confirmArg = confirm ? "--confirm " : string.Empty; this.CallScalar( "repair " + confirmArg + "\"" + this.enlistmentRoot + "\"", expectedExitCode: SuccessExitCode); } public string Register(string enlistmentRoot) { return this.CallScalar($"register", expectedExitCode: SuccessExitCode, workingDirectory: enlistmentRoot); } public string Unregister(string enlistmentRoot) { return this.CallScalar($"unregister", expectedExitCode: SuccessExitCode, workingDirectory: enlistmentRoot); } public string ListRepos() { return this.CallScalar($"list", expectedExitCode: SuccessExitCode, workingDirectory: this.enlistmentRoot); } public string Diagnose() { return this.CallScalar("diagnose \"" + this.enlistmentRoot + "\""); } public string Status(string trace = null) { return this.CallScalar("status " + this.enlistmentRoot, trace: trace); } public string CacheServer(string args) { return this.CallScalar("cache-server " + args + " \"" + this.enlistmentRoot + "\""); } public string RunServiceVerb(string argument) { return this.CallScalar("service " + argument, expectedExitCode: SuccessExitCode); } public string ReadConfig(string key, bool failOnError) { return this.CallScalar($"config {key}", failOnError ? SuccessExitCode : DoNotCheckExitCode).TrimEnd('\r', '\n'); } public void WriteConfig(string key, string value) { this.CallScalar($"config {key} {value}", expectedExitCode: SuccessExitCode); } public void DeleteConfig(string key) { this.CallScalar($"config --delete {key}", expectedExitCode: SuccessExitCode); } /// <summary> /// Invokes a call to scalar using the arguments specified /// </summary> /// <param name="args">The arguments to use when invoking scalar</param> /// <param name="expectedExitCode"> /// What the expected exit code should be. /// >= than 0 to check the exit code explicitly /// -1 = Fail if the exit code is 0 /// -2 = Do not check the exit code (Default) /// </param> /// <param name="trace">What to set the GIT_TRACE environment variable to</param> /// <param name="standardInput">What to write to the standard input stream</param> /// <param name="internalParameter">The internal parameter to set in the arguments</param> /// <returns></returns> private string CallScalar( string args, int expectedExitCode = DoNotCheckExitCode, string trace = null, string standardInput = null, string internalParameter = null, string workingDirectory = null) { ProcessStartInfo processInfo = new ProcessStartInfo(this.pathToScalar); if (internalParameter == null) { internalParameter = ScalarHelpers.GetInternalParameter(); } processInfo.Arguments = args + " " + TestConstants.InternalUseOnlyFlag + " " + internalParameter; if (!string.IsNullOrEmpty(workingDirectory)) { processInfo.WorkingDirectory = workingDirectory; } processInfo.WindowStyle = ProcessWindowStyle.Hidden; processInfo.UseShellExecute = false; processInfo.RedirectStandardOutput = true; if (standardInput != null) { processInfo.RedirectStandardInput = true; } if (trace != null) { processInfo.EnvironmentVariables["GIT_TRACE"] = trace; } if (!string.IsNullOrEmpty(workingDirectory)) { processInfo.WorkingDirectory = workingDirectory; } using (Process process = Process.Start(processInfo)) { if (standardInput != null) { process.StandardInput.Write(standardInput); process.StandardInput.Close(); } string result = process.StandardOutput.ReadToEnd(); process.WaitForExit(); if (expectedExitCode >= SuccessExitCode) { process.ExitCode.ShouldEqual(expectedExitCode, result); } else if (expectedExitCode == ExitCodeShouldNotBeZero) { process.ExitCode.ShouldNotEqual(SuccessExitCode, "Exit code should not be zero"); } return result; } } } }
37.71066
133
0.561718
[ "MIT" ]
Bhaskers-Blu-Org2/scalar
Scalar.FunctionalTests/Tools/ScalarProcess.cs
7,429
C#
using System; using System.Collections.Generic; using System.Text; namespace Mixins.Method2 { /// <summary> /// Implement mixins using extension methods, empty interfaces, /// and the ConditionalWeakTable to manage state. /// </summary> /// <remarks> /// Based on the example I found here: http://www.c-sharpcorner.com/UploadFile/b942f9/how-to-create-mixin-using-C-Sharp-4-0/ /// </remarks> public static class Program { public static void Main() { var h = new Human("Jim"); h.SetBirthDate(new DateTime(1980, 1, 1)); Console.WriteLine("Name {0}, Age = {1}", h.Name, h.GetAge()); var h2 = new Human("Fred"); h2.SetBirthDate(new DateTime(1960, 6, 1)); Console.WriteLine("Name {0}, Age = {1}", h2.Name, h2.GetAge()); Console.ReadKey(); } } }
27.785714
125
0.663239
[ "MIT" ]
treytomes/ILExperiments
Mixins/Method2/Program.cs
780
C#
using RepairsApi.V2.Configuration; using System.Threading.Tasks; namespace RepairsApi.V2.UseCase.Interfaces { public interface IGetFilterUseCase { Task<ModelFilterConfiguration> Execute(string modelName); } }
20.909091
65
0.76087
[ "MIT" ]
LBHackney-IT/repairs-api-dotnet
RepairsApi/V2/UseCase/Interfaces/IGetFilterUseCase.cs
230
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Calabonga.Chat.WinFormClient { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
24.666667
65
0.631757
[ "MIT" ]
Calabonga/SignalRChat
Calabonga.Chat.WinFormClient/Calabonga.Chat.WinFormClient/Program.cs
592
C#
using System; using System.Collections.Generic; using System.Linq; namespace _03._Legendary_Farming { class Program { static void Main(string[] args) { ReceiveKeyMaterials(); } static void ReceiveKeyMaterials() { Dictionary<string, int> materials = new Dictionary<string, int>(); SortedDictionary<string, int> junks = new SortedDictionary<string, int>(); materials.Add("fragments", 0); materials.Add("shards", 0); materials.Add("motes", 0); while (true) { string[] material = Console.ReadLine() .Split(" ", StringSplitOptions.RemoveEmptyEntries) .Select(x => x.ToLowerInvariant()) .ToArray(); for (int i = 0; i < material.Length; i += 2) { string product = material[i + 1]; int quantity = int.Parse(material[i]); if (product == "fragments" || product == "shards" || product == "motes") { if (materials.ContainsKey(product)) { materials[product] += quantity; } } else { if (junks.ContainsKey(product)) { junks[product] += quantity; } else { junks.Add(product, quantity); } } string legendaryItem = ReturnLegendaryItem(materials); if (legendaryItem != "") { materials[legendaryItem] -= 250; legendaryItem = legendaryItem == "fragments" ? "Valanyr" : legendaryItem == "shards" ? "Shadowmourne" : "Dragonwrath"; Console.WriteLine($"{legendaryItem} obtained!"); PrintResult(materials, junks); return; } } } } static string ReturnLegendaryItem(Dictionary<string, int> dictOfMaterials) { foreach (var item in dictOfMaterials) { if (dictOfMaterials[item.Key] >= 250) { return item.Key; } } return ""; } static void PrintResult(Dictionary<string, int> materials, SortedDictionary<string, int> junks) { var orderList = materials.OrderByDescending(x => x.Value) .ThenBy(x => x.Key); foreach (var item in orderList) { Console.WriteLine($"{item.Key}: {item.Value}"); } foreach (var item in junks) { Console.WriteLine($"{item.Key}: {item.Value}"); } } } }
34.411111
142
0.426219
[ "MIT" ]
PetroslavGochev/CSharpFundamentalModule
07.Associative Arrays/Associative Arrays - Exercise/03. Legendary Farming/Program.cs
3,099
C#
using System; using System.Collections.Generic; using FM.LiveSwitch; using FM.LiveSwitch.Sdp; namespace MITM { public class Mixer { List<(string, VideoTrack)> tracks; private string _activeTrack = string.Empty; private NullVideoSource _activeSource = null; private NullVideoSink _activeSink = null; public void AddTrack(string name, VideoTrack track) { tracks.Add((name, track)); if (tracks.Count == 1) { SetInput(track); } } public void RemoveTrack(string name) { if (String.Equals(name, _activeTrack, StringComparison.OrdinalIgnoreCase)) { throw new Exception("You can not remove the active track."); } for (int i = 0, l = tracks.Count; i < l; i++) { var track = tracks[i]; if (String.Equals(track.Item1, name, StringComparison.OrdinalIgnoreCase)) { tracks.Remove(track); } } } public VideoTrack GetTrackByName(string name) { for (int i = 0, l = tracks.Count; i < l; i++) { var track = tracks[i]; if (String.Equals(track.Item1, name, StringComparison.OrdinalIgnoreCase)) { return track.Item2; } } return default(VideoTrack); } public void SetOutput(VideoTrack track) { SetOutput((NullVideoSource)track.Source); } public void SetOutput(NullVideoSource source) { _activeSource = source; } public void SetInput(NullVideoSink sink) { // Dewire the existing events. if (_activeSink != null) { _activeSink.OnProcessFrame -= ProcessFrame; } _activeSink = sink; _activeSink.OnProcessFrame += ProcessFrame; _needsKeyFrame = true; } public void SetInput(string name) { if (name == _activeTrack) { return; } var track = GetTrackByName(name); if (track != null) { SetInput((NullVideoSink)track.Sink); } } public bool _needsKeyFrame = false; public void ProcessFrame(VideoFrame frame) { if (_needsKeyFrame) { ((FM.LiveSwitch.Vp8.Encoder)_activeSource.Output).ForceKeyFrame = true; _needsKeyFrame = false; } if (_activeSource != null) { _activeSource.ProcessFrame(frame); } } public void SetInput(VideoTrack track) { if (track != null) { SetInput((NullVideoSink)track.Sink); } } public Mixer() { tracks = new List<(string, VideoTrack)>(); } } }
25.569106
89
0.481717
[ "MIT" ]
jakesteele/LiveSwitch-Video-Switcher
Mixer.cs
3,147
C#
#region -- copyright -- // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // #endregion using System; using System.Collections.Generic; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Neo.IronLua { public sealed class LuaTaskFactory : ITaskFactory { private LuaChunk task = null; private TaskPropertyInfo[] taskProperties = null; public bool Initialize(string taskName, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) { var log = new TaskLoggingHelper(taskFactoryLoggingHost, taskName); // We use the property group for the declaration taskProperties = (from c in parameterGroup select c.Value).ToArray(); // Compile chunk try { log.LogMessage("Compile script."); task = Lua.CompileChunk(taskBody, taskName, Lua.StackTraceCompileOptions, new KeyValuePair<string, Type>("engine", typeof(IBuildEngine)), new KeyValuePair<string, Type>("log", typeof(TaskLoggingHelper)) ); return true; } catch (LuaParseException e) { log.LogError("{0} (at line {1},{2})", e.Message, taskName, e.Line); return false; } } // func Initialize public ITask CreateTask(IBuildEngine taskFactoryLoggingHost) => new LuaTask(task); public void CleanupTask(ITask task) => ((LuaTask)task).Dispose(); public TaskPropertyInfo[] GetTaskParameters() => taskProperties; public string FactoryName => typeof(LuaTaskFactory).Name; public Type TaskType => typeof(LuaTask); public static Lua Lua { get; } = new Lua(); } // class LuaTaskFactory }
33.175676
150
0.709165
[ "Apache-2.0" ]
ShadowMarker789/neolua
NeoLua.MSBuild/LuaTaskFactory.cs
2,457
C#
/* * * 文件名 :ModuleAttribute * 程序说明 : 模块特性,标记该特性表示属于应用模块的部分 * 更新时间 : 2020-06-01 21:50 * 联系作者 : QQ:779149549 * 开发者群 : QQ群:874752819 * 邮件联系 : zhouhaogg789@outlook.com * 视频教程 : https://space.bilibili.com/32497462 * 博客地址 : https://www.cnblogs.com/zh7791/ * 项目地址 : https://github.com/HenJigg/WPF-Xamarin-Blazor-Examples * 项目说明 : 以上所有代码均属开源免费使用,禁止个人行为出售本项目源代码 */ namespace Consumption.Shared.Common.Attributes { using Consumption.Shared.Common.Enums; using System; /// <summary> /// 模块特性, 标记该特性表示属于应用模块的部分 /// </summary> [AttributeUsage(AttributeTargets.Class)] public class ModuleAttribute : Attribute { public ModuleAttribute(string name, ModuleType moduleType) { this.name = name; this.moduleType = moduleType; } private string name; /// <summary> /// 描述 /// </summary> public string Name { get { return name; } } private ModuleType moduleType; /// <summary> /// 模块类型 /// </summary> public ModuleType ModuleType { get { return moduleType; } } } }
22.867925
66
0.566007
[ "MIT" ]
JasonYJ90/WPF-Xamarin-Blazor-Examples
src/Consumption/Consumption.Shared/Common/Attributes/ModuleAttribute.cs
1,444
C#
/* PureMVC C# Multi-Core Port by Tang Khai Phuong <phuong.tang@puremvc.org>, et al. PureMVC - Copyright(c) 2006-08 Futurescale, Inc., Some rights reserved. Your reuse is governed by the Creative Commons Attribution 3.0 License */ #region Using #endregion using System; using System.Collections.Generic; namespace PureMVC.Interfaces { /// <summary> /// The interface definition for a PureMVC Model /// </summary> /// <remarks> /// <para>In PureMVC, <c>IModel</c> implementors provide access to <c>IProxy</c> objects by named lookup</para> /// <para>An <c>IModel</c> assumes these responsibilities:</para> /// <list type="bullet"> /// <item>Maintain a cache of <c>IProxy</c> instances</item> /// <item>Provide methods for registering, retrieving, and removing <c>IProxy</c> instances</item> /// </list> /// </remarks> public interface IModel : IDisposable { /// <summary> /// Register an <c>IProxy</c> instance with the <c>Model</c> /// </summary> /// <param name="proxy">A reference to the proxy object to be held by the <c>Model</c></param> void RegisterProxy(IProxy proxy); /// <summary> /// Retrieve an <c>IProxy</c> instance from the Model /// </summary> /// <param name="proxyName">The name of the proxy to retrieve</param> /// <returns>The <c>IProxy</c> instance previously registered with the given <c>proxyName</c></returns> IProxy RetrieveProxy(string proxyName); /// <summary> /// Remove an <c>IProxy</c> instance from the Model /// </summary> /// <param name="proxyName">The name of the <c>IProxy</c> instance to be removed</param> IProxy RemoveProxy(string proxyName); /// <summary> /// Check if a Proxy is registered /// </summary> /// <param name="proxyName">The name of the proxy to check for</param> /// <returns>whether a Proxy is currently registered with the given <c>proxyName</c>.</returns> bool HasProxy(string proxyName); /// <summary> /// List all proxy name /// </summary> IEnumerable<string> ListProxyNames { get; } } }
36.983607
119
0.608156
[ "BSD-3-Clause" ]
dreamirror/pureMVC
PureMVC.MultiCore.DotNet/PureMVC/Interfaces/IModel.cs
2,258
C#
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; namespace RandomchaosMGBase.BaseClasses.Animation { public class SpriteSheetAnimationPlayer { public TimeSpan AnimationOffSet { get; set; } protected bool _IsPlaying = false; public bool IsPlaying { get { return _IsPlaying; } } public Vector2 CurrentCell { get; set; } public int CurrentKeyframe { get; set; } public float ClipLerpValue { get { if (currentClip != null) return (float)CurrentKeyframe / currentClip.Keyframes.Count; else return 0; } } protected SpriteSheetAnimationClip currentClip; public SpriteSheetAnimationClip CurrentClip { get { return currentClip; } } /// <summary> /// Gets the current play position. /// </summary> TimeSpan currentTime; public TimeSpan CurrentTime { get { return currentTime; } } public Dictionary<string, SpriteSheetAnimationClip> Clips { get; set; } public SpriteSheetAnimationPlayer(Dictionary<string, SpriteSheetAnimationClip> clips = null, TimeSpan animationOffSet = new TimeSpan()) { AnimationOffSet = animationOffSet; Clips = clips; } public void StartClip(string name, int frame = 0) { StartClip(Clips[name]); } public void StartClip(SpriteSheetAnimationClip clip, int frame = 0) { if (clip != null && clip != currentClip) { currentTime = TimeSpan.Zero + AnimationOffSet; CurrentKeyframe = frame; currentClip = clip; _IsPlaying = true; } } public void StopClip() { if (currentClip != null && IsPlaying) _IsPlaying = false; } public void Update(TimeSpan time) { if (currentClip != null) GetCurrentCell(time); } public void Update(float lerp) { if (currentClip != null) GetCurrentCell(lerp); } protected void GetCurrentCell(float lerp) { CurrentKeyframe = (int)MathHelper.Lerp(0, currentClip.Keyframes.Count - 1, lerp); CurrentCell = currentClip.Keyframes[CurrentKeyframe].Cell; } protected void GetCurrentCell(TimeSpan time) { time += currentTime; // If we reached the end, loop back to the start. while (time >= currentClip.Duration) time -= currentClip.Duration; if ((time < TimeSpan.Zero) || (time >= currentClip.Duration)) throw new ArgumentOutOfRangeException("time"); if (time < currentTime) { if (currentClip.Looped) CurrentKeyframe = 0; else { CurrentKeyframe = currentClip.Keyframes.Count - 1; StopClip(); } } currentTime = time; // Read key frame matrices. IList<SpriteSheetKeyFrame> keyframes = currentClip.Keyframes; while (CurrentKeyframe < keyframes.Count) { SpriteSheetKeyFrame keyframe = keyframes[CurrentKeyframe]; // Stop when we've read up to the current time position. if (keyframe.Time > currentTime) break; // Use this key frame. CurrentCell = keyframe.Cell; CurrentKeyframe++; } } } }
26.832168
143
0.52515
[ "MIT" ]
Lajbert/Randomchaos-MonoGame-Samples
RandomchaosMGBase/BaseClasses/Animation/SpriteSheetAnimationPlayer.cs
3,839
C#
using System; using System.Linq; namespace JoyGodot.Assets.Scripts.GUI.Inventory_System { public class JoyCraftingSlot : JoyConstrainedSlot { public string IngredientType { get; set; } public int AmountRequired { get; set; } public float AmountInSlot { get { if (this.m_Item is null) { return 0; } if (this.IngredientType.Equals("component", StringComparison.OrdinalIgnoreCase)) { if (this.m_Item.ItemType.UnidentifiedName.Equals(this.Slot, StringComparison.OrdinalIgnoreCase)) { return 1f; } } else if (this.IngredientType.Equals("material", StringComparison.OrdinalIgnoreCase)) { if (this.m_Item.HasTag(this.Slot) || this.m_Item.ItemType.MaterialNames.Any( name => name.Equals(this.Slot, StringComparison.OrdinalIgnoreCase))) { return this.m_Item.ItemType.Size; } } return 0; } } public bool SufficientMaterial => this.AmountInSlot >= this.AmountRequired; } }
31.022727
116
0.49304
[ "MIT" ]
Nosrick/JoyGodot
Assets/Scripts/GUI/Inventory System/JoyCraftingSlot.cs
1,367
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("StareCase")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("StareCase")] [assembly: AssemblyCopyright("Copyright © Microsoft 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a732a8ec-a870-4f44-b47a-df72cb70d974")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.945946
84
0.75
[ "MIT" ]
ASVECode/HackerRank
StareCase/Properties/AssemblyInfo.cs
1,407
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SquareFrame1 { class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); for (int row = 1; row <= n; row++) { if (row == 1 || row == n) { Console.Write("+"); } else { Console.Write("|"); } for (int col = 1; col < n; col++) { if (col == n - 1 && (row == 1 || row == n)) { Console.Write(" +"); } else if (col == n - 1) { Console.Write(" |"); } else { Console.Write(" -"); } } Console.WriteLine(); } } } }
24.422222
63
0.303003
[ "MIT" ]
yani-valeva/Exercise-repo
DrawWithLoops/SquareFrame1/Program.cs
1,101
C#