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
namespace Microsoft.Maui.Controls { public partial class DatePicker { public static IPropertyMapper<IDatePicker, DatePickerHandler> ControlsDatePickerMapper = new PropertyMapper<DatePicker, DatePickerHandler>(DatePickerHandler.Mapper) { #if IOS [PlatformConfiguration.iOSSpecific.DatePicker.UpdateModeProperty.PropertyName] = MapUpdateMode, #endif }; internal static new void RemapForControls() { // Adjust the mappings to preserve Controls.DatePicker legacy behaviors DatePickerHandler.Mapper = ControlsDatePickerMapper; } } }
30.722222
166
0.801085
[ "MIT" ]
10088/maui
src/Controls/src/Core/HandlerImpl/DatePicker/DatePicker.cs
555
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.MachineLearningServices.Outputs { [OutputType] public sealed class ACIServiceResponseResponseEncryptionProperties { /// <summary> /// Encryption Key name /// </summary> public readonly string KeyName; /// <summary> /// Encryption Key Version /// </summary> public readonly string KeyVersion; /// <summary> /// vault base Url /// </summary> public readonly string VaultBaseUrl; [OutputConstructor] private ACIServiceResponseResponseEncryptionProperties( string keyName, string keyVersion, string vaultBaseUrl) { KeyName = keyName; KeyVersion = keyVersion; VaultBaseUrl = vaultBaseUrl; } } }
26.465116
81
0.623023
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/MachineLearningServices/Outputs/ACIServiceResponseResponseEncryptionProperties.cs
1,138
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Travel.Application.Common.Interfaces; using Travel.Domain.Settings; using Travel.Shared.Files; using Travel.Shared.Services; namespace Travel.Shared { public static class DependencyInjection { public static IServiceCollection AddInfrastructureShared(this IServiceCollection services, IConfiguration config) { services.Configure<MailSettings>(config.GetSection("MailSettings")); services.AddTransient<IDateTime, DateTimeService>(); services.AddTransient<IEmailService, EmailService>(); services.AddTransient<ICsvFileBuilder, CsvFileBuilder>(); return services; } } }
32.363636
117
0.785112
[ "MIT" ]
PacktPublishing/ASP.NET-Core-5-and-Vue.js-3
Chapter07/Travel/src/infrastructure/Travel.Shared/DependencyInjection.cs
714
C#
using Abp.Configuration.Startup; using Abp.Localization.Dictionaries; using Abp.Localization.Dictionaries.Xml; using Abp.Reflection.Extensions; namespace ToDoList.Localization { public static class ToDoListLocalizationConfigurer { public static void Configure(ILocalizationConfiguration localizationConfiguration) { localizationConfiguration.Sources.Add( new DictionaryBasedLocalizationSource(ToDoListConsts.LocalizationSourceName, new XmlEmbeddedFileLocalizationDictionaryProvider( typeof(ToDoListLocalizationConfigurer).GetAssembly(), "ToDoList.Localization.SourceFiles" ) ) ); } } }
33.391304
92
0.661458
[ "MIT" ]
yixuanloh/ToDoList
src/ToDoList.Core/Localization/ToDoListLocalizationConfigurer.cs
770
C#
using System.ComponentModel.DataAnnotations.Schema; using api.Context; using api.Models; namespace api.Dtos { public class SurfDto { public Guid Id { get; set; } public string Name { get; set; } = string.Empty!; public Guid ProjectId { get; set; } public SurfCostProfileDto? CostProfile { get; set; } public SurfCessationCostProfileDto? SurfCessationCostProfileDto { get; set; } public Maturity Maturity { get; set; } public double InfieldPipelineSystemLength { get; set; } public double UmbilicalSystemLength { get; set; } public ArtificialLift ArtificialLift { get; set; } public int RiserCount { get; set; } public int TemplateCount { get; set; } public ProductionFlowline ProductionFlowline { get; set; } } public class SurfCostProfileDto : TimeSeriesCostDto { } public class SurfCessationCostProfileDto : TimeSeriesCostDto { } public enum ProductionFlowlineDto { Default = 999 } }
27.473684
85
0.658046
[ "MIT" ]
DanielBohme/dcd
backend/api/Dtos/SurfDto.cs
1,044
C#
namespace EnvironmentAssessment.Common.VimApi { public class InaccessibleFTMetadataDatastore : InaccessibleDatastore { public new InaccessibleFTMetadataDatastore_LinkedView LinkedView { get { return (InaccessibleFTMetadataDatastore_LinkedView)this._linkedView; } } } }
20.785714
72
0.797251
[ "MIT" ]
octansIt/environmentassessment
EnvironmentAssessment.Wizard/Common/VimApi/I/InaccessibleFTMetadataDatastore.cs
291
C#
/** * Copyright 2015 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ using Ca.Infoway.Messagebuilder; namespace Ca.Infoway.Messagebuilder.Model.Ab_r02_04_03_imm.Domainvalue { public interface EyeAndVisionServiceProviderHIPAA : Code { } }
38.25
83
0.716153
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-ab-r02_04_03_imm/Main/Ca/Infoway/Messagebuilder/Model/Ab_r02_04_03_imm/Domainvalue/EyeAndVisionServiceProviderHIPAA.cs
1,071
C#
using System; using System.Collections.Generic; using System.Linq; using MediaKit.Core.Extensions; using Xamarin.Forms; namespace MediaKit.Core { /// <summary> /// Base object to manipulate animation sequences, group them and schedule their running for specific target. /// The main purpose of using Storyboards instead plain Xamarin Forms animation objects is declarative way of defining /// animation sequences and possibility to define storyboard inside XAML files. /// </summary> [ContentProperty(nameof(Animations))] public sealed class Storyboard : BindableObject, IApplicable { private Duration _duration = Duration.Automatic; private bool _isApplied; private VisualElement _target; /// <summary> /// Unique storyboard identificator, used as Xamarin Forms animation handle as default and no explicit handle specified /// </summary> public Guid Id { get; } = Guid.NewGuid(); /// <summary> /// Calculated duration of storyboard. Value, produced by addition durations and offsets of animations . /// <returns> /// <see cref="Core.Duration.Forever" /> or explicit timespan duration will be returned. /// In case <see cref="Duration" /> specified explicitly with <see cref="Core.Duration.Forever" /> or /// <see cref="TimeSpan" /> it overrides calculated value. Explicit value may be used to schedule forever and /// shorter than calculated animations execution. /// </returns> /// </summary> public Duration Duration { get { if (_duration == Duration.Automatic) return new Duration(Animations.Any() ? Animations.Max(x => x.CalculateExactAnimationDuration().ToTimeSpan().SumSafety(x.BeginTime)) : TimeSpan.Zero); return _duration; } set { this.ThrowIfApplied(); _duration = value; } } /// <summary> /// <see cref="IAnimation" /> sequence, scheduled to be executed in storyboard's scope /// </summary> public List<IAnimation> Animations { get; } = new List<IAnimation>(); /// <summary> /// <see cref="VisualElement" /> Target view, which will be animation's owner if specified. Otherwise it should be /// specified externally with 'animationRoot' param /// of one of <see cref="StoryboardExtensions.Begin(Storyboard, StoryboardFinishedCallback)" /> /// extension methods. /// </summary> public VisualElement Target { get => _target; set { this.ThrowIfApplied(); _target = value; } } /// <summary> /// Specifies, does this object freezed for new changes. /// </summary> public bool IsApplied { get => _isApplied; private set { this.ThrowIfApplied(); _isApplied = value; } } /// <summary> /// Allows to freeze object for new changes. /// </summary> public void Apply() { Animations.ForEach(x => x.ApplySafety()); IsApplied = true; } } }
36.453608
131
0.552885
[ "MIT" ]
vasylmosiiuk/XForms.MediaKit
MediaKit/MediaKit.Core/Storyboard.cs
3,538
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CineTeatro.Common.Entities { public class ButacaSector : ICloneable { public int ButacaSectorId { get; set; } public Butaca Butaca { get; set; } public int ButacaId { get; set; } public Sector Sector { get; set; } public int SectorId { get; set; } public object Clone() { return this.MemberwiseClone(); } } }
23.826087
48
0.594891
[ "CC0-1.0" ]
cbaldini/cinema-theatre-ef
CineTeatro.Common/Entities/ButacaSector.cs
550
C#
using System; using tdsm.api; using tdsm.core.Messages.Out; using Terraria; namespace tdsm.core.Messages.In { public class ItemOwnerInfoMessage : SlotMessageHandler { public override Packet GetPacket() { return Packet.ITEM_OWNER_INFO; } public override void Process(int whoAmI, byte[] readBuffer, int length, int num) { int num51 = (int)ReadInt16(readBuffer); int num52 = (int)ReadByte(readBuffer); if (Main.item[num51].owner != whoAmI) { return; } Main.item[num51].owner = num52; if (num52 == Main.myPlayer) { Main.item[num51].keepTime = 15; } else { Main.item[num51].keepTime = 0; } if (Main.netMode == 2) { Main.item[num51].owner = 255; Main.item[num51].keepTime = 15; NewNetMessage.SendData(22, -1, -1, String.Empty, num51, 0f, 0f, 0f, 0); return; } return; } } }
26.674419
88
0.483871
[ "MIT" ]
DeathCradle/Terraria-s-Dedicated-Server-Mod
Core/Messages/In/22_ItemOwnerInfoMessage.cs
1,149
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.AzureNextGen.OperationsManagement.Outputs { [OutputType] public sealed class ManagementConfigurationPropertiesResponse { /// <summary> /// The applicationId of the appliance for this Management. /// </summary> public readonly string? ApplicationId; /// <summary> /// Parameters to run the ARM template /// </summary> public readonly ImmutableArray<Outputs.ArmTemplateParameterResponse> Parameters; /// <summary> /// The type of the parent resource. /// </summary> public readonly string ParentResourceType; /// <summary> /// The provisioning state for the ManagementConfiguration. /// </summary> public readonly string ProvisioningState; /// <summary> /// The Json object containing the ARM template to deploy /// </summary> public readonly object Template; [OutputConstructor] private ManagementConfigurationPropertiesResponse( string? applicationId, ImmutableArray<Outputs.ArmTemplateParameterResponse> parameters, string parentResourceType, string provisioningState, object template) { ApplicationId = applicationId; Parameters = parameters; ParentResourceType = parentResourceType; ProvisioningState = provisioningState; Template = template; } } }
31.614035
88
0.642619
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/OperationsManagement/Outputs/ManagementConfigurationPropertiesResponse.cs
1,802
C#
// Copyright (c) 2010-2013 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.Collections.Generic; using System.Linq; using ICSharpCode.Decompiler.TypeSystem; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.Semantics { /// <summary> /// Represents the result of a method, constructor or indexer invocation. /// </summary> public class InvocationResolveResult : MemberResolveResult { /// <summary> /// Gets the arguments that are being passed to the method, in the order the arguments are being evaluated. /// </summary> public readonly IList<ResolveResult> Arguments; /// <summary> /// Gets the list of initializer statements that are appplied to the result of this invocation. /// This is used to represent object and collection initializers. /// With the initializer statements, the <see cref="InitializedObjectResolveResult"/> is used /// to refer to the result of this invocation. /// </summary> public readonly IList<ResolveResult> InitializerStatements; public InvocationResolveResult(ResolveResult targetResult, IParameterizedMember member, IList<ResolveResult> arguments = null, IList<ResolveResult> initializerStatements = null, IType returnTypeOverride = null) : base(targetResult, member, returnTypeOverride) { this.Arguments = arguments ?? EmptyList<ResolveResult>.Instance; this.InitializerStatements = initializerStatements ?? EmptyList<ResolveResult>.Instance; } public new IParameterizedMember Member { get { return (IParameterizedMember)base.Member; } } /// <summary> /// Gets the arguments in the order they are being passed to the method. /// For parameter arrays (params), this will return an ArrayCreateResolveResult. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Derived methods may be expensive and create new lists")] public virtual IList<ResolveResult> GetArgumentsForCall() { return Arguments; } public override IEnumerable<ResolveResult> GetChildResults() { return base.GetChildResults().Concat(this.Arguments).Concat(this.InitializerStatements); } } }
45.56
124
0.731051
[ "MIT" ]
164306530/ILSpy
ICSharpCode.Decompiler/Semantics/InvocationResolveResult.cs
3,419
C#
// Copyright 2018 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using EnvDTE; using GoogleCloudExtension.Deployment; using GoogleCloudExtension.Projects.DotNet4; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace GoogleCloudExtensionUnitTests.Projects.DotNet4 { [TestClass] public class CsprojProjectTests { [TestMethod] public void TestConstructor_SetsProject() { var mockedProject = Mock.Of<Project>( p => p.Properties.Item("TargetFrameworkMoniker").Value.ToString() == ".NETFramework,Version=v4.4.4"); var objectUnderTest = new CsprojProject(mockedProject); Assert.AreEqual(mockedProject, objectUnderTest.Project); } [TestMethod] public void TestConstructor_SetsFrameworkVersion() { var mockedProject = Mock.Of<Project>( p => p.Properties.Item("TargetFrameworkMoniker").Value.ToString() == ".NETFramework,Version=v4.4.4"); var objectUnderTest = new CsprojProject(mockedProject); Assert.AreEqual("4.4.4", objectUnderTest.FrameworkVersion); } [TestMethod] public void TestProjectType_IsExpectedConstant() { var objectUnderTest = new CsprojProject( Mock.Of<Project>( p => p.Properties.Item("TargetFrameworkMoniker").Value.ToString() == ".NETFramework,Version=v4.4.4")); Assert.AreEqual(KnownProjectTypes.WebApplication, objectUnderTest.ProjectType); } [TestMethod] public void TestName_ComesFromProject() { const string testProjectName = "TestProjectName"; var mockedProject = Mock.Of<Project>( p => p.Properties.Item("TargetFrameworkMoniker").Value.ToString() == ".NETFramework,Version=v4.4.4" && p.Name == testProjectName); var objectUnderTest = new CsprojProject(mockedProject); Assert.AreEqual(testProjectName, objectUnderTest.Name); } [TestMethod] public void TestFullPath_ComesFromProject() { const string testProjectName = @"c:\Full\Project\Name"; var mockedProject = Mock.Of<Project>( p => p.Properties.Item("TargetFrameworkMoniker").Value.ToString() == ".NETFramework,Version=v4.4.4" && p.FullName == testProjectName); var objectUnderTest = new CsprojProject(mockedProject); Assert.AreEqual(testProjectName, objectUnderTest.FullPath); } [TestMethod] public void TestDirectoryPath_ComesFromProject() { var mockedProject = Mock.Of<Project>( p => p.Properties.Item("TargetFrameworkMoniker").Value.ToString() == ".NETFramework,Version=v4.4.4" && p.FullName == @"c:\Full\Project\Path"); var objectUnderTest = new CsprojProject(mockedProject); Assert.AreEqual(@"c:\Full\Project", objectUnderTest.DirectoryPath); } } }
38.173469
91
0.624432
[ "Apache-2.0" ]
GoogleCloudPlatform/google-cloud-visualstudio
GoogleCloudExtension/GoogleCloudExtensionUnitTests/Projects/DotNet4/CsprojProjectTests.cs
3,743
C#
using System; using System.Collections.Generic; namespace FootballApp.API.Dtos { public class UserToReturnDto { public int Id { get; set; } public string Username { get; set; } public string Firstname { get; set; } public string Lastname { get; set; } public string Email { get; set; } public int Age { get; set; } public DateTime? LastActive { get; set; } public DateTime Created { get; set; } public string Gender { get; set; } public string City { get; set; } public string Country { get; set; } public string Flag { get; set; } public bool IsPowerUser { get; set; } public int? NumberOfGroupsCreated { get; set; } public PhotoToReturnDto MainPhoto { get; set; } public ICollection<MembershipToReturnDto> Memberships { get; set; } public ICollection<PhotoToReturnDto> Photos { get; set; } public ICollection<GroupToReturnDto> GroupsCreated { get; set; } } }
36.357143
75
0.620825
[ "MIT" ]
milosnikic/FootballApp
FootballApp.API/Dtos/UserToReturnDto.cs
1,018
C#
using QuestHelper.Server.Models; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using System.IdentityModel.Tokens.Jwt; using Microsoft.AspNetCore.Http; namespace QuestHelper.Server.Managers { /// <summary> /// Чтение/запись Identity /// </summary> public class IdentityManager { public ClaimsIdentity GetIdentity(User user) { if (user != null) { var claims = new List<Claim> { new Claim(JwtRegisteredClaimNames.UniqueName, user.Name), new Claim(JwtRegisteredClaimNames.NameId, user.UserId) }; ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); return claimsIdentity; } return null; } public static string GetUserId(HttpContext context) { object userIdObj; if (context.Items.TryGetValue("UserId", out userIdObj)) { return userIdObj.ToString(); } return string.Empty; } } }
28.617021
92
0.5829
[ "Apache-2.0" ]
gromozeka07b9/Gosh
QuestHelper/QuestHelper.Server/Managers/IdentityManager.cs
1,359
C#
using Android.App; using Android.Content.PM; using Android.OS; using Android.Runtime; namespace DemoAndroidXCrash.Droid { [Activity(Label = "DemoAndroidXCrash", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); LoadApplication(new App()); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } }
42.310345
192
0.713936
[ "MIT" ]
moljac/Samples.AndroidX
samples/issues/0064/4275736/DemoAndroidXCrash/fix-1/DemoAndroidXCrash/DemoAndroidXCrash.Android/MainActivity.cs
1,229
C#
namespace DN.WebApi.Shared.DTOs.Notifications; public class JobNotification : INotificationMessage { public string MessageType { get; set; } = typeof(JobNotification).Name; public string Message { get; set; } public string JobId { get; set; } public decimal Progress { get; set; } }
33.333333
75
0.716667
[ "MIT" ]
egbakou/dotnet-webapi-boilerplate
src/Shared/Shared.DTOs/Notifications/JobNotification.cs
302
C#
/* * Copyright 2010-2014 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 rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RDS.Model { /// <summary> /// This data type is used as a response element in the <code>DescribeReservedDBInstancesOfferings</code> /// action. /// </summary> public partial class ReservedDBInstancesOffering { private string _currencyCode; private string _dbInstanceClass; private int? _duration; private double? _fixedPrice; private bool? _multiAZ; private string _offeringType; private string _productDescription; private List<RecurringCharge> _recurringCharges = new List<RecurringCharge>(); private string _reservedDBInstancesOfferingId; private double? _usagePrice; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public ReservedDBInstancesOffering() { } /// <summary> /// Gets and sets the property CurrencyCode. /// <para> /// The currency code for the reserved DB instance offering. /// </para> /// </summary> public string CurrencyCode { get { return this._currencyCode; } set { this._currencyCode = value; } } // Check to see if CurrencyCode property is set internal bool IsSetCurrencyCode() { return this._currencyCode != null; } /// <summary> /// Gets and sets the property DBInstanceClass. /// <para> /// The DB instance class for the reserved DB instance. /// </para> /// </summary> public string DBInstanceClass { get { return this._dbInstanceClass; } set { this._dbInstanceClass = value; } } // Check to see if DBInstanceClass property is set internal bool IsSetDBInstanceClass() { return this._dbInstanceClass != null; } /// <summary> /// Gets and sets the property Duration. /// <para> /// The duration of the offering in seconds. /// </para> /// </summary> public int Duration { get { return this._duration.GetValueOrDefault(); } set { this._duration = value; } } // Check to see if Duration property is set internal bool IsSetDuration() { return this._duration.HasValue; } /// <summary> /// Gets and sets the property FixedPrice. /// <para> /// The fixed price charged for this offering. /// </para> /// </summary> public double FixedPrice { get { return this._fixedPrice.GetValueOrDefault(); } set { this._fixedPrice = value; } } // Check to see if FixedPrice property is set internal bool IsSetFixedPrice() { return this._fixedPrice.HasValue; } /// <summary> /// Gets and sets the property MultiAZ. /// <para> /// Indicates if the offering applies to Multi-AZ deployments. /// </para> /// </summary> public bool MultiAZ { get { return this._multiAZ.GetValueOrDefault(); } set { this._multiAZ = value; } } // Check to see if MultiAZ property is set internal bool IsSetMultiAZ() { return this._multiAZ.HasValue; } /// <summary> /// Gets and sets the property OfferingType. /// <para> /// The offering type. /// </para> /// </summary> public string OfferingType { get { return this._offeringType; } set { this._offeringType = value; } } // Check to see if OfferingType property is set internal bool IsSetOfferingType() { return this._offeringType != null; } /// <summary> /// Gets and sets the property ProductDescription. /// <para> /// The database engine used by the offering. /// </para> /// </summary> public string ProductDescription { get { return this._productDescription; } set { this._productDescription = value; } } // Check to see if ProductDescription property is set internal bool IsSetProductDescription() { return this._productDescription != null; } /// <summary> /// Gets and sets the property RecurringCharges. /// <para> /// The recurring price charged to run this reserved DB instance. /// </para> /// </summary> public List<RecurringCharge> RecurringCharges { get { return this._recurringCharges; } set { this._recurringCharges = value; } } // Check to see if RecurringCharges property is set internal bool IsSetRecurringCharges() { return this._recurringCharges != null && this._recurringCharges.Count > 0; } /// <summary> /// Gets and sets the property ReservedDBInstancesOfferingId. /// <para> /// The offering identifier. /// </para> /// </summary> public string ReservedDBInstancesOfferingId { get { return this._reservedDBInstancesOfferingId; } set { this._reservedDBInstancesOfferingId = value; } } // Check to see if ReservedDBInstancesOfferingId property is set internal bool IsSetReservedDBInstancesOfferingId() { return this._reservedDBInstancesOfferingId != null; } /// <summary> /// Gets and sets the property UsagePrice. /// <para> /// The hourly price charged for this offering. /// </para> /// </summary> public double UsagePrice { get { return this._usagePrice.GetValueOrDefault(); } set { this._usagePrice = value; } } // Check to see if UsagePrice property is set internal bool IsSetUsagePrice() { return this._usagePrice.HasValue; } } }
30.660944
111
0.573768
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/RDS/Generated/Model/ReservedDBInstancesOffering.cs
7,144
C#
namespace ClassLib037 { public class Class024 { public static string Property => "ClassLib037"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib037/Class024.cs
120
C#
using System; using System.Collections.Generic; using System.Text; using Bond; using Bond.Expressions; namespace BondExpressionsInterceptor { using System; using System.Globalization; using System.Linq.Expressions; using System.Reflection; using Bond.Internal.Reflection; internal static class SerializerGeneratorFactory<R, W> { public static ISerializerGenerator<R, W> Create<S>(Expression<Action<R, W, int>> deferredSerialize, S schema, bool inlineNested = true) { return Cache<S>.Create(deferredSerialize, schema, inlineNested); } static class Cache<S> { public static readonly Func<Expression<Action<R, W, int>>, S, bool, ISerializerGenerator<R, W>> Create; [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] static Cache() { Type generator = null; var attribute = typeof(W).GetAttribute<SerializerAttribute>(); if (attribute == null) { generator = typeof(SerializerTransform<R, W>); } /* else { if (!attribute.Type.IsGenericType() || attribute.Type.GetTypeInfo().GenericTypeParameters.Length != 2) { throw new InvalidOperationException( "Serializer generator is expected to be a generic type with two type parameters."); } generator = attribute.Type.MakeGenericType(typeof(R), typeof(W)); if (!typeof(ISerializerGenerator<R, W>).IsAssignableFrom(generator)) { throw new InvalidOperationException( string.Format( CultureInfo.InvariantCulture, "Serializer generator {0} specified for writer {1} is not an ISerializerGenerator.", generator, typeof(W))); } }*/ var ctor = generator.GetConstructor(typeof(Expression<Action<R, W, int>>), typeof(S), typeof(bool)) ?? generator.GetConstructor(typeof(Expression<Action<R, W, int>>), typeof(S)); if (ctor == null) { throw new InvalidOperationException( string.Format( CultureInfo.InvariantCulture, "Constructor {0}(Expression<Action<R, W, int>>, {1}) not defined.", generator, typeof(S))); } var deferredSerialize = Expression.Parameter(typeof(Expression<Action<R, W, int>>)); var schema = Expression.Parameter(typeof(S)); var inlineNested = Expression.Parameter(typeof(bool)); var newExpression = ctor.GetParameters().Length == 3 ? Expression.New(ctor, deferredSerialize, schema, inlineNested) : Expression.New(ctor, deferredSerialize, schema); Create = Expression.Lambda<Func<Expression<Action<R, W, int>>, S, bool, ISerializerGenerator<R, W>>>( newExpression, deferredSerialize, schema, inlineNested).Compile(); } } } }
40.233333
143
0.520851
[ "MIT" ]
mjsabby/BondExpressionsInterceptor
SerializerGeneratorFactory.cs
3,623
C#
/** * Copyright 2017-2021 Plexus Interop Deutsche Bank AG * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Plexus.Interop.Transport.Transmission.WebSockets.Client.Internal { using Plexus.Channels; using Plexus.Pools; using Plexus.Processes; using SuperSocket.ClientEngine; using System; using System.Threading; using System.Threading.Tasks; using WebSocket4Net; internal sealed class WebSocketClientTransmissionConnection : ProcessBase, ITransmissionConnection { private static readonly TimeSpan ConnectionTimeout = TimeoutConstants.Timeout20Sec; private readonly ILogger _log; private readonly WebSocket _webSocket; private readonly WebSocketClientTransmissionReader _reader; private readonly WebSocketClientTransmissionWriter _writer; private readonly Promise _connectCompletion = new Promise(); private readonly Promise _disconnectCompletion = new Promise(); public WebSocketClientTransmissionConnection(string url) { _log = LogManager.GetLogger<WebSocketClientTransmissionConnection>(Id.ToString()); _disconnectCompletion.Task.PropagateCompletionToPromise(_connectCompletion); _webSocket = new WebSocket(url.Replace("http://", "ws://").Replace("https://", "wss://")); _webSocket.Opened += OnOpened; _webSocket.Closed += OnClosed; _webSocket.Error += OnError; _webSocket.NoDelay = true; _webSocket.EnableAutoSendPing = true; _webSocket.AutoSendPingInterval = 5000; _webSocket.ReceiveBufferSize = PooledBuffer.MaxSize; _webSocket.Security.AllowNameMismatchCertificate = true; _webSocket.Security.AllowCertificateChainErrors = true; _webSocket.Security.AllowUnstrustedCertificate = true; _reader = new WebSocketClientTransmissionReader(Id, _webSocket, CancellationToken); _writer = new WebSocketClientTransmissionWriter(Id, _webSocket, CancellationToken); Completion.LogCompletion(_log); _log.Trace("Created"); } private void OnError(object sender, ErrorEventArgs e) { _log.Trace("OnError: {0}", e.Exception.FormatTypeAndMessage()); Stop(); _disconnectCompletion.TryFail(e.Exception); } private void OnClosed(object sender, EventArgs e) { _log.Trace("OnClosed"); Stop(); _disconnectCompletion.TryComplete(); } private void OnOpened(object sender, EventArgs e) { _log.Trace("OnOpened"); _connectCompletion.TryComplete(); } public UniqueId Id { get; } = UniqueId.Generate(); public IReadableChannel<IPooledBuffer> In => _reader.In; public ITerminatableWritableChannel<IPooledBuffer> Out => _writer.Out; public async Task ConnectAsync(CancellationToken cancellationToken) { using (var cancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) using (cancellation.Token.Register(Stop, false)) { cancellation.CancelAfter(ConnectionTimeout); try { await StartAsync().ConfigureAwait(false); } finally { cancellationToken.ThrowIfCancellationRequested(); } } } public Task DisconnectAsync() => StopAsync(); protected override async Task<Task> StartCoreAsync() { try { if (CancellationToken.IsCancellationRequested) { _webSocket.Dispose(); return TaskConstants.Completed; } _log.Trace("Opening socket"); _webSocket.Open(); await _connectCompletion.Task.WithCancellation(CancellationToken).ConfigureAwait(false); _log.Trace("Connected"); _writer.Start(); return ProcessAsync(); } catch { _webSocket.Dispose(); throw; } } private async Task ProcessAsync() { using (_webSocket) { try { try { await Task.WhenAny(_writer.Completion, _reader.Completion).Unwrap().ConfigureAwait(false); } catch (Exception ex) { _writer.Out.TryTerminate(ex); _webSocket.Close(); throw; } finally { await Task.WhenAll(_writer.Completion, _reader.Completion).ConfigureAwait(false); } } finally { _webSocket.Close(); await _disconnectCompletion.Task.ConfigureAwait(false); } } } } }
36.142857
114
0.582574
[ "Apache-2.0" ]
deutschebank/plexus-interop
desktop/src/Plexus.Interop.Transport.Transmission.WebSockets.Client/Internal/WebSocketClientTransmissionConnection.cs
5,819
C#
using System.Collections.Generic; using Nop.Web.Framework.Models; namespace Nop.Web.Areas.Admin.Models.Catalog { /// <summary> /// Represents an associated product model to add to the product /// </summary> public partial class AddAssociatedProductModel : BaseNopModel { #region Ctor public AddAssociatedProductModel() { SelectedProductIds = new List<int>(); } #endregion #region Properties public int ProductId { get; set; } public IList<int> SelectedProductIds { get; set; } #endregion } }
22.444444
68
0.623762
[ "MIT" ]
ASP-WAF/FireWall
Samples/NopeCommerce/Presentation/Nop.Web/Areas/Admin/Models/Catalog/AddAssociatedProductModel.cs
608
C#
using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Moq; using Xunit; using Vim.Extensions; using Vim.UnitTest.Mock; namespace Vim.UnitTest { public abstract class TextChangeTest { public sealed class InsertTextTest : TextChangeTest { /// <summary> /// The InsertText for a simple insert is just the text /// </summary> [Fact] public void Simple() { var textChange = TextChange.NewInsert("dog"); Assert.Equal("dog", textChange.InsertText.Value); } /// <summary> /// Combined inserts should just combine the values /// </summary> [Fact] public void CombinedInsert() { var textChange = TextChange.NewCombination( TextChange.NewInsert("hello "), TextChange.NewInsert("world")); Assert.Equal("hello world", textChange.InsertText.Value); } /// <summary> /// A naked delete should not have an InsertText /// </summary> [Fact] public void DeleteLeft() { var textChange = TextChange.NewDeleteLeft(1); Assert.True(textChange.InsertText.IsNone()); } /// <summary> /// If the delete doesn't remove all of the text then there is still an insert /// </summary> [Fact] public void SmallDeleteLeft() { var textChange = TextChange.NewCombination( TextChange.NewInsert("dogs"), TextChange.NewDeleteLeft(1)); Assert.Equal("dog", textChange.InsertText.Value); } /// <summary> /// If the delete removes all of the text then there is no insert /// </summary> [Fact] public void BigDeleteLeft() { var textChange = TextChange.NewCombination( TextChange.NewInsert("dogs"), TextChange.NewDeleteLeft(10)); Assert.True(textChange.InsertText.IsNone()); } } public abstract class ReduceTest : TextChangeTest { /// <summary> /// There are a lot of empty states which can be produced by the reduce /// routines. We should empty them out to 0 /// </summary> public sealed class EmptyTest : ReduceTest { /// <summary> /// The insert + delete here should collapse to an empty Insert which should /// simply be resolved out to nothing by the /// </summary> [Fact] public void InsertAndDeleteLeft() { var textChange = TextChange.CreateReduced( TextChange.NewCombination( TextChange.NewInsert("cat"), TextChange.NewDeleteLeft(3)), TextChange.NewDeleteRight(3)); Assert.Equal(3, textChange.AsDeleteRight().Item); } /// <summary> /// The insert + delete here should collapse to an empty Insert which should /// simply be resolved out to nothing by the /// </summary> [Fact] public void InsertAndDeleteLeftReverse() { var textChange = TextChange.CreateReduced( TextChange.NewDeleteRight(3), TextChange.NewCombination( TextChange.NewInsert("cat"), TextChange.NewDeleteLeft(3))); Assert.Equal(3, textChange.AsDeleteRight().Item); } } public sealed class MiscTest : ReduceTest { [Fact] public void DoubleInsert() { var textChange = TextChange.CreateReduced( TextChange.NewInsert("a"), TextChange.NewInsert("b")); Assert.Equal("ab", textChange.AsInsert().Item); } [Fact] public void DoubleDeleteLeft() { var textChange = TextChange.CreateReduced( TextChange.NewDeleteLeft(5), TextChange.NewDeleteLeft(6)); Assert.Equal(11, textChange.AsDeleteLeft().Item); } [Fact] public void DoubleDeleteRight() { var textChange = TextChange.CreateReduced( TextChange.NewDeleteRight(5), TextChange.NewDeleteRight(6)); Assert.Equal(11, textChange.AsDeleteRight().Item); } [Fact] public void InsertThenDeletePartial() { var textChange = TextChange.CreateReduced( TextChange.NewInsert("cat"), TextChange.NewDeleteLeft(2)); Assert.Equal("c", textChange.AsInsert().Item); } [Fact] public void InsertThenDeleteMore() { var textChange = TextChange.CreateReduced( TextChange.NewInsert("cat"), TextChange.NewDeleteLeft(4)); Assert.Equal(1, textChange.AsDeleteLeft().Item); } [Fact] public void InsertThenDeleteExact() { var textChange = TextChange.CreateReduced( TextChange.NewInsert("cat"), TextChange.NewDeleteLeft(3)); Assert.Equal("", textChange.AsInsert().Item); } /// <summary> /// The tree for Issue 1108 can be constructed 2 ways. Left or right heavy. This /// does the opposite way to make sure we get the same answer /// </summary> [Fact] public void Issue1108Reversed() { var textChange = TextChange.CreateReduced( TextChange.NewCombination( TextChange.NewInsert("pr"), TextChange.NewDeleteLeft(2)), TextChange.NewInsert("protected")); Assert.Equal("protected", textChange.AsInsert().Item); } /// <summary> /// This is a pretty typical intellisense pattern. Need to make sure we /// can delete it down to the simple resulting insert /// </summary> [Fact] public void Issue1108() { var textChange = TextChange.CreateReduced( TextChange.NewInsert("pr"), TextChange.NewCombination( TextChange.NewDeleteLeft(2), TextChange.NewInsert("protected"))); Assert.Equal("protected", textChange.AsInsert().Item); } } } } }
38.95
100
0.454942
[ "Apache-2.0" ]
Kazark/VsVim
Test/VimCoreTest/TextChangeTest.cs
7,792
C#
using Rhino.Geometry; using DB = Autodesk.Revit.DB; namespace RhinoInside.Revit.Convert.Geometry { /// <summary> /// Converts <see cref="SubD"/> to be transfered to a <see cref="DB.Solid"/>. /// </summary> static class SubDEncoder { #region Encode internal static Brep ToRawBrep(/*const*/ SubD subD, double scaleFactor) { var brep = subD.ToBrep(); return BrepEncoder.EncodeRaw(ref brep, scaleFactor) ? brep : default; } #endregion } }
24
79
0.658333
[ "MIT" ]
IMVVVVVIP/rhino.inside-revit
src/RhinoInside.Revit/Convert/Geometry/SubDEncoder.cs
480
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("03. Printing Triangle")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("03. Printing Triangle")] [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] [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("6cdd08f7-f3ca-4384-a8ca-59454d2d2911")] // 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")]
38.72973
84
0.747383
[ "MIT" ]
origami99/SoftUni
02. ProgFund/Exercises/05. Methods. Debugging - Lab/03. Printing Triangle/Properties/AssemblyInfo.cs
1,436
C#
namespace BooksRaffle.Models { public partial class Tag { public bool Equals(Tag other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Id == other.Id && string.Equals((string) Name, (string) other.Name); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Tag)obj); } public override int GetHashCode() { unchecked { return (Id * 397) ^ (Name != null ? Name.GetHashCode() : 0); } } } }
29.035714
87
0.519065
[ "MIT" ]
deccer/BooksRaffle
BooksRaffle/Models/Tag.partial.cs
815
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Gcp.Container.Inputs { public sealed class ClusterNodePoolUpgradeSettingsGetArgs : Pulumi.ResourceArgs { [Input("maxSurge", required: true)] public Input<int> MaxSurge { get; set; } = null!; [Input("maxUnavailable", required: true)] public Input<int> MaxUnavailable { get; set; } = null!; public ClusterNodePoolUpgradeSettingsGetArgs() { } } }
28.730769
88
0.68407
[ "ECL-2.0", "Apache-2.0" ]
dimpu47/pulumi-gcp
sdk/dotnet/Container/Inputs/ClusterNodePoolUpgradeSettingsGetArgs.cs
747
C#
using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; using System.ComponentModel.Design; using Task = System.Threading.Tasks.Task; namespace VsixToolWindowAsyncPackageExample { internal sealed class VsixToolWindowCommand { public const int CommandId = 0x0100; public static readonly Guid CommandSet = new Guid("919cd8f4-e812-4b71-9734-0149032c7c8c"); private static AsyncPackage _asyncPackage; public static VsixToolWindowCommand Instance { get; private set; } public static async Task InitializeGregt(AsyncPackage asyncPackage) { if (asyncPackage == null) { throw new ArgumentNullException(nameof(asyncPackage)); } _asyncPackage = asyncPackage; OleMenuCommandService commandService = await asyncPackage.GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService; Instance = new VsixToolWindowCommand(commandService); } private VsixToolWindowCommand(OleMenuCommandService commandService) { var commandId = new CommandID(CommandSet, CommandId); var menuItem = new OleMenuCommand(FindShowToolWindowAsync, commandId); commandService.AddCommand(menuItem); } /// <summary> /// Is hit when user selects Tools > Windows > VS Sports Desk /// </summary> private void FindShowToolWindowAsync(object sender, EventArgs e) { // Get the instance number 0 of this tool window. This window is single instance so this instance is actually the only one. // The last flag is set to true so that if the tool window does not exists it will be created. _asyncPackage.JoinableTaskFactory.RunAsync(async delegate { //////////////////////////////////////////////var window = await _asyncPackage.ShowToolWindowAsync(typeof(VsixToolWindowPane), 0, true, _asyncPackage.DisposalToken); //var window = _asyncPackage.FindToolWindow(typeof(VsixToolWindowPane), 0, true); var window = await _asyncPackage.FindToolWindowAsync(typeof(VsixToolWindowPane), 0, true, _asyncPackage.DisposalToken); if (window?.Frame == null) { throw new NotSupportedException("Cannot create tool window"); } await _asyncPackage.JoinableTaskFactory.SwitchToMainThreadAsync(); var windowFrame = (IVsWindowFrame)window.Frame; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show()); }); } } }
45.694915
181
0.652819
[ "Apache-2.0" ]
GregTrevellick/HelloWorldVsixToolWindowAsyncPackageExample
VsixToolWindowAsyncPackageExample/VsixToolWindowCommand.cs
2,698
C#
using System.IO; namespace Perry.Commands.Options { class PerryOptions { public PerryOptions(bool interactive, string logPath, bool includeException, bool includeVariable, string instrumentationKey) { Interactive = interactive; LogPath = string.IsNullOrWhiteSpace(logPath) ? null : Path.GetFullPath(logPath); IncludeException = includeException; IncludeVariable = includeVariable; InstrumentationKey = instrumentationKey; } public bool Interactive { get; } public string LogPath { get; } public bool IncludeException { get; } public bool IncludeVariable { get; } public string InstrumentationKey { get; } public int MemoryErrorCount { get; } = 20; } }
34.695652
133
0.649123
[ "Apache-2.0" ]
ronnykarlsson/perry
Perry/Commands/Options/PerryOptions.cs
800
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace UniversalQueryFrameWork { /// <summary> /// App.xaml 的交互逻辑 /// </summary> public partial class App : Application { } }
17.833333
42
0.707165
[ "Apache-2.0" ]
xiaokaizh/UniversalQueryFrameWork
App.xaml.cs
333
C#
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; using Microsoft.IdentityModel.Tokens; using WopiHost.Abstractions; namespace WopiHost.FileSystemProvider { /// <inheritdoc/> public class WopiSecurityHandler : IWopiSecurityHandler { private readonly JwtSecurityTokenHandler _tokenHandler = new(); private SymmetricSecurityKey _key = null; private SymmetricSecurityKey Key { get { if (_key is null) { //RandomNumberGenerator rng = RandomNumberGenerator.Create(); //byte[] key = new byte[128]; //rng.GetBytes(key); var key = Encoding.ASCII.GetBytes("secretKeysecretKeysecretKey123"/* + new Random(DateTime.Now.Millisecond).Next(1,999)*/); _key = new SymmetricSecurityKey(key); } return _key; } } //TODO: abstract private readonly Dictionary<string, ClaimsPrincipal> _userDatabase = new() { { "Anonymous", new ClaimsPrincipal( new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.NameIdentifier, "12345"), new Claim(ClaimTypes.Name, "Anonymous"), new Claim(ClaimTypes.Email, "anonymous@domain.tld"), //TDOO: this needs to be done per file new Claim(WopiClaimTypes.USER_PERMISSIONS, (WopiUserPermissions.UserCanWrite | WopiUserPermissions.UserCanRename | WopiUserPermissions.UserCanAttend | WopiUserPermissions.UserCanPresent).ToString()) }) ) } }; /// <inheritdoc/> public SecurityToken GenerateAccessToken(string userId, string resourceId) { var user = _userDatabase[userId]; var tokenDescriptor = new SecurityTokenDescriptor { Subject = user.Identities.FirstOrDefault(), Expires = DateTime.UtcNow.AddHours(1), //access token ttl: https://wopi.readthedocs.io/projects/wopirest/en/latest/concepts.html#term-access-token-ttl SigningCredentials = new SigningCredentials(Key, SecurityAlgorithms.HmacSha256) }; return _tokenHandler.CreateToken(tokenDescriptor); } /// <inheritdoc/> public ClaimsPrincipal GetPrincipal(string tokenString) { //TODO: https://github.com/aspnet/Security/tree/master/src/Microsoft.AspNetCore.Authentication.JwtBearer var tokenValidation = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false, ValidateActor = false, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = Key }; try { // Try to validate the token var principal = _tokenHandler.ValidateToken(tokenString, tokenValidation, out var token); return principal; } catch (Exception ex) { return null; } } /// <inheritdoc/> public bool IsAuthorized(ClaimsPrincipal principal, string resourceId, WopiAuthorizationRequirement operation) { //TODO: logic return true; } /// <summary> /// Converts the security token to a Base64 string. /// </summary> public string WriteToken(SecurityToken token) { return _tokenHandler.WriteToken(token); } } }
34.212389
218
0.56984
[ "BSD-3-Clause" ]
Nokecy/WopiHost
WopiHost.FileSystemProvider/WopiSecurityHandler.cs
3,868
C#
namespace ClearHl7.Codes.V281 { /// <summary> /// HL7 Version 2 Table 0181 - MFN Record-Level Error Return. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0181</remarks> public enum CodeMfnRecordLevelErrorReturn { /// <summary> /// S - Successful posting of the record defined by the MFE segment. /// </summary> SuccessfulPostingOfTheRecord, /// <summary> /// U - Unsuccessful posting of the record defined by the MFE segment. /// </summary> UnsuccessfulPostingOfTheRecord } }
30.894737
78
0.599659
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7.Codes/V281/CodeMfnRecordLevelErrorReturn.cs
589
C#
/* * Payment Gateway API Specification. * * The documentation here is designed to provide all of the technical guidance required to consume and integrate with our APIs for payment processing. To learn more about our APIs please visit https://docs.firstdata.com/org/gateway. * * The version of the OpenAPI document: 6.14.0.20201015.001 * * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// Secure3D21AuthenticationResultAllOf /// </summary> [DataContract] public partial class Secure3D21AuthenticationResultAllOf : IEquatable<Secure3D21AuthenticationResultAllOf>, IValidatableObject { /// <summary> /// The result of authentication attempt returned by the 3D Secure authentication process (PaRes). /// </summary> /// <value>The result of authentication attempt returned by the 3D Secure authentication process (PaRes).</value> [JsonConverter(typeof(StringEnumConverter))] public enum AuthenticationResponseEnum { /// <summary> /// Enum A for value: A /// </summary> [EnumMember(Value = "A")] A = 1, /// <summary> /// Enum N for value: N /// </summary> [EnumMember(Value = "N")] N = 2, /// <summary> /// Enum U for value: U /// </summary> [EnumMember(Value = "U")] U = 3, /// <summary> /// Enum Y for value: Y /// </summary> [EnumMember(Value = "Y")] Y = 4, /// <summary> /// Enum C for value: C /// </summary> [EnumMember(Value = "C")] C = 5, /// <summary> /// Enum R for value: R /// </summary> [EnumMember(Value = "R")] R = 6 } /// <summary> /// The result of authentication attempt returned by the 3D Secure authentication process (PaRes). /// </summary> /// <value>The result of authentication attempt returned by the 3D Secure authentication process (PaRes).</value> [DataMember(Name = "authenticationResponse", EmitDefaultValue = false)] public AuthenticationResponseEnum? AuthenticationResponse { get; set; } /// <summary> /// The transaction status as returned by the 3D Secure authentication process. /// </summary> /// <value>The transaction status as returned by the 3D Secure authentication process.</value> [JsonConverter(typeof(StringEnumConverter))] public enum TransactionStatusEnum { /// <summary> /// Enum A for value: A /// </summary> [EnumMember(Value = "A")] A = 1, /// <summary> /// Enum N for value: N /// </summary> [EnumMember(Value = "N")] N = 2, /// <summary> /// Enum U for value: U /// </summary> [EnumMember(Value = "U")] U = 3, /// <summary> /// Enum Y for value: Y /// </summary> [EnumMember(Value = "Y")] Y = 4, /// <summary> /// Enum C for value: C /// </summary> [EnumMember(Value = "C")] C = 5, /// <summary> /// Enum R for value: R /// </summary> [EnumMember(Value = "R")] R = 6 } /// <summary> /// The transaction status as returned by the 3D Secure authentication process. /// </summary> /// <value>The transaction status as returned by the 3D Secure authentication process.</value> [DataMember(Name = "transactionStatus", EmitDefaultValue = false)] public TransactionStatusEnum? TransactionStatus { get; set; } /// <summary> /// Initializes a new instance of the <see cref="Secure3D21AuthenticationResultAllOf" /> class. /// </summary> /// <param name="cavv">The Cardholder Authentication Verification Value (CAVV) is a cryptographic value derived by the issuer during payment authentication that can provide evidence of the results of payment authentication during an online purchase..</param> /// <param name="xid">The transaction identifier (XID) is a unique tracking number set by the merchant..</param> /// <param name="transactionId">The response transaction UUID. Only applicable to MasterCard..</param> /// <param name="authenticationResponse">The result of authentication attempt returned by the 3D Secure authentication process (PaRes). (default to AuthenticationResponseEnum.Y).</param> /// <param name="transactionStatus">The transaction status as returned by the 3D Secure authentication process..</param> public Secure3D21AuthenticationResultAllOf(string cavv = default(string), string xid = default(string), string transactionId = default(string), AuthenticationResponseEnum? authenticationResponse = AuthenticationResponseEnum.Y, TransactionStatusEnum? transactionStatus = null) { this.Cavv = cavv; this.Xid = xid; this.TransactionId = transactionId; this.AuthenticationResponse = authenticationResponse; this.TransactionStatus = transactionStatus; } /// <summary> /// The Cardholder Authentication Verification Value (CAVV) is a cryptographic value derived by the issuer during payment authentication that can provide evidence of the results of payment authentication during an online purchase. /// </summary> /// <value>The Cardholder Authentication Verification Value (CAVV) is a cryptographic value derived by the issuer during payment authentication that can provide evidence of the results of payment authentication during an online purchase.</value> [DataMember(Name = "cavv", EmitDefaultValue = false)] public string Cavv { get; set; } /// <summary> /// The transaction identifier (XID) is a unique tracking number set by the merchant. /// </summary> /// <value>The transaction identifier (XID) is a unique tracking number set by the merchant.</value> [DataMember(Name = "xid", EmitDefaultValue = false)] public string Xid { get; set; } /// <summary> /// The response transaction UUID. Only applicable to MasterCard. /// </summary> /// <value>The response transaction UUID. Only applicable to MasterCard.</value> [DataMember(Name = "transactionId", EmitDefaultValue = false)] public string TransactionId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Secure3D21AuthenticationResultAllOf {\n"); sb.Append(" Cavv: ").Append(Cavv).Append("\n"); sb.Append(" Xid: ").Append(Xid).Append("\n"); sb.Append(" TransactionId: ").Append(TransactionId).Append("\n"); sb.Append(" AuthenticationResponse: ").Append(AuthenticationResponse).Append("\n"); sb.Append(" TransactionStatus: ").Append(TransactionStatus).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as Secure3D21AuthenticationResultAllOf); } /// <summary> /// Returns true if Secure3D21AuthenticationResultAllOf instances are equal /// </summary> /// <param name="input">Instance of Secure3D21AuthenticationResultAllOf to be compared</param> /// <returns>Boolean</returns> public bool Equals(Secure3D21AuthenticationResultAllOf input) { if (input == null) return false; return ( this.Cavv == input.Cavv || (this.Cavv != null && this.Cavv.Equals(input.Cavv)) ) && ( this.Xid == input.Xid || (this.Xid != null && this.Xid.Equals(input.Xid)) ) && ( this.TransactionId == input.TransactionId || (this.TransactionId != null && this.TransactionId.Equals(input.TransactionId)) ) && ( this.AuthenticationResponse == input.AuthenticationResponse || this.AuthenticationResponse.Equals(input.AuthenticationResponse) ) && ( this.TransactionStatus == input.TransactionStatus || this.TransactionStatus.Equals(input.TransactionStatus) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Cavv != null) hashCode = hashCode * 59 + this.Cavv.GetHashCode(); if (this.Xid != null) hashCode = hashCode * 59 + this.Xid.GetHashCode(); if (this.TransactionId != null) hashCode = hashCode * 59 + this.TransactionId.GetHashCode(); hashCode = hashCode * 59 + this.AuthenticationResponse.GetHashCode(); hashCode = hashCode * 59 + this.TransactionStatus.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { // Cavv (string) maxLength if(this.Cavv != null && this.Cavv.Length > 32) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Cavv, length must be less than 32.", new [] { "Cavv" }); } // Cavv (string) minLength if(this.Cavv != null && this.Cavv.Length < 20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Cavv, length must be greater than 20.", new [] { "Cavv" }); } // Xid (string) maxLength if(this.Xid != null && this.Xid.Length > 32) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Xid, length must be less than 32.", new [] { "Xid" }); } // Xid (string) minLength if(this.Xid != null && this.Xid.Length < 20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Xid, length must be greater than 20.", new [] { "Xid" }); } yield break; } } }
41.533113
283
0.576497
[ "MIT" ]
mrtristan/DotNet
src/Org.OpenAPITools/Model/Secure3D21AuthenticationResultAllOf.cs
12,543
C#
using System; using Xunit; namespace HanumanInstitute.FFmpeg.UnitTests { public static class AssertExtensions { /// <summary> /// Evaluates whether or not the substring is contained within specified value, depending on whether contains is true (Contains) or false (DoesNotContain). /// </summary> /// <param name="expectedSubstring">The string to look for.</param> /// <param name="actualValue">The string to validate.</param> /// <param name="contains">Whether the expected substring should be present or not in the full string.</param> public static void ContainsOrNot(this string actualValue, string expectedSubstring, bool contains) { if (contains) { Assert.Contains(expectedSubstring, actualValue, StringComparison.InvariantCulture); } else { Assert.DoesNotContain(expectedSubstring, actualValue, StringComparison.InvariantCulture); } } } }
38.37037
163
0.639961
[ "BSD-2-Clause" ]
mysteryx93/EmergenceGuardian.Encoder
FFmpeg.UnitTest/AssertExtensions.cs
1,038
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cabinet.Web.Files { public enum FileTypeCategory { Unknown = 0, Document = 1, Image = 2, Audio = 3, Video = 4, Archive = 5, Html = 6, Code = 7, Font = 8 } }
17.95
34
0.56546
[ "MIT" ]
johncmckim/cabinet
src/Cabinet.Web/Files/FileTypeCategory.cs
361
C#
using System; namespace Azure.Durable.Functions.Managers { public static class KineticEnergyManager { /// This is a completely made up (and incorrect) calculation for the kinetic energy of a /// spherical object. Only used to demo Durable Functions in the context of Near Earth Objects. public static float CalculateMegatonTnt( float diameterInKm, float velocityInKmPerSecond) { // Assume fixed density of 2000 kg/m3 const float density = 2000; // Spherical volume calculation = V = 4/3 * (PI * r^3); var volume = 1.25 * Math.PI * Math.Pow(diameterInKm * 1000 / 2, 3); var mass = volume * density; // Kinetic energy calculation = E = 1/2 * m * v^2 var energyInJoule = 0.5 * mass * Math.Pow(velocityInKmPerSecond * 1000, 2); var joulePerMegatonTnt = 4.2 * Math.Pow(10, 15); var energyInMegatonTnt = energyInJoule / joulePerMegatonTnt; return Convert.ToSingle(energyInMegatonTnt); } } }
38.75
103
0.61106
[ "MIT" ]
igordemjanov/azure-durable-functions
Azure.Durable.Functions/Managers/KineticEnergyManager.cs
1,087
C#
using UnityEngine; namespace Puzzle.Room { public class WallNode : MonoBehaviour, IWallNode { public GameObject GameObject => gameObject; [SerializeField, HideInInspector] private bool _top = true; [SerializeField, HideInInspector] private bool _bottom = true; [SerializeField, HideInInspector] private bool _left = true; [SerializeField, HideInInspector] private bool _right = true; [SerializeField, HideInInspector] private bool _front = true; [SerializeField, HideInInspector] private bool _back = true; [SerializeField] private GameObject _topWall = null; [SerializeField] private GameObject _bottomWall = null; [SerializeField] private GameObject _leftWall = null; [SerializeField] private GameObject _rightWall = null; [SerializeField] private GameObject _frontWall = null; [SerializeField] private GameObject _backWall = null; private void ResetWalls() { _top = true; _bottom = true; _left = true; _right = true; _front = true; _back = true; } private void UpdateActivity() { _topWall.SetActive(_top); _bottomWall.SetActive(_bottom); _leftWall.SetActive(_left); _rightWall.SetActive(_right); _frontWall.SetActive(_front); _backWall.SetActive(_back); } public void AutomaticWalls() { Transform parent = transform.parent; ResetWalls(); for (int i = 0; i < parent.childCount; i++) { Transform c = parent.GetChild(i); if (c == transform) continue; if (!c.gameObject.activeSelf) continue; WallNode wn = c.GetComponent<WallNode>(); if (wn == null) continue; if (Vector3.Distance(c.position, transform.position) > 5.5f) continue; UpdateWallUsingOther(c); } UpdateActivity(); } private void UpdateWallUsingOther(Transform other) { float len = Mathf.Max(Mathf.Max(transform.localScale.x, transform.localScale.y), transform.localScale.z); float min = len - 0.5f; float max = len + 0.5f; float iMin = -len - 0.5f; float iMax = -len + 0.5f; Vector3 delta = other.position - transform.position; if (delta.x < max && delta.x > min) _right = false; else if (delta.x < iMax && delta.x > iMin) _left = false; if (delta.y < max && delta.y > min) _top = false; else if (delta.y < iMax && delta.y > iMin) _bottom = false; if (delta.z < max && delta.z > min) _front = false; else if (delta.z < iMax && delta.z > iMin) _back = false; } } }
28.588235
108
0.68107
[ "Apache-2.0" ]
BrentFarris/ForgeAlloy
ForgeAlloyUnity/Assets/Examples/ComplexSample/src/Room/WallNode.cs
2,432
C#
using AH.NWMS.DAL; using AH.NWMS.MODEL; using AH.PRMS.MODEL; using AH.DRUGS.MODEL; using System; using System.Collections.Generic; using System.Linq; using System.Text; using AH.OPD.MODEL; namespace AH.NWMS.BLL { public class IPDPrescriptionBLL { /* public IPDDoctor GetDoctorsDetails(string DocID) { return new IPDPrescriptionDAL().GetDoctorsDetails(DocID); }*/ public short SaveIPDPrescription(IPDPrescription prs) { return new IPDPrescriptionDAL().SaveIPDPrescription(prs); } public short EditIPDPrescription(IPDPrescription Iprs) { return new IPDPrescriptionDAL().EditIPDPrescription(Iprs); } public List<IPDPrescription> GetPrescribedDrugs(string regId) { return new IPDPrescriptionDAL().GetPrescribedDrugs(regId); } public List<IPDPrescription> GetPrescribedTests(string regId) { return new IPDPrescriptionDAL().GetPrescribedTests(regId); } public short SaveDischargeAdvices(IPDPrescription prs) { return new IPDPrescriptionDAL().SaveDischargeAdvices(prs); } public short IsDischargeAdvCreated(string regId) { return new IPDPrescriptionDAL().IsDischargeAdvCreated(regId); } public IPDPrescription GetDischargeAdvicesForEdit(string regId) { return new IPDPrescriptionDAL().GetDischargeAdvicesForEdit(regId); } public short EditDischargeAdvices(IPDPrescription Iprs) { return new IPDPrescriptionDAL().EditDischargeAdvices(Iprs); } public IPDPrescription GetIPDPrescriptionForEdit(string visit_no, string Reg_ID) { return new IPDPrescriptionDAL().GetIPDPrescriptionForEdit(visit_no, Reg_ID); } public short IsDrugReqDone(string visit_id, string drug_id) { return new IPDPrescriptionDAL().IsDrugReqDone(visit_id, drug_id); } } }
29.910448
87
0.672156
[ "Apache-2.0" ]
atiq-shumon/DotNetProjects
Hospital_ERP_VS13-WCF_WF/AH.NWMS/BLL/IPDPrescriptionBLL.cs
2,006
C#
using UnityEngine.UI; using UnityEngine; public class SetText : MonoBehaviour { public Text Version; void Start() { Version.text = LoadJson.Version.ToString(); } }
13.714286
51
0.651042
[ "MIT" ]
SolomonRosemite/Unity-FutureCube
FutureCube/Assets/Scripts/SetText.cs
194
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ProjectManager : MonoBehaviour { //All projects that will be managed public List<Project> projects; //The levels that each project has public List<int> levels; //The amount of time that each project has until it is completed public List<int> time; /// <summary> /// Gets the amount of time that each project has remaining /// </summary> /// <param name="project">The project you want to get the time of</param> /// <returns>Returns the amount of time remaining on the project</returns> public int GetTime(Project project){ return time[projects.IndexOf(project)]; } /// <summary> /// Gets the level of a specific project /// </summary> /// <param name="project">The project you want to get the level of</param> /// <returns>Returns the level of a specific project</returns> public int GetLevel(Project project){ return levels[projects.IndexOf(project)]; } /// <summary> /// Checks a project to see if it is constantly processing /// </summary> /// <param name="project">The project that you want to check</param> /// <returns>Returns a boolean determining whether the project is constant or not</returns> public bool IsConstant(Project project){ return project.projectLength.x < 0; } /// <summary> /// Gets the level of the project and checks if it is maxed /// </summary> /// <param name="project">The project you are checking</param> /// <returns>Returns a boolean stating whether a project is maxed or not</returns> public bool IsMaxed(Project project){ return levels[projects.IndexOf(project)] == 3; } /// <summary> /// /// </summary> /// <param name="type"></param> /// <returns></returns> public float FX(FXT type){ foreach (Project p in projects) { if(p.type == type){ if(IsConstant(p)){ return p.amount[0] * GetLevel(p); }else{ if(GetLevel(p) == 0){ return 1f; }else if(GetLevel(p) == 4){ return p.amount[2]; }else{ return p.amount[GetLevel(p)-1]; } } } } return 1f; } /// <summary> /// /// </summary> /// <param name="project"></param> /// <returns></returns> public int GetLength(Project project){ if(GetLevel(project)<3){ return project.projectLength[GetLevel(project)]; } return 0; } /// <summary> /// /// </summary> public void UpdateProjects(){ for (int i = 0; i < projects.Count; i++) { if(IsConstant(projects[i])){ levels[i] = 0; } } // Process research foreach (BuildingSpot spot in GM.I.city.buildings) { if(spot.currentProject != null){ int index = projects.IndexOf(spot.currentProject); if(!spot.currentProject.monthlyCost.Limited(GM.I.resource.resources)){ if(IsConstant(spot.currentProject)){ levels[index] += 1; }else{ time[index]++; } } } } // Process finished research for (int i = 0; i < projects.Count; i++) { if(!IsConstant(projects[i])){ if(levels[i] < 4){ if(GetLength(projects[i]) <= time[i]){ levels[i]++; time[i] = 0; } } } } // Stop finished projects foreach (BuildingSpot spot in GM.I.city.buildings) { if(spot.currentProject != null){ int index = projects.IndexOf(spot.currentProject); if((time[index] == 0 || levels[index] == 4) && !IsConstant(projects[index])){ spot.currentProject = null; } } } } }
29.69863
95
0.505996
[ "MIT" ]
EternityDoom/gameoff2020
Unity Project/Assets/SCRIPT/ProjectManager.cs
4,338
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("FrequentNumber")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FrequentNumber")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("b37db7b9-9409-42a5-aef5-1287e8f137e6")] // 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.864865
84
0.745896
[ "MIT" ]
PetarTilevRusev/Arrays-Homework
FrequentNumber/Properties/AssemblyInfo.cs
1,404
C#
// Copyright (c) Microsoft Corporation. All Rights Reserved. // Licensed under the MIT License. using Android.OS; using Microsoft.Datasync.Client.Utils; using System; using System.Diagnostics.CodeAnalysis; namespace Microsoft.Datasync.Client.Platforms { /// <summary> /// Android-specific implementation of the <see cref="IPlatformInformation"/> interface. /// </summary> internal class PlatformInformation : IPlatformInformation { /// <summary> /// Information about the OS. /// </summary> public IOSInformation OS => new OSInformation { Architecture = System.Environment.OSVersion.Platform.ToString(), Name = "Android", Version = Build.VERSION.Release }; /// <summary> /// True if this is running on an emulated device /// </summary> public bool IsEmulator => Build.Brand.Equals("generic", StringComparison.InvariantCultureIgnoreCase); /// <summary> /// Converts the IsEmulator into a string. /// </summary> /// <remarks> /// Excluded from code coverage because the string.Empty version will never be returned in a test situation. /// </remarks> [ExcludeFromCodeCoverage] private string Emulator => IsEmulator ? ";test" : ""; /// <summary> /// The details section of the <c>User-Agent</c> header. /// </summary> public string UserAgentDetails { get => $"lang=Managed;os={OS.Name}/{OS.Version};arch={OS.Architecture};version={Platform.AssemblyVersion}{Emulator}"; } } }
33.489796
129
0.618525
[ "MIT" ]
Azure/azure-mobile-apps
sdk/dotnet/src/Microsoft.Datasync.Client/Platforms/android/PlatformInformation.cs
1,643
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Threading.Tasks; using MySql.Data.MySqlClient; using System.Data.SQLite; namespace test_query { class Program { //using mysql //static void Main(string[] args) //{ // Console.Title = "test_query"; // var conn = new MySqlConnection("Server=localhost; Uid=root;"); // string q = "SHOW DATABASES"; // try // { // conn.Open(); // //var cmd = new MySqlCommand(q, conn); // //Console.WriteLine(cmd.ExecuteNonQuery()); // //MySqlDataReader reader = cmd.ExecuteReader(); // var da = new MySqlDataAdapter(q, conn); // DataSet ds = new DataSet(); // da.Fill(ds); // for (int i = 0; i < ds.Tables.Count; i++) // { // for (int j = 0; j < ds.Tables[i].Rows.Count; j++) // { // for (int k = 0; k < ds.Tables[i].Columns.Count; k++) // { // Console.Write(ds.Tables[i].Rows[j].ItemArray[k]); // } // } // } // } // catch (MySqlException ex) { Console.WriteLine(string.Concat(ex.Number, ex.Message)); } // finally { conn.Close(); } // Console.ReadKey(); //} //using sqlite static void Main(string[] args) { Console.Title = "test sqlite"; do{ Console.Clear(); string cs = "Data Source="; int select = 0; string dbName = null, tblName = null; Console.WriteLine("1. List Table"); Console.WriteLine("2. Create Table"); Console.WriteLine("3. Create Database"); Console.Write("Pilih menu : "); try { select = Convert.ToInt32(Console.ReadLine()); switch (select) { case 1: Console.WriteLine(); using (var conn = new SQLiteConnection(cs + "db_lite.db")) { try { conn.Open(); string q = "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY 1;"; using (var da = new SQLiteDataAdapter(q, conn)) { var ds = new DataSet(); da.Fill(ds); //Console.WriteLine(ds.Tables.Count); for (int i = 0; i < ds.Tables.Count; i++) { for (int j = 0; j < ds.Tables[i].Rows.Count; j++) { for (int k = 0; k < ds.Tables[i].Columns.Count; k++) { Console.Write(ds.Tables[i].Rows[j].ItemArray[k]); } Console.WriteLine(); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { conn.Close(); } } break; case 2: Console.Write("Input nama table : "); tblName = Console.ReadLine(); using (var conn = new SQLiteConnection(cs + "db_lite.db")) { try { conn.Open(); string q = "CREATE TABLE " + tblName + " (_id int not null, _nama varchar(30) not null);"; using (var cmd = new SQLiteCommand(q, conn)) { cmd.ExecuteNonQuery(); Console.WriteLine("table " + tblName + " telah di buat"); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { conn.Close(); } } break; case 3: Console.Write("Input nama database : "); dbName = Console.ReadLine(); try { SQLiteConnection.CreateFile(dbName); Console.WriteLine("database " + dbName + " telah di buat"); } catch (Exception ex) { Console.WriteLine(ex.Message); } break; default: Console.WriteLine("Input diluar range"); break; } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.Write("\nLagi ? Y/T"); } while (char.ToUpper(Console.ReadKey().KeyChar) != 'T'); } } }
43.783582
132
0.343958
[ "MIT" ]
ChupUchup/Backup-Me
random/test_query/Program.cs
5,869
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("_4.Download_file")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("_4.Download_file")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("f38f3389-37f3-493e-b2ba-8642c2d400b6")] // 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.972973
84
0.745196
[ "MIT" ]
todorm85/TelerikAcademy
Courses/Programming/C# Part 2/07. Exception Handling/4. Download file/Properties/AssemblyInfo.cs
1,408
C#
using System; using System.Collections.Generic; using System.Linq; namespace DevilDaggersCore.Game { public static class GameInfo { #region V1 public static readonly Dagger V1Default = new(GameVersion.V1, "Default", "444444", null); public static readonly Dagger V1Bronze = new(GameVersion.V1, "Bronze", "CD7F32", 60); public static readonly Dagger V1Silver = new(GameVersion.V1, "Silver", "DDDDDD", 120); public static readonly Dagger V1Golden = new(GameVersion.V1, "Golden", "FFDF00", 250); public static readonly Dagger V1Devil = new(GameVersion.V1, "Devil", "FF0000", 500); public static readonly Upgrade V1Level1 = new(GameVersion.V1, "Level 1", "BB5500", 20, 10, null, null, "N/A"); public static readonly Upgrade V1Level2 = new(GameVersion.V1, "Level 2", "FFAA00", 40, 20, null, null, "10 gems"); public static readonly Upgrade V1Level3 = new(GameVersion.V1, "Level 3", "00FFFF", 80, 40, 40, 40, "70 gems"); // TODO: Figure out Level 3 homing spray. public static readonly Death V1Fallen = new(GameVersion.V1, "FALLEN", "DDDDDD", 0); public static readonly Death V1Swarmed = new(GameVersion.V1, "SWARMED", "352710", 1); public static readonly Death V1Impaled = new(GameVersion.V1, "IMPALED", "433114", 2); public static readonly Death V1Infested = new(GameVersion.V1, "INFESTED", "99A100", 4); public static readonly Death V1Purged = new(GameVersion.V1, "PURGED", "4E3000", 6); public static readonly Death V1Sacrificed = new(GameVersion.V1, "SACRIFICED", "804E00", 8); public static readonly Death V1Eviscerated = new(GameVersion.V1, "EVISCERATED", "837E75", 9); public static readonly Death V1Annihilated = new(GameVersion.V1, "ANNIHILATED", "BE2C20", 10); public static readonly Death V1Stricken = new(GameVersion.V1, "STRICKEN", "DCCB00", 16); public static readonly Death V1Devastated = new(GameVersion.V1, "DEVASTATED", "FF0000", 17); public static readonly Death V1Dismembered = new(GameVersion.V1, "DISMEMBERED", "804E00", 18); public static readonly Enemy V1Squid1 = new(GameVersion.V1, "Squid I", "4E3000", 10, 1, 2, 0x0, V1Purged, 1, null, 3); public static readonly Enemy V1Squid2 = new(GameVersion.V1, "Squid II", "804E00", 20, 2, 3, 0x1, V1Sacrificed, 2, null, 39); public static readonly Enemy V1Centipede = new(GameVersion.V1, "Centipede", "837E75", 75, 25, 25, 0x2, V1Eviscerated, 25, null, 114); public static readonly Enemy V1Gigapede = new(GameVersion.V1, "Gigapede", "7B5157", 250, 50, 50, 0x5, V1Eviscerated, 50, null, 264); public static readonly Enemy V1Leviathan = new(GameVersion.V1, "Leviathan", "FF0000", 600, 6, 6, 0x4, V1Devastated, 600, null, 397); public static readonly Enemy V1Spider1 = new(GameVersion.V1, "Spider I", "097A00", 25, 1, 1, 0x3, V1Infested, 3, null, 39); public static readonly Enemy V1Skull1 = new(GameVersion.V1, "Skull I", "352710", 1, 0, 0, null, V1Swarmed, 0.25f, null, null, V1Squid1, V1Squid2); public static readonly Enemy V1Skull2 = new(GameVersion.V1, "Skull II", "433114", 5, 1, 1, null, V1Impaled, 1, null, null, V1Squid1); public static readonly Enemy V1Skull3 = new(GameVersion.V1, "Skull III", "6E5021", 10, 1, 1, null, V1Dismembered, 1, null, null, V1Squid2); public static readonly Enemy V1TransmutedSkull2 = new(GameVersion.V1, "Transmuted Skull II", "721A13", 10, 1, 1, null, V1Impaled, 1, null, null, V1Leviathan); public static readonly Enemy V1TransmutedSkull3 = new(GameVersion.V1, "Transmuted Skull III", "982319", 20, 1, 1, null, V1Dismembered, 2, null, null, V1Leviathan); public static readonly Enemy V1TransmutedSkull4 = new(GameVersion.V1, "Transmuted Skull IV", "BE2C20", 100, 0, 0, null, V1Annihilated, 10, null, null, V1Leviathan); public static readonly Enemy V1SpiderEgg1 = new(GameVersion.V1, "Spider Egg I", "99A100", 3, 0, 0, null, V1Infested, 3, null, null, V1Spider1); public static readonly Enemy V1Spiderling = new(GameVersion.V1, "Spiderling", "DCCB00", 3, 0, 0, null, V1Stricken, 1, null, null, V1SpiderEgg1); #endregion V1 #region V2 public static readonly Dagger V2Default = new(GameVersion.V2, "Default", "444444", null); public static readonly Dagger V2Bronze = new(GameVersion.V2, "Bronze", "CD7F32", 60); public static readonly Dagger V2Silver = new(GameVersion.V2, "Silver", "DDDDDD", 120); public static readonly Dagger V2Golden = new(GameVersion.V2, "Golden", "FFDF00", 250); public static readonly Dagger V2Devil = new(GameVersion.V2, "Devil", "FF0000", 500); public static readonly Upgrade V2Level1 = new(GameVersion.V2, "Level 1", "BB5500", 20, 10, null, null, "N/A"); public static readonly Upgrade V2Level2 = new(GameVersion.V2, "Level 2", "FFAA00", 40, 20, null, null, "10 gems"); public static readonly Upgrade V2Level3 = new(GameVersion.V2, "Level 3", "00FFFF", 80, 40, 40, 20, "70 gems"); public static readonly Upgrade V2Level4 = new(GameVersion.V2, "Level 4", "FF0099", 106f + 2f / 3f, 60, 40, 30, "150 stored homing daggers"); public static readonly Death V2Fallen = new(GameVersion.V2, "FALLEN", "DDDDDD", 0); public static readonly Death V2Swarmed = new(GameVersion.V2, "SWARMED", "352710", 1); public static readonly Death V2Impaled = new(GameVersion.V2, "IMPALED", "433114", 2); public static readonly Death V2Gored = new(GameVersion.V2, "GORED", "6E5021", 3); public static readonly Death V2Infested = new(GameVersion.V2, "INFESTED", "99A100", 4); public static readonly Death V2Opened = new(GameVersion.V2, "OPENED", "976E2E", 5); public static readonly Death V2Purged = new(GameVersion.V2, "PURGED", "4E3000", 6); public static readonly Death V2Desecrated = new(GameVersion.V2, "DESECRATED", "804E00", 7); public static readonly Death V2Sacrificed = new(GameVersion.V2, "SACRIFICED", "AF6B00", 8); public static readonly Death V2Eviscerated = new(GameVersion.V2, "EVISCERATED", "837E75", 9); public static readonly Death V2Annihilated = new(GameVersion.V2, "ANNIHILATED", "7B5157", 10); public static readonly Death V2Envenomated = new(GameVersion.V2, "ENVENOMATED", "657A00", 12); public static readonly Death V2Stricken = new(GameVersion.V2, "STRICKEN", "DCCB00", 16); public static readonly Death V2Devastated = new(GameVersion.V2, "DEVASTATED", "FF0000", 17); public static readonly Enemy V2Squid1 = new(GameVersion.V2, "Squid I", "4E3000", 10, 1, 2, 0x0, V2Purged, 1, 1, 3); public static readonly Enemy V2Squid2 = new(GameVersion.V2, "Squid II", "804E00", 20, 2, 3, 0x1, V2Desecrated, 2, 1, 39); public static readonly Enemy V2Squid3 = new(GameVersion.V2, "Squid III", "AF6B00", 90, 3, 3, 0x6, V2Sacrificed, 3, 9, 244); public static readonly Enemy V2Centipede = new(GameVersion.V2, "Centipede", "837E75", 75, 25, 25, 0x2, V2Eviscerated, 25, 25, 114); public static readonly Enemy V2Gigapede = new(GameVersion.V2, "Gigapede", "7B5157", 250, 50, 50, 0x5, V2Annihilated, 50, 50, 259); public static readonly Enemy V2Leviathan = new(GameVersion.V2, "Leviathan", "FF0000", 1500, 6, 6, 0x4, V2Devastated, 1500, 1500, 350); public static readonly Enemy V2Spider1 = new(GameVersion.V2, "Spider I", "097A00", 25, 1, 1, 0x3, V2Infested, 3, 3, 39); public static readonly Enemy V2Spider2 = new(GameVersion.V2, "Spider II", "13FF00", 200, 1, 1, 0x8, V2Envenomated, 20, 20, 274); public static readonly Enemy V2Skull1 = new(GameVersion.V2, "Skull I", "352710", 1, 0, 0, null, V2Swarmed, 0.25f, 0.25f, null, V2Squid1, V2Squid2, V2Squid3); public static readonly Enemy V2Skull2 = new(GameVersion.V2, "Skull II", "433114", 5, 1, 1, null, V2Impaled, 1, 1, null, V2Squid1); public static readonly Enemy V2Skull3 = new(GameVersion.V2, "Skull III", "6E5021", 10, 1, 1, null, V2Gored, 1, 1, null, V2Squid2); public static readonly Enemy V2Skull4 = new(GameVersion.V2, "Skull IV", "976E2E", 100, 0, 0, null, V2Opened, 10, 10, null, V2Squid3); public static readonly Enemy V2TransmutedSkull1 = new(GameVersion.V2, "Transmuted Skull I", "4C110C", 10, 0, 0, null, V2Swarmed, 0.25f, 10, null, V2Leviathan); public static readonly Enemy V2TransmutedSkull2 = new(GameVersion.V2, "Transmuted Skull II", "721A13", 20, 1, 1, null, V2Impaled, 2, 2, null, V2Leviathan); public static readonly Enemy V2TransmutedSkull3 = new(GameVersion.V2, "Transmuted Skull III", "982319", 100, 1, 1, null, V2Gored, 10, 10, null, V2Leviathan); public static readonly Enemy V2TransmutedSkull4 = new(GameVersion.V2, "Transmuted Skull IV", "BE2C20", 300, 0, 0, null, V2Opened, 30, 30, null, V2Leviathan); public static readonly Enemy V2SpiderEgg1 = new(GameVersion.V2, "Spider Egg I", "99A100", 3, 0, 0, null, V2Infested, 3, 3, null, V2Spider1); public static readonly Enemy V2SpiderEgg2 = new(GameVersion.V2, "Spider Egg II", "657A00", 3, 0, 0, null, V2Envenomated, 3, 3, null, V2Spider2); public static readonly Enemy V2Spiderling = new(GameVersion.V2, "Spiderling", "DCCB00", 3, 0, 0, null, V2Stricken, 1, 1, null, V2SpiderEgg1, V2SpiderEgg2); public static readonly Enemy V2Andras = new(GameVersion.V2, "Andras", "666666", 25, 1, 1, 0x7, null, null, null, null); #endregion V2 #region V3 public static readonly Dagger V3Default = new(GameVersion.V3, "Default", "444444", null); public static readonly Dagger V3Bronze = new(GameVersion.V3, "Bronze", "CD7F32", 60); public static readonly Dagger V3Silver = new(GameVersion.V3, "Silver", "DDDDDD", 120); public static readonly Dagger V3Golden = new(GameVersion.V3, "Golden", "FFDF00", 250); public static readonly Dagger V3Devil = new(GameVersion.V3, "Devil", "FF0000", 500); public static readonly Upgrade V3Level1 = new(GameVersion.V3, "Level 1", "BB5500", 20, 10, null, null, "N/A"); public static readonly Upgrade V3Level2 = new(GameVersion.V3, "Level 2", "FFAA00", 40, 20, null, null, "10 gems"); public static readonly Upgrade V3Level3 = new(GameVersion.V3, "Level 3", "00FFFF", 80, 40, 40, 20, "70 gems"); public static readonly Upgrade V3Level4 = new(GameVersion.V3, "Level 4", "FF0099", 106f + 2f / 3f, 60, 40, 30, "150 stored homing daggers"); public static readonly Death V3Fallen = new(GameVersion.V3, "FALLEN", "DDDDDD", 0); public static readonly Death V3Swarmed = new(GameVersion.V3, "SWARMED", "352710", 1); public static readonly Death V3Impaled = new(GameVersion.V3, "IMPALED", "433114", 2); public static readonly Death V3Gored = new(GameVersion.V3, "GORED", "6E5021", 3); public static readonly Death V3Infested = new(GameVersion.V3, "INFESTED", "DCCB00", 4); public static readonly Death V3Opened = new(GameVersion.V3, "OPENED", "976E2E", 5); public static readonly Death V3Purged = new(GameVersion.V3, "PURGED", "4E3000", 6); public static readonly Death V3Desecrated = new(GameVersion.V3, "DESECRATED", "804E00", 7); public static readonly Death V3Sacrificed = new(GameVersion.V3, "SACRIFICED", "AF6B00", 8); public static readonly Death V3Eviscerated = new(GameVersion.V3, "EVISCERATED", "837E75", 9); public static readonly Death V3Annihilated = new(GameVersion.V3, "ANNIHILATED", "478B41", 10); public static readonly Death V3Intoxicated = new(GameVersion.V3, "INTOXICATED", "99A100", 11); public static readonly Death V3Envenomated = new(GameVersion.V3, "ENVENOMATED", "657A00", 12); public static readonly Death V3Incarnated = new(GameVersion.V3, "INCARNATED", "FF0000", 13); public static readonly Death V3Discarnated = new(GameVersion.V3, "DISCARNATED", "FF3131", 14); public static readonly Death V3Barbed = new(GameVersion.V3, "BARBED", "771D00", 15); public static readonly Enemy V3Squid1 = new(GameVersion.V3, "Squid I", "4E3000", 10, 1, 2, 0x0, V3Purged, 1, 1, 3); public static readonly Enemy V3Squid2 = new(GameVersion.V3, "Squid II", "804E00", 20, 2, 3, 0x1, V3Desecrated, 2, 1, 39); public static readonly Enemy V3Squid3 = new(GameVersion.V3, "Squid III", "AF6B00", 90, 3, 3, 0x6, V3Sacrificed, 3, 9, 244); public static readonly Enemy V3Centipede = new(GameVersion.V3, "Centipede", "837E75", 75, 25, 25, 0x2, V3Eviscerated, 25, 25, 114); public static readonly Enemy V3Gigapede = new(GameVersion.V3, "Gigapede", "478B41", 250, 50, 50, 0x5, V3Annihilated, 50, 50, 259); public static readonly Enemy V3Ghostpede = new(GameVersion.V3, "Ghostpede", "C8A2C8", 500, 10, 10, 0x9, V3Intoxicated, null, null, 442); public static readonly Enemy V3Leviathan = new(GameVersion.V3, "Leviathan", "FF0000", 1500, 6, 6, 0x4, V3Incarnated, 1500, 1500, 350); public static readonly Enemy V3Thorn = new(GameVersion.V3, "Thorn", "771D00", 120, 0, 0, 0x7, V3Barbed, 12, 12, 447); public static readonly Enemy V3Spider1 = new(GameVersion.V3, "Spider I", "097A00", 25, 1, 1, 0x3, V3Intoxicated, 3, 3, 39); public static readonly Enemy V3Spider2 = new(GameVersion.V3, "Spider II", "13FF00", 200, 1, 1, 0x8, V3Envenomated, 20, 20, 274); public static readonly Enemy V3TheOrb = new(GameVersion.V3, "The Orb", "FF3131", 2400, 0, 0, null, V3Discarnated, 2400, 2400, null, V3Leviathan); public static readonly Enemy V3Skull1 = new(GameVersion.V3, "Skull I", "352710", 1, 0, 0, null, V3Swarmed, 0.25f, 0.25f, null, V3Squid1, V3Squid2, V3Squid3); public static readonly Enemy V3Skull2 = new(GameVersion.V3, "Skull II", "433114", 5, 1, 1, null, V3Impaled, 1, 1, null, V3Squid1); public static readonly Enemy V3Skull3 = new(GameVersion.V3, "Skull III", "6E5021", 10, 1, 1, null, V3Gored, 1, 1, null, V3Squid2); public static readonly Enemy V3Skull4 = new(GameVersion.V3, "Skull IV", "976E2E", 100, 0, 0, null, V3Opened, 10, 10, null, V3Squid3); public static readonly Enemy V3TransmutedSkull1 = new(GameVersion.V3, "Transmuted Skull I", "4C110C", 10, 0, 0, null, V3Swarmed, 0.25f, 10, null, V3Leviathan, V3TheOrb); public static readonly Enemy V3TransmutedSkull2 = new(GameVersion.V3, "Transmuted Skull II", "721A13", 20, 1, 1, null, V3Impaled, 2, 2, null, V3Leviathan, V3TheOrb); public static readonly Enemy V3TransmutedSkull3 = new(GameVersion.V3, "Transmuted Skull III", "982319", 100, 1, 1, null, V3Gored, 10, 10, null, V3Leviathan, V3TheOrb); public static readonly Enemy V3TransmutedSkull4 = new(GameVersion.V3, "Transmuted Skull IV", "BE2C20", 300, 0, 0, null, V3Opened, 30, 30, null, V3Leviathan, V3TheOrb); public static readonly Enemy V3SpiderEgg1 = new(GameVersion.V3, "Spider Egg I", "99A100", 3, 0, 0, null, V3Intoxicated, 3, 3, null, V3Spider1); public static readonly Enemy V3SpiderEgg2 = new(GameVersion.V3, "Spider Egg II", "657A00", 3, 0, 0, null, V3Envenomated, 3, 3, null, V3Spider2); public static readonly Enemy V3Spiderling = new(GameVersion.V3, "Spiderling", "DCCB00", 3, 0, 0, null, V3Infested, 1, 1, null, V3SpiderEgg1, V3SpiderEgg2); #endregion V3 #region V3.1 public static readonly Dagger V31Default = new(GameVersion.V31, "Default", "444444", null); public static readonly Dagger V31Bronze = new(GameVersion.V31, "Bronze", "CD7F32", 60); public static readonly Dagger V31Silver = new(GameVersion.V31, "Silver", "DDDDDD", 120); public static readonly Dagger V31Golden = new(GameVersion.V31, "Golden", "FFDF00", 250); public static readonly Dagger V31Devil = new(GameVersion.V31, "Devil", "FF0000", 500); public static readonly Dagger V31LeviathanDagger = new(GameVersion.V31, "Leviathan", "A00000", 1000); public static readonly Upgrade V31Level1 = new(GameVersion.V31, "Level 1", "BB5500", 20, 10, null, null, "N/A"); public static readonly Upgrade V31Level2 = new(GameVersion.V31, "Level 2", "FFAA00", 40, 20, null, null, "10 gems"); public static readonly Upgrade V31Level3 = new(GameVersion.V31, "Level 3", "00FFFF", 80, 40, 40, 20, "70 gems"); public static readonly Upgrade V31Level4 = new(GameVersion.V31, "Level 4", "FF0099", 106f + 2f / 3f, 60, 40, 30, "150 stored homing daggers"); public static readonly Death V31Fallen = new(GameVersion.V31, "FALLEN", "DDDDDD", 0); public static readonly Death V31Swarmed = new(GameVersion.V31, "SWARMED", "352710", 1); public static readonly Death V31Impaled = new(GameVersion.V31, "IMPALED", "433114", 2); public static readonly Death V31Gored = new(GameVersion.V31, "GORED", "6E5021", 3); public static readonly Death V31Infested = new(GameVersion.V31, "INFESTED", "DCCB00", 4); public static readonly Death V31Opened = new(GameVersion.V31, "OPENED", "976E2E", 5); public static readonly Death V31Purged = new(GameVersion.V31, "PURGED", "4E3000", 6); public static readonly Death V31Desecrated = new(GameVersion.V31, "DESECRATED", "804E00", 7); public static readonly Death V31Sacrificed = new(GameVersion.V31, "SACRIFICED", "AF6B00", 8); public static readonly Death V31Eviscerated = new(GameVersion.V31, "EVISCERATED", "837E75", 9); public static readonly Death V31Annihilated = new(GameVersion.V31, "ANNIHILATED", "478B41", 10); public static readonly Death V31Intoxicated = new(GameVersion.V31, "INTOXICATED", "99A100", 11); public static readonly Death V31Envenomated = new(GameVersion.V31, "ENVENOMATED", "657A00", 12); public static readonly Death V31Incarnated = new(GameVersion.V31, "INCARNATED", "FF0000", 13); public static readonly Death V31Discarnated = new(GameVersion.V31, "DISCARNATED", "FF3131", 14); public static readonly Death V31Entangled = new(GameVersion.V31, "ENTANGLED", "771D00", 15); public static readonly Death V31Haunted = new(GameVersion.V31, "HAUNTED", "C8A2C8", 16); public static readonly Enemy V31Squid1 = new(GameVersion.V31, "Squid I", "4E3000", 10, 1, 2, 0x0, V31Purged, 1, 1, 3); public static readonly Enemy V31Squid2 = new(GameVersion.V31, "Squid II", "804E00", 20, 2, 3, 0x1, V31Desecrated, 2, 1, 39); public static readonly Enemy V31Squid3 = new(GameVersion.V31, "Squid III", "AF6B00", 90, 3, 3, 0x6, V31Sacrificed, 3, 9, 244); public static readonly Enemy V31Centipede = new(GameVersion.V31, "Centipede", "837E75", 75, 25, 25, 0x2, V31Eviscerated, 25, 25, 114); public static readonly Enemy V31Gigapede = new(GameVersion.V31, "Gigapede", "478B41", 250, 50, 50, 0x5, V31Annihilated, 50, 50, 259); public static readonly Enemy V31Ghostpede = new(GameVersion.V31, "Ghostpede", "C8A2C8", 500, 10, 10, 0x9, V31Haunted, null, null, 442); public static readonly Enemy V31Leviathan = new(GameVersion.V31, "Leviathan", "FF0000", 1500, 6, 6, 0x4, V31Incarnated, 1500, 1500, 350); public static readonly Enemy V31Thorn = new(GameVersion.V31, "Thorn", "771D00", 120, 0, 0, 0x7, V31Entangled, 12, 12, 447); public static readonly Enemy V31Spider1 = new(GameVersion.V31, "Spider I", "097A00", 25, 1, 1, 0x3, V31Intoxicated, 3, 3, 39); public static readonly Enemy V31Spider2 = new(GameVersion.V31, "Spider II", "13FF00", 200, 1, 1, 0x8, V31Envenomated, 20, 20, 274); public static readonly Enemy V31TheOrb = new(GameVersion.V31, "The Orb", "FF3131", 2400, 0, 0, null, V31Discarnated, 2400, 2400, null, V31Leviathan); public static readonly Enemy V31Skull1 = new(GameVersion.V31, "Skull I", "352710", 1, 0, 0, null, V31Swarmed, 0.25f, 0.25f, null, V31Squid1, V31Squid2, V31Squid3); public static readonly Enemy V31Skull2 = new(GameVersion.V31, "Skull II", "433114", 5, 1, 1, null, V31Impaled, 1, 1, null, V31Squid1); public static readonly Enemy V31Skull3 = new(GameVersion.V31, "Skull III", "6E5021", 10, 1, 1, null, V31Gored, 1, 1, null, V31Squid2); public static readonly Enemy V31Skull4 = new(GameVersion.V31, "Skull IV", "976E2E", 100, 0, 0, null, V31Opened, 10, 10, null, V31Squid3); public static readonly Enemy V31TransmutedSkull1 = new(GameVersion.V31, "Transmuted Skull I", "4C110C", 10, 0, 0, null, V31Swarmed, 0.25f, 10, null, V31Leviathan, V31TheOrb); public static readonly Enemy V31TransmutedSkull2 = new(GameVersion.V31, "Transmuted Skull II", "721A13", 20, 1, 1, null, V31Impaled, 2, 2, null, V31Leviathan, V31TheOrb); public static readonly Enemy V31TransmutedSkull3 = new(GameVersion.V31, "Transmuted Skull III", "982319", 100, 1, 1, null, V31Gored, 10, 10, null, V31Leviathan, V31TheOrb); public static readonly Enemy V31TransmutedSkull4 = new(GameVersion.V31, "Transmuted Skull IV", "BE2C20", 300, 0, 0, null, V31Opened, 30, 30, null, V31Leviathan, V31TheOrb); public static readonly Enemy V31SpiderEgg1 = new(GameVersion.V31, "Spider Egg I", "99A100", 3, 0, 0, null, V31Intoxicated, 3, 3, null, V31Spider1); public static readonly Enemy V31SpiderEgg2 = new(GameVersion.V31, "Spider Egg II", "657A00", 3, 0, 0, null, V31Envenomated, 3, 3, null, V31Spider2); public static readonly Enemy V31Spiderling = new(GameVersion.V31, "Spiderling", "DCCB00", 3, 0, 0, null, V31Infested, 1, 1, null, V31SpiderEgg1, V31SpiderEgg2); #endregion V3.1 #region V3.2 public static readonly Dagger V32Default = new(GameVersion.V32, "Default", "444444", null); public static readonly Dagger V32Bronze = new(GameVersion.V32, "Bronze", "CD7F32", 60); public static readonly Dagger V32Silver = new(GameVersion.V32, "Silver", "DDDDDD", 120); public static readonly Dagger V32Golden = new(GameVersion.V32, "Golden", "FFDF00", 250); public static readonly Dagger V32Devil = new(GameVersion.V32, "Devil", "FF0000", 500); public static readonly Dagger V32LeviathanDagger = new(GameVersion.V32, "Leviathan", "A00000", 1000); public static readonly Upgrade V32Level1 = new(GameVersion.V32, "Level 1", "BB5500", 20, 10, null, null, "N/A"); public static readonly Upgrade V32Level2 = new(GameVersion.V32, "Level 2", "FFAA00", 40, 20, null, null, "10 gems"); public static readonly Upgrade V32Level3 = new(GameVersion.V32, "Level 3", "00FFFF", 80, 40, 40, 20, "70 gems"); public static readonly Upgrade V32Level4 = new(GameVersion.V32, "Level 4", "FF0099", 106f + 2f / 3f, 60, 40, 30, "150 stored homing daggers"); public static readonly Death V32Fallen = new(GameVersion.V32, "FALLEN", "DDDDDD", 0); public static readonly Death V32Swarmed = new(GameVersion.V32, "SWARMED", "352710", 1); public static readonly Death V32Impaled = new(GameVersion.V32, "IMPALED", "433114", 2); public static readonly Death V32Gored = new(GameVersion.V32, "GORED", "6E5021", 3); public static readonly Death V32Infested = new(GameVersion.V32, "INFESTED", "DCCB00", 4); public static readonly Death V32Opened = new(GameVersion.V32, "OPENED", "976E2E", 5); public static readonly Death V32Purged = new(GameVersion.V32, "PURGED", "4E3000", 6); public static readonly Death V32Desecrated = new(GameVersion.V32, "DESECRATED", "804E00", 7); public static readonly Death V32Sacrificed = new(GameVersion.V32, "SACRIFICED", "AF6B00", 8); public static readonly Death V32Eviscerated = new(GameVersion.V32, "EVISCERATED", "837E75", 9); public static readonly Death V32Annihilated = new(GameVersion.V32, "ANNIHILATED", "478B41", 10); public static readonly Death V32Intoxicated = new(GameVersion.V32, "INTOXICATED", "99A100", 11); public static readonly Death V32Envenomated = new(GameVersion.V32, "ENVENOMATED", "657A00", 12); public static readonly Death V32Incarnated = new(GameVersion.V32, "INCARNATED", "FF0000", 13); public static readonly Death V32Discarnated = new(GameVersion.V32, "DISCARNATED", "FF3131", 14); public static readonly Death V32Entangled = new(GameVersion.V32, "ENTANGLED", "771D00", 15); public static readonly Death V32Haunted = new(GameVersion.V32, "HAUNTED", "C8A2C8", 16); public static readonly Enemy V32Squid1 = new(GameVersion.V32, "Squid I", "4E3000", 10, 1, 2, 0x0, V32Purged, 1, 1, 3); public static readonly Enemy V32Squid2 = new(GameVersion.V32, "Squid II", "804E00", 20, 2, 3, 0x1, V32Desecrated, 2, 1, 39); public static readonly Enemy V32Squid3 = new(GameVersion.V32, "Squid III", "AF6B00", 90, 3, 3, 0x6, V32Sacrificed, 3, 9, 244); public static readonly Enemy V32Centipede = new(GameVersion.V32, "Centipede", "837E75", 75, 25, 25, 0x2, V32Eviscerated, 25, 25, 114); public static readonly Enemy V32Gigapede = new(GameVersion.V32, "Gigapede", "478B41", 250, 50, 50, 0x5, V32Annihilated, 50, 50, 259); public static readonly Enemy V32Ghostpede = new(GameVersion.V32, "Ghostpede", "C8A2C8", 500, 10, 10, 0x9, V32Haunted, null, null, 442); public static readonly Enemy V32Leviathan = new(GameVersion.V32, "Leviathan", "FF0000", 1500, 6, 6, 0x4, V32Incarnated, 1500, 1500, 350); public static readonly Enemy V32Thorn = new(GameVersion.V32, "Thorn", "771D00", 120, 0, 0, 0x7, V32Entangled, 12, 12, 447); public static readonly Enemy V32Spider1 = new(GameVersion.V32, "Spider I", "097A00", 25, 1, 1, 0x3, V32Intoxicated, 3, 3, 39); public static readonly Enemy V32Spider2 = new(GameVersion.V32, "Spider II", "13FF00", 200, 1, 1, 0x8, V32Envenomated, 20, 20, 274); public static readonly Enemy V32TheOrb = new(GameVersion.V32, "The Orb", "FF3131", 2400, 0, 0, null, V32Discarnated, 2400, 2400, null, V32Leviathan); public static readonly Enemy V32Skull1 = new(GameVersion.V32, "Skull I", "352710", 1, 0, 0, null, V32Swarmed, 0.25f, 0.25f, null, V32Squid1, V32Squid2, V32Squid3); public static readonly Enemy V32Skull2 = new(GameVersion.V32, "Skull II", "433114", 5, 1, 1, null, V32Impaled, 1, 1, null, V32Squid1); public static readonly Enemy V32Skull3 = new(GameVersion.V32, "Skull III", "6E5021", 10, 1, 1, null, V32Gored, 1, 1, null, V32Squid2); public static readonly Enemy V32Skull4 = new(GameVersion.V32, "Skull IV", "976E2E", 100, 0, 0, null, V32Opened, 10, 10, null, V32Squid3); public static readonly Enemy V32TransmutedSkull1 = new(GameVersion.V32, "Transmuted Skull I", "4C110C", 10, 0, 0, null, V32Swarmed, 1, 1, null, V32Leviathan, V32TheOrb); public static readonly Enemy V32TransmutedSkull2 = new(GameVersion.V32, "Transmuted Skull II", "721A13", 20, 1, 1, null, V32Impaled, 2, 2, null, V32Leviathan, V32TheOrb); public static readonly Enemy V32TransmutedSkull3 = new(GameVersion.V32, "Transmuted Skull III", "982319", 100, 1, 1, null, V32Gored, 10, 10, null, V32Leviathan, V32TheOrb); public static readonly Enemy V32TransmutedSkull4 = new(GameVersion.V32, "Transmuted Skull IV", "BE2C20", 300, 0, 0, null, V32Opened, 30, 30, null, V32Leviathan, V32TheOrb); public static readonly Enemy V32SpiderEgg1 = new(GameVersion.V32, "Spider Egg I", "99A100", 3, 0, 0, null, V32Intoxicated, 1, 1, null, V32Spider1); public static readonly Enemy V32SpiderEgg2 = new(GameVersion.V32, "Spider Egg II", "657A00", 3, 0, 0, null, V32Envenomated, 1, 1, null, V32Spider2); public static readonly Enemy V32Spiderling = new(GameVersion.V32, "Spiderling", "DCCB00", 3, 0, 0, null, V32Infested, 1, 1, null, V32SpiderEgg1, V32SpiderEgg2); #endregion V3.2 private static readonly GameVersion[] _gameVersions = (GameVersion[])Enum.GetValues(typeof(GameVersion)); private static readonly IEnumerable<DevilDaggersEntity> _entities = typeof(GameInfo).GetFields().Where(f => f.FieldType.IsSubclassOf(typeof(DevilDaggersEntity))).Select(f => (DevilDaggersEntity)f.GetValue(null)!); private static readonly Dictionary<Enemy, string[]> _enemyInfo = new() { { V1Squid1, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 10 Skull Is and 1 Skull II every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V1Squid2, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 10 Skull Is and 1 Skull III every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V1Centipede, new[] { "Emerges approximately 3 seconds after its spawn, starts flying idly for a while, then starts chasing the player", "Regularly dives down and moves underground for a while" } }, { V1Gigapede, new[] { "Emerges approximately 3 seconds after its spawn, then starts flying around the arena", "Regularly dives down and moves underground for a while" } }, { V1Leviathan, new[] { "Activates 8.5333 seconds after its initial appearance", "Attracts and transmutes all skulls by beckoning every 20 seconds, starting 13.5333 seconds after its spawn (5 seconds after becoming active)", "Rotates counter-clockwise" } }, { V1Spider1, new[] { "Spawns at the edge of the arena and starts lifting its head, faces the player after 3 seconds", "Attracts and consumes gems when facing the player, ejecting them as Spider Egg I one at a time", "Hides its head when shot and left unharmed for 1 second", "Begins moving randomly in an unpredictable jittery fashion after initially raising its head" } }, { V1Skull1, new[] { "Slowly chases the player" } }, { V1Skull2, new[] { "Moves randomly" } }, { V1Skull3, new[] { "Chases the player fast" } }, { V1TransmutedSkull2, new[] { "Moves randomly" } }, { V1TransmutedSkull3, new[] { "Chases the player fast" } }, { V1TransmutedSkull4, new[] { "Chases the player fast" } }, { V1SpiderEgg1, new[] { "Hatches into 5 Spiderlings after 10 seconds" } }, { V1Spiderling, new[] { "Darts towards the player in bursts with random offsets" } }, { V2Squid1, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 10 Skull Is and 1 Skull II every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V2Squid2, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 10 Skull Is and 1 Skull III every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V2Squid3, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 15 Skull Is and 1 Skull IV every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V2Centipede, new[] { "Emerges approximately 3 seconds after its spawn, starts flying idly for a while, then starts chasing the player", "Regularly dives down and moves underground for a while" } }, { V2Gigapede, new[] { "Emerges approximately 3 seconds after its spawn, then starts chasing the player immediately" } }, { V2Leviathan, new[] { "Activates 8.5333 seconds after its initial appearance", "Attracts and transmutes all skulls by beckoning every 20 seconds, starting 13.5333 seconds after its spawn (5 seconds after becoming active)", "Rotates counter-clockwise" } }, { V2Spider1, new[] { "Spawns at the edge of the arena and starts lifting its head, faces the player after 3 seconds", "Attracts and consumes gems when facing the player, ejecting them as Spider Egg I one at a time", "Hides its head when shot and left unharmed for 1 second", "Begins moving randomly in an unpredictable jittery fashion after initially raising its head" } }, { V2Spider2, new[] { "Spawns at the edge of the arena and starts lifting its head, faces the player after 9 seconds", "Attracts and consumes gems when facing the player, ejecting them as Spider Egg II one at a time", "Hides its head when shot and left unharmed for 1 second", "Begins moving randomly in an unpredictable jittery fashion after initially raising its head (though barely noticeable due to its size)" } }, { V2Skull1, new[] { "Slowly chases the player" } }, { V2Skull2, new[] { "Moves randomly" } }, { V2Skull3, new[] { "Chases the player fast" } }, { V2Skull4, new[] { "Chases the player fast" } }, { V2TransmutedSkull1, new[] { "Slowly chases the player" } }, { V2TransmutedSkull2, new[] { "Moves randomly" } }, { V2TransmutedSkull3, new[] { "Chases the player fast" } }, { V2TransmutedSkull4, new[] { "Chases the player fast" } }, { V2SpiderEgg1, new[] { "Hatches into 5 Spiderlings after 10 seconds" } }, { V2SpiderEgg2, new[] { "Hatches into 5 Spiderlings after 10 seconds" } }, { V2Spiderling, new[] { "Darts towards the player in bursts with random offsets" } }, { V2Andras, new[] { "Unfinished enemy that was never added to the real game", "Only appears in V2, can only be spawned using an edited spawnset", "Has its own sounds", "Uses the model for Skull III, but is smaller in size", "Does nothing but attract and consume all homing daggers like Ghostpede ", "Only takes damage when shot from above, so the player will need to daggerjump", "The player doesn't die when touching it" } }, { V3Squid1, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 10 Skull Is and 1 Skull II every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V3Squid2, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 10 Skull Is and 1 Skull III every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V3Squid3, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 15 Skull Is and 1 Skull IV every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V3Centipede, new[] { "Emerges approximately 3 seconds after its spawn, starts flying idly for a while, then starts chasing the player", "Regularly dives down and moves underground for a while" } }, { V3Gigapede, new[] { "Emerges approximately 3 seconds after its spawn, then starts chasing the player immediately" } }, { V3Ghostpede, new[] { "Emerges approximately 3 seconds after its spawn, then starts flying in circles high above the arena", "Attracts and consumes all homing daggers, making them useless" } }, { V3Leviathan, new[] { "Activates 8.5333 seconds after its initial appearance", "Attracts and transmutes all skulls by beckoning every 20 seconds, starting 13.5333 seconds after its spawn (5 seconds after becoming active)", "Rotates counter-clockwise", "Drops The Orb 3.3167 seconds after dying" } }, { V3Thorn, new[] { "Emerges approximately 3 seconds after its spawn", "Takes up space" } }, { V3Spider1, new[] { "Spawns at the edge of the arena and starts lifting its head, faces the player after 3 seconds", "Attracts and consumes gems when facing the player, ejecting them as Spider Egg I one at a time", "Hides its head when shot and left unharmed for 1 second", "Begins moving randomly in an unpredictable jittery fashion after initially raising its head" } }, { V3Spider2, new[] { "Spawns at the edge of the arena and starts lifting its head, faces the player after 9 seconds", "Attracts and consumes gems when facing the player, ejecting them as Spider Egg II one at a time", "Hides its head when shot and left unharmed for 1 second", "Begins moving randomly in an unpredictable jittery fashion after initially raising its head (though barely noticeable due to its size)" } }, { V3Skull1, new[] { "Slowly chases the player" } }, { V3Skull2, new[] { "Moves randomly" } }, { V3Skull3, new[] { "Chases the player fast" } }, { V3Skull4, new[] { "Chases the player fast" } }, { V3TransmutedSkull1, new[] { "Slowly chases the player" } }, { V3TransmutedSkull2, new[] { "Moves randomly" } }, { V3TransmutedSkull3, new[] { "Chases the player fast" } }, { V3TransmutedSkull4, new[] { "Chases the player fast" } }, { V3SpiderEgg1, new[] { "Hatches into 5 Spiderlings after 10 seconds" } }, { V3SpiderEgg2, new[] { "Hatches into 5 Spiderlings after 10 seconds" } }, { V3Spiderling, new[] { "Darts towards the player in bursts with random offsets" } }, { V3TheOrb, new[] { "Activates 10 seconds after Leviathan's death", "Behaves like an eyeball, will look at the player, then attract and transmute all skulls by beckoning every 2.5333 seconds", "Becomes stunned under constant fire, cannot look or attract skulls while stunned" } }, { V31Squid1, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 10 Skull Is and 1 Skull II every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V31Squid2, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 10 Skull Is and 1 Skull III every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V31Squid3, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 15 Skull Is and 1 Skull IV every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V31Centipede, new[] { "Emerges approximately 3 seconds after its spawn, starts flying idly for a while, then starts chasing the player", "Burrows after 15 seconds of being emerged, or if the player gets too close to its head" } }, { V31Gigapede, new[] { "Emerges approximately 3 seconds after its spawn, then starts chasing the player immediately" } }, { V31Ghostpede, new[] { "Emerges approximately 3 seconds after its spawn, then starts flying in circles high above the arena", "Attracts and consumes all homing daggers, making them useless" } }, { V31Leviathan, new[] { "Activates 8.5333 seconds after its initial appearance", "Attracts and transmutes all skulls by beckoning every 20 seconds, starting 13.5333 seconds after its spawn (5 seconds after becoming active)", "Rotates counter-clockwise", "Drops The Orb 3.3167 seconds after dying" } }, { V31Thorn, new[] { "Emerges approximately 3 seconds after its spawn", "Takes up space" } }, { V31Spider1, new[] { "Spawns at the edge of the arena and starts lifting its head, faces the player after 3 seconds", "Attracts and consumes gems when facing the player, ejecting them as Spider Egg I one at a time", "Hides its head when shot and left unharmed for 1 second", "Begins moving randomly in an unpredictable jittery fashion after initially raising its head" } }, { V31Spider2, new[] { "Spawns at the edge of the arena and starts lifting its head, faces the player after 9 seconds", "Attracts and consumes gems when facing the player, ejecting them as Spider Egg II one at a time", "Hides its head when shot and left unharmed for 1 second", "Begins moving randomly in an unpredictable jittery fashion after initially raising its head (though barely noticeable due to its size)" } }, { V31Skull1, new[] { "Slowly chases the player" } }, { V31Skull2, new[] { "Moves randomly" } }, { V31Skull3, new[] { "Chases the player fast" } }, { V31Skull4, new[] { "Chases the player fast" } }, { V31TransmutedSkull1, new[] { "Slowly chases the player" } }, { V31TransmutedSkull2, new[] { "Moves randomly" } }, { V31TransmutedSkull3, new[] { "Chases the player fast" } }, { V31TransmutedSkull4, new[] { "Chases the player fast" } }, { V31SpiderEgg1, new[] { "Hatches into 5 Spiderlings after 10 seconds" } }, { V31SpiderEgg2, new[] { "Hatches into 5 Spiderlings after 10 seconds" } }, { V31Spiderling, new[] { "Darts towards the player in bursts with random offsets" } }, { V31TheOrb, new[] { "Activates 10 seconds after Leviathan's death", "Behaves like an eyeball, will look at the player, then attract and transmute all skulls by beckoning every 2.5333 seconds", "Becomes stunned under constant fire, cannot look or attract skulls while stunned" } }, { V32Squid1, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 10 Skull Is and 1 Skull II every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V32Squid2, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 10 Skull Is and 1 Skull III every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V32Squid3, new[] { "Spawns at the edge of the arena", "Moves slowly and rotates clockwise", "Spawns 15 Skull Is and 1 Skull IV every 20 seconds (starting 3 seconds after its initial appearance)" } }, { V32Centipede, new[] { "Emerges approximately 3 seconds after its spawn, starts flying idly for a while, then starts chasing the player", "Burrows after 15 seconds of being emerged, or if the player gets too close to its head" } }, { V32Gigapede, new[] { "Emerges approximately 3 seconds after its spawn, then starts chasing the player immediately" } }, { V32Ghostpede, new[] { "Emerges approximately 3 seconds after its spawn, then starts flying in circles high above the arena", "Attracts and consumes all homing daggers, making them useless" } }, { V32Leviathan, new[] { "Activates 8.5333 seconds after its initial appearance", "Attracts and transmutes all skulls by beckoning every 20 seconds, starting 13.5333 seconds after its spawn (5 seconds after becoming active)", "Rotates counter-clockwise", "Drops The Orb 3.3167 seconds after dying" } }, { V32Thorn, new[] { "Emerges approximately 3 seconds after its spawn", "Takes up space" } }, { V32Spider1, new[] { "Spawns at the edge of the arena and starts lifting its head, faces the player after 3 seconds", "Attracts and consumes gems when facing the player, ejecting them as Spider Egg I one at a time", "Hides its head when shot and left unharmed for 1 second", "Begins moving randomly in an unpredictable jittery fashion after initially raising its head" } }, { V32Spider2, new[] { "Spawns at the edge of the arena and starts lifting its head, faces the player after 9 seconds", "Attracts and consumes gems when facing the player, ejecting them as Spider Egg II one at a time", "Hides its head when shot and left unharmed for 1 second", "Begins moving randomly in an unpredictable jittery fashion after initially raising its head (though barely noticeable due to its size)" } }, { V32Skull1, new[] { "Slowly chases the player" } }, { V32Skull2, new[] { "Moves randomly" } }, { V32Skull3, new[] { "Chases the player fast" } }, { V32Skull4, new[] { "Chases the player fast" } }, { V32TransmutedSkull1, new[] { "Slowly chases the player" } }, { V32TransmutedSkull2, new[] { "Moves randomly" } }, { V32TransmutedSkull3, new[] { "Chases the player fast" } }, { V32TransmutedSkull4, new[] { "Chases the player fast" } }, { V32SpiderEgg1, new[] { "Hatches into 5 Spiderlings after 10 seconds" } }, { V32SpiderEgg2, new[] { "Hatches into 5 Spiderlings after 10 seconds" } }, { V32Spiderling, new[] { "Darts towards the player in bursts with random offsets" } }, { V32TheOrb, new[] { "Activates 10 seconds after Leviathan's death", "Behaves like an eyeball, will look at the player, then attract and transmute all skulls by beckoning every 2.5333 seconds", "Becomes stunned under constant fire, cannot look or attract skulls while stunned" } }, }; private static readonly List<Dagger> _v1Daggers = _entities.OfType<Dagger>().Where(e => e.GameVersion == GameVersion.V1).ToList(); private static readonly List<Death> _v1Deaths = _entities.OfType<Death>().Where(e => e.GameVersion == GameVersion.V1).ToList(); private static readonly List<Enemy> _v1Enemies = _entities.OfType<Enemy>().Where(e => e.GameVersion == GameVersion.V1).ToList(); private static readonly List<Upgrade> _v1Upgrades = _entities.OfType<Upgrade>().Where(e => e.GameVersion == GameVersion.V1).ToList(); private static readonly List<Dagger> _v2Daggers = _entities.OfType<Dagger>().Where(e => e.GameVersion == GameVersion.V2).ToList(); private static readonly List<Death> _v2Deaths = _entities.OfType<Death>().Where(e => e.GameVersion == GameVersion.V2).ToList(); private static readonly List<Enemy> _v2Enemies = _entities.OfType<Enemy>().Where(e => e.GameVersion == GameVersion.V2).ToList(); private static readonly List<Upgrade> _v2Upgrades = _entities.OfType<Upgrade>().Where(e => e.GameVersion == GameVersion.V2).ToList(); private static readonly List<Dagger> _v3Daggers = _entities.OfType<Dagger>().Where(e => e.GameVersion == GameVersion.V3).ToList(); private static readonly List<Death> _v3Deaths = _entities.OfType<Death>().Where(e => e.GameVersion == GameVersion.V3).ToList(); private static readonly List<Enemy> _v3Enemies = _entities.OfType<Enemy>().Where(e => e.GameVersion == GameVersion.V3).ToList(); private static readonly List<Upgrade> _v3Upgrades = _entities.OfType<Upgrade>().Where(e => e.GameVersion == GameVersion.V3).ToList(); private static readonly List<Dagger> _v31Daggers = _entities.OfType<Dagger>().Where(e => e.GameVersion == GameVersion.V31).ToList(); private static readonly List<Death> _v31Deaths = _entities.OfType<Death>().Where(e => e.GameVersion == GameVersion.V31).ToList(); private static readonly List<Enemy> _v31Enemies = _entities.OfType<Enemy>().Where(e => e.GameVersion == GameVersion.V31).ToList(); private static readonly List<Upgrade> _v31Upgrades = _entities.OfType<Upgrade>().Where(e => e.GameVersion == GameVersion.V31).ToList(); private static readonly List<Dagger> _v32Daggers = _entities.OfType<Dagger>().Where(e => e.GameVersion == GameVersion.V32).ToList(); private static readonly List<Death> _v32Deaths = _entities.OfType<Death>().Where(e => e.GameVersion == GameVersion.V32).ToList(); private static readonly List<Enemy> _v32Enemies = _entities.OfType<Enemy>().Where(e => e.GameVersion == GameVersion.V32).ToList(); private static readonly List<Upgrade> _v32Upgrades = _entities.OfType<Upgrade>().Where(e => e.GameVersion == GameVersion.V32).ToList(); public static GameVersion? GetGameVersionFromDate(DateTime dateTime) { for (int i = 0; i < _gameVersions.Length; i++) { if (dateTime >= GetReleaseDate(_gameVersions[i]) && (i == _gameVersions.Length - 1 || dateTime < GetReleaseDate(_gameVersions[i + 1]))) return _gameVersions[i]; } return null; } public static DateTime? GetReleaseDate(GameVersion gameVersion) => gameVersion switch { GameVersion.V1 => new(2016, 2, 18), GameVersion.V2 => new(2016, 7, 5), GameVersion.V3 => new(2016, 9, 19), GameVersion.V31 => new(2021, 2, 19), GameVersion.V32 => new(2021, 10, 27), _ => null, }; public static string[] GetEnemyInfo(Enemy enemy) { foreach (KeyValuePair<Enemy, string[]> kvp in _enemyInfo) { if (kvp.Key == enemy) return kvp.Value; } throw new($"Could not find enemy info for {nameof(Enemy)} with name '{enemy.Name}' and version '{enemy.GameVersion}'."); } public static List<Dagger> GetDaggers(GameVersion gameVersion) => gameVersion switch { GameVersion.V1 => _v1Daggers, GameVersion.V2 => _v2Daggers, GameVersion.V3 => _v3Daggers, GameVersion.V31 => _v31Daggers, _ => _v32Daggers, }; public static List<Death> GetDeaths(GameVersion gameVersion) => gameVersion switch { GameVersion.V1 => _v1Deaths, GameVersion.V2 => _v2Deaths, GameVersion.V3 => _v3Deaths, GameVersion.V31 => _v31Deaths, _ => _v32Deaths, }; public static List<Enemy> GetEnemies(GameVersion gameVersion) => gameVersion switch { GameVersion.V1 => _v1Enemies, GameVersion.V2 => _v2Enemies, GameVersion.V3 => _v3Enemies, GameVersion.V31 => _v31Enemies, _ => _v32Enemies, }; public static List<Upgrade> GetUpgrades(GameVersion gameVersion) => gameVersion switch { GameVersion.V1 => _v1Upgrades, GameVersion.V2 => _v2Upgrades, GameVersion.V3 => _v3Upgrades, GameVersion.V31 => _v31Upgrades, _ => _v32Upgrades, }; public static Enemy? GetEnemyBySpawnsetType(GameVersion gameVersion, int spawnsetType) => GetEnemies(gameVersion).Find(e => e.SpawnsetType == spawnsetType); public static Death? GetDeathByType(GameVersion gameVersion, int deathType) => GetDeaths(gameVersion).Find(e => e.DeathType == deathType); public static Death? GetDeathByName(GameVersion gameVersion, string deathName) => GetDeaths(gameVersion).Find(e => string.Equals(e.Name, deathName, StringComparison.InvariantCultureIgnoreCase)); public static Dagger GetDaggerFromTenthsOfMilliseconds(GameVersion gameVersion, int timeInTenthsOfMilliseconds) => GetDaggerFromSeconds(gameVersion, timeInTenthsOfMilliseconds / 10000.0); public static Dagger GetDaggerFromSeconds(GameVersion gameVersion, double timeInSeconds) { List<Dagger> daggers = GetDaggers(gameVersion); for (int i = daggers.Count - 1; i >= 0; i--) { if (timeInSeconds >= (daggers[i].UnlockSecond ?? 0)) return daggers[i]; } throw new ArgumentOutOfRangeException(nameof(timeInSeconds), $"Could not determine dagger based on time '{timeInSeconds:0.0000}'."); } public static IEnumerable<GameVersion> GetAppearances(string entityName) => _entities.Where(e => e.Name == entityName && !(e.GameVersion is GameVersion.V31 or GameVersion.V32)).Select(e => e.GameVersion); } }
92.432432
429
0.721408
[ "Unlicense" ]
NoahStolk/DevilDaggersCore
DevilDaggersCore/Game/GameInfo.cs
47,880
C#
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Globalization; using Xenko.Core.Assets.Editor.ViewModel; using Xenko.Core.Presentation.ValueConverters; using Xenko.Editor.Build; namespace Xenko.Assets.Presentation.ValueConverters { /// <summary> /// This value converter will convert any numeric value to integer. <see cref="ConvertBack"/> is supported and /// will convert the value to the target if it is numeric, otherwise it returns the value as-is. /// </summary> public class TimeToFrames : ValueConverterBase<TimeToFrames> { /// <inheritdoc/> public override object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return null; var gameSettings = SessionViewModel.Instance?.ServiceProvider.Get<GameSettingsProviderService>().CurrentGameSettings; var frameRate = (double) (gameSettings?.GetOrCreate<EditorSettings>().AnimationFrameRate ?? 30); frameRate = Math.Max(frameRate, 1.0); var timeSpan = (TimeSpan)value; return System.Convert.ChangeType(timeSpan.TotalSeconds * frameRate + 0.1, typeof(long)); } /// <inheritdoc/> public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var gameSettings = SessionViewModel.Instance?.ServiceProvider.Get<GameSettingsProviderService>().CurrentGameSettings; var frameRate = (double)(gameSettings?.GetOrCreate<EditorSettings>().AnimationFrameRate ?? 30); frameRate = Math.Max(frameRate, 1.0); var scalar = (double)(value ?? default(double)); return TimeSpan.FromSeconds(scalar / frameRate); } } }
43.217391
129
0.685614
[ "MIT" ]
Aminator/xenko
sources/editor/Xenko.Assets.Presentation/ValueConverters/TimeToFrames.cs
1,988
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SetManaValue : MonoBehaviour { public GameObject whiskas; public GameObject maxWhiskas; private Image[] whiskas_array; private Image[] disactiveWhiskas_array; private Slider manaSlider; private Text manaText; private void OnEnable() { TurnManager.setDisplay += ChangeValue; } private void OnDisable() { TurnManager.setDisplay -= ChangeValue; } private void ChangeValue(int currentAmount, int maxMana) { if (whiskas_array == null) //As it's called from the awake method this avoids Init(); for (int i = 0; i < currentAmount; i++) { whiskas_array[i].gameObject.SetActive(true); } for (int i = currentAmount; i < whiskas_array.Length; i++) { whiskas_array[i].gameObject.SetActive(false); } for (int i = 0; i < maxMana; i++) { disactiveWhiskas_array[i].gameObject.SetActive(true); } //manaSlider.value = amount; manaText.text = currentAmount.ToString(); } private void Init() { //manaSlider = GetComponent<Slider>(); manaText = GetComponentInChildren<Text>(); whiskas_array = whiskas.GetComponentsInChildren<Image>(); disactiveWhiskas_array = maxWhiskas.GetComponentsInChildren<Image>(); for (int i = 0; i < disactiveWhiskas_array.Length; i++) { disactiveWhiskas_array[i].gameObject.SetActive(false); } } }
27.542373
86
0.621538
[ "MIT" ]
MarcM-collab/Project2_Fix
Assets/Scripts/UI/SetManaValue.cs
1,625
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.AzureNextGen.DigitalTwins.V20201201.Outputs { [OutputType] public sealed class ConnectionPropertiesResponsePrivateLinkServiceConnectionState { /// <summary> /// Actions required for a private endpoint connection. /// </summary> public readonly string? ActionsRequired; /// <summary> /// The description for the current state of a private endpoint connection. /// </summary> public readonly string Description; /// <summary> /// The status of a private endpoint connection. /// </summary> public readonly string Status; [OutputConstructor] private ConnectionPropertiesResponsePrivateLinkServiceConnectionState( string? actionsRequired, string description, string status) { ActionsRequired = actionsRequired; Description = description; Status = status; } } }
30.069767
85
0.651199
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/DigitalTwins/V20201201/Outputs/ConnectionPropertiesResponsePrivateLinkServiceConnectionState.cs
1,293
C#
using System; using System.Collections.Generic; using System.Linq; using PasPasPas.Globals; using PasPasPas.Globals.Runtime; using PasPasPas.Globals.Types; namespace PasPasPas.Typings.Structured { /// <summary> /// callable routine /// </summary> public class RoutineGroup : IRoutineGroup, IEquatable<IRoutineGroup> { /// <summary> /// create a new routine /// </summary> public RoutineGroup(ITypeDefinition definingType, string name, ITypeDefinition? genericType = default) { Name = name; DefiningType = definingType; } /// <summary> /// routine parameters /// </summary> public List<IRoutine> Items { get; } = new List<IRoutine>(); /// <summary> /// routine name /// </summary> public string Name { get; } /// <summary> /// defining type /// </summary> public ITypeDefinition DefiningType { get; } /// <summary> /// no intrinsic routine /// </summary> public IntrinsicRoutineId RoutineId => IntrinsicRoutineId.Unknown; /// <summary> /// type definition /// </summary> public ITypeDefinition TypeDefinition => DefiningType.DefiningUnit.TypeRegistry.SystemUnit.RoutineGroupType; /// <summary> /// symbol type kind /// </summary> public SymbolTypeKind SymbolKind => SymbolTypeKind.RoutineGroup; /// <summary> /// check for equality /// </summary> /// <param name="other"></param> /// <returns></returns> public bool Equals(ITypeSymbol? other) => Equals(other as IRoutineGroup); /// <summary> /// check for equality /// </summary> /// <param name="other"></param> /// <returns></returns> public bool Equals(IRoutineGroup? other) => RoutineId.Equals(other?.RoutineId) && DefiningType.Equals(other?.DefiningType) && Items.SequenceEqual(other?.Items); /// <summary> /// find a matching parameter group /// </summary> /// <param name="callableRoutines">list of callable routines</param> /// <param name="signature">used signature</param> public void ResolveCall(IList<IRoutineResult> callableRoutines, ISignature signature) { foreach (var paramGroup in Items) { if (!paramGroup.Matches(default, signature)) continue; callableRoutines.Add(DefiningType.DefiningUnit.TypeRegistry.Runtime.Types.MakeInvocationResult(paramGroup)); } } } }
30.391304
124
0.558655
[ "Apache-2.0" ]
prjm/paspaspas
PasPasPas.Typings/src/Structured/RoutineGroup.cs
2,798
C#
using System; using Android.App; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace DotMatrixClock.Droid { [Activity(Label = "DotMatrixClock", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } } }
27.68
191
0.697977
[ "Apache-2.0" ]
1ostrich/xamarin-forms-samples
BoxView/DotMatrixClock/DotMatrixClock/DotMatrixClock.Android/MainActivity.cs
694
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using TemplateValidator; using Xunit; namespace Microsoft.Templates.Test { [Trait("Type", "TemplateValidation")] [Trait("ExecutionSet", "Minimum")] [Trait("ExecutionSet", "TemplateValidation")] public class TemplateJsonValidationTests { public static IEnumerable<object[]> GetAllTemplateJsonFiles() { // This is the relative path from where the test assembly will run from const string templatesRoot = "../../../../../Templates"; // The following excludes the catalog and project folders, but they only contain a single template file each var foldersOfInterest = new[] { "_composition", "Features", "Pages" }; foreach (var folder in foldersOfInterest) { foreach (var file in new DirectoryInfo(Path.Combine(templatesRoot, folder)).GetFiles("template.json", SearchOption.AllDirectories)) { yield return new object[] { file.FullName }; } } } private static IEnumerable<string> GetFiles(string directory) { foreach (var dir in Directory.GetDirectories(directory)) { foreach (var file in Directory.GetFiles(dir)) { yield return file; } foreach (var file in GetFiles(dir)) { yield return file; } } } [Theory] [MemberData("GetAllTemplateJsonFiles")] public async Task VerifyAllTemplateFilesAsync(string filePath) { var result = await TemplateJsonVerifier.VerifyTemplatePathAsync(filePath); Assert.True(result.Success, $"{filePath}: " + string.Join(Environment.NewLine, result.Messages)); } } }
34.741935
147
0.603064
[ "MIT" ]
hihain/WindowsTemplateStudio
code/test/Templates.Test/TemplateJsonValidationTests.cs
2,156
C#
using Tralus.Framework.Migration; namespace Mahan.Stations.Migration.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; public sealed class Configuration : TralusDbMigrationConfiguration<Data.StationsDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(Mahan.Stations.Data.StationsDbContext context) { base.Seed(context); context.Database.ExecuteSqlCommand(String.Format(SqlResource.DropViewIfExists, "Stations.FlightReportView")); context.Database.ExecuteSqlCommand(SqlResource.FlightReportView); // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } } }
33
121
0.599845
[ "Apache-2.0" ]
mehrandvd/Tralus
Samples/Stations/Source/Mahan.Tralus.Stations.Migration/Migrations/Configuration.cs
1,287
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("This PC")] [assembly: AssemblyDescription("Windows Explorer 'This PC' folder display editor")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Idiot&Robot")] [assembly: AssemblyProduct("This PC")] [assembly: AssemblyCopyright("Copyright © 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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
40.696429
96
0.755156
[ "MIT" ]
idiotandrobot/thispc
source/This PC/Properties/AssemblyInfo.cs
2,282
C#
using Basket.API.Entities; using Microsoft.Extensions.Caching.Distributed; using Newtonsoft.Json; using System; using System.Threading.Tasks; namespace Basket.API.Repositories { public class BasketRepository : IBasketRepository { private readonly IDistributedCache _redisCache; public BasketRepository(IDistributedCache redisCache) { _redisCache = redisCache ?? throw new ArgumentException(nameof(redisCache)); } public async Task DeleteBasket(string username) { await _redisCache.RemoveAsync(username); } public async Task<ShoppingCart> GetBasket(string username) { var basket = await _redisCache.GetStringAsync(username); if (string.IsNullOrEmpty(basket)) return null; return JsonConvert.DeserializeObject<ShoppingCart>(basket); } public async Task<ShoppingCart> UpdateBasket(ShoppingCart basket) { await _redisCache.SetStringAsync(basket.UserName,JsonConvert.SerializeObject(basket)); return await GetBasket(basket.UserName); } } }
28.292683
98
0.668966
[ "MIT" ]
MuriloSGomes/MicroServiceTreino
src/Services/Basket/Basket.API/Repositories/BasketRepository.cs
1,162
C#
using Windows.UI.Xaml.Controls; // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236 namespace SimpleViewer.Universal.Views { public sealed partial class ShellView : UserControl { public ShellView() { InitializeComponent(); } } }
21.6
96
0.66358
[ "BSD-3-Clause" ]
007souvikdas/fo-dicom-samples
Universal/SimpleViewer.Universal/Views/ShellView.xaml.cs
326
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Pchp.Core.Reflection; using Pchp.Core.Resources; namespace Pchp.Core { [DebuggerNonUserCode, DebuggerStepThrough] public static class Operators { #region Numeric /// <summary> /// Bit mask corresponding to the sign in <see cref="long"/> value. /// </summary> internal const long LONG_SIGN_MASK = (1L << (8 * sizeof(long) - 1)); /// <summary> /// Performs bitwise and operation. /// </summary> internal static PhpValue BitAnd(in PhpValue x, in PhpValue y) { var bx = x.ToBytesOrNull(); if (bx != null) { var by = y.ToBytesOrNull(); if (by != null) { return PhpValue.Create(BitAnd(bx, by)); } } // return PhpValue.Create(x.ToLong() & y.ToLong()); } /// <summary> /// Performs bitwise or operation. /// </summary> internal static PhpValue BitOr(in PhpValue x, in PhpValue y) { var bx = x.ToBytesOrNull(); if (bx != null) { var by = y.ToBytesOrNull(); if (by != null) { return PhpValue.Create(BitOr(bx, by)); } } // return PhpValue.Create(x.ToLong() | y.ToLong()); } /// <summary> /// Performs exclusive or operation. /// </summary> internal static PhpValue BitXor(in PhpValue x, in PhpValue y) { var bx = x.ToBytesOrNull(); if (bx != null) { var by = y.ToBytesOrNull(); if (by != null) { return PhpValue.Create(BitXor(bx, by)); } } // return PhpValue.Create(x.ToLong() ^ y.ToLong()); } static byte[] BitAnd(byte[] bx, byte[] by) { int length = Math.Min(bx.Length, by.Length); if (length == 0) { return Array.Empty<byte>(); } byte[] result = new byte[length]; for (int i = 0; i < result.Length; i++) { result[i] = (byte)(bx[i] & by[i]); } return result; } static byte[] BitOr(byte[] bx, byte[] by) { if (bx.Length == 0 && by.Length == 0) { return Array.Empty<byte>(); } byte[] result, or; if (bx.Length > by.Length) { result = (byte[])bx.Clone(); or = by; } else { result = (byte[])by.Clone(); or = bx; } for (int i = 0; i < or.Length; i++) { result[i] |= or[i]; } return result; } static byte[] BitXor(byte[] bx, byte[] by) { int length = Math.Min(bx.Length, by.Length); byte[] result = new byte[length]; return BitXor(result, bx, by); } /// <summary> /// Performs specified binary operation on arrays of bytes. /// </summary> /// <param name="result">An array where to store the result. Data previously stored here will be overwritten.</param> /// <param name="x">The first operand.</param> /// <param name="y">The second operand</param> /// <returns>The reference to the the <paramref name="result"/> array.</returns> static byte[] BitXor(byte[]/*!*/ result, byte[]/*!*/ x, byte[]/*!*/ y) { Debug.Assert(result != null && x != null && y != null && result.Length <= x.Length && result.Length <= y.Length); for (int i = 0; i < result.Length; i++) { result[i] = unchecked((byte)(x[i] ^ y[i])); } // remaining bytes are ignored // return result; } /// <summary> /// Performs bitwise negation. /// </summary> internal static PhpValue BitNot(in PhpValue x) { switch (x.TypeCode) { case PhpTypeCode.Long: return PhpValue.Create(~x.Long); case PhpTypeCode.Alias: return ~x.Alias.Value; case PhpTypeCode.String: case PhpTypeCode.MutableString: throw new NotImplementedException(); // bitwise negation of each character in string case PhpTypeCode.Object: if (x.Object == null) { return PhpValue.Null; } goto default; default: // TODO: Err UnsupportedOperandTypes return PhpValue.Null; } } /// <summary> /// Performs division according to PHP semantics. /// </summary> /// <remarks>The division operator ("/") returns a float value unless the two operands are integers /// (or strings that get converted to integers) and the numbers are evenly divisible, /// in which case an integer value will be returned.</remarks> internal static PhpNumber Div(in PhpValue x, in PhpValue y) { var info = x.ToNumber(out var nx) | y.ToNumber(out var ny); if ((info & Convert.NumberInfo.IsPhpArray) != 0) { throw PhpException.ErrorException(ErrResources.unsupported_operand_types); } // TODO: // division by zero: //if (y == 0) //{ // PhpException.Throw(PhpError.Warning, CoreResources.GetString("division_by_zero")); // return false; //} return nx / ny; } #endregion #region Assignment /// <summary> /// Assigns a PHP value by value according to the PHP semantics. /// </summary> /// <param name="target">Target of the assignment.</param> /// <param name="value">Value to be assigned.</param> public static void SetValue(ref PhpValue target, PhpValue value) { Debug.Assert(!value.IsAlias); if (target.Object is PhpAlias alias) { alias.Value = value; } else { target = value; } } /// <summary> /// Assigns a PHP value to an aliased place. /// </summary> /// <param name="target">Target of the assignment.</param> /// <param name="value">Value to be assigned.</param> public static void SetValue(PhpAlias/*!*/target, PhpValue value) { Debug.Assert(target != null); Debug.Assert(!value.IsAlias); target.Value = value; } #endregion #region Ensure /// <summary> /// Ensures given variable is not <c>null</c>. /// </summary> public static object EnsureObject(ref object obj) => obj ?? (obj = new stdClass()); /// <summary> /// Ensures given variable is not <c>null</c>. /// </summary> public static PhpArray EnsureArray(ref PhpArray arr) => arr ?? (arr = new PhpArray()); /// <summary> /// Ensures given variable is not <c>null</c>. /// </summary> public static IPhpArray EnsureArray(ref IPhpArray arr) => arr ?? (arr = new PhpArray()); /// <summary> /// Ensures the value is <see cref="PhpString"/> and gets mutable access to the value (non-shared). /// </summary> /// <returns>Object on which edit operations can be performed. Cannot be <c>null</c>.</returns> public static PhpString.Blob EnsureWritableString(ref PhpValue value) { PhpString.Blob blob; switch (value.TypeCode) { case PhpTypeCode.MutableString: if ((blob = value.MutableStringBlob).IsShared) { value = new PhpValue(blob = value.MutableStringBlob.ReleaseOne()); } break; case PhpTypeCode.Null: blob = new PhpString.Blob(); value = new PhpValue(blob); break; case PhpTypeCode.String: blob = new PhpString.Blob(value.String); value = new PhpValue(blob); break; case PhpTypeCode.Alias: blob = value.Alias.EnsureWritableString(); break; default: blob = new PhpString.Blob(value.ToStringUtf8()); value = new PhpValue(blob); break; } return blob; } #endregion #region IsSet, IsEmpty /// <summary> /// Implementation of PHP <c>isset</c> operator. /// </summary> /// <remarks>Value (eventualy dereferenced value) is not <c>NULL</c>.</remarks> public static bool IsSet(PhpValue value) => !value.IsNull; /// <summary> /// Implements <c>empty</c> operator. /// </summary> public static bool IsEmpty(PhpValue value) => value.IsEmpty; /// <summary> /// Implements <c>empty</c> operator on objects. /// </summary> public static bool IsEmpty(object value) => ReferenceEquals(value, null); #endregion #region Array Access /// <summary> /// Provides <see cref="IPhpArray"/> interface for <see cref="ArrayAccess"/> instance. /// </summary> sealed class ArrayAccessAsPhpArray : IPhpArray { readonly ArrayAccess _array; public ArrayAccessAsPhpArray(ArrayAccess array) { Debug.Assert(array != null); _array = array; } public int Count { get { throw new NotSupportedException(); } } public void AddValue(PhpValue value) => SetItemValue(PhpValue.Null, value); public PhpAlias EnsureItemAlias(IntStringKey key) { var item = _array.offsetGet(key); return PhpValue.EnsureAlias(ref item); } public IPhpArray EnsureItemArray(IntStringKey key) { var item = _array.offsetGet(key); return PhpValue.EnsureArray(ref item); } public object EnsureItemObject(IntStringKey key) { var item = _array.offsetGet(key); return PhpValue.EnsureObject(ref item); } public PhpValue GetItemValue(IntStringKey key) => _array.offsetGet(PhpValue.Create(key)); public PhpValue GetItemValue(PhpValue index) => _array.offsetGet(index); public void RemoveKey(IntStringKey key) => _array.offsetUnset(PhpValue.Create(key)); public void RemoveKey(PhpValue index) => _array.offsetUnset(index); public void SetItemAlias(IntStringKey key, PhpAlias alias) => _array.offsetSet(PhpValue.Create(key), PhpValue.Create(alias)); public void SetItemAlias(PhpValue index, PhpAlias alias) => _array.offsetSet(index, PhpValue.Create(alias)); public void SetItemValue(IntStringKey key, PhpValue value) => _array.offsetSet(PhpValue.Create(key), value); public void SetItemValue(PhpValue index, PhpValue value) => _array.offsetSet(index, value); } sealed class ListAsPhpArray : IPhpArray { readonly IList _array; public ListAsPhpArray(IList array) { Debug.Assert(array != null); _array = array; } object ToObject(PhpValue value) => value.ToClr(); // TODO, type conversion public int Count => _array.Count; public void AddValue(PhpValue value) { _array.Add(ToObject(value)); } public PhpAlias EnsureItemAlias(IntStringKey key) { var item = GetItemValue(key); return PhpValue.EnsureAlias(ref item); } public IPhpArray EnsureItemArray(IntStringKey key) { var item = GetItemValue(key); return PhpValue.EnsureArray(ref item); } public object EnsureItemObject(IntStringKey key) { var item = GetItemValue(key); return PhpValue.EnsureObject(ref item); } public PhpValue GetItemValue(IntStringKey key) { if (key.IsInteger && Utilities.NumberUtils.IsInt32(key.Integer)) { return PhpValue.FromClr(_array[unchecked((int)key.Integer)]); } else { throw new ArgumentException(nameof(key)); } } public PhpValue GetItemValue(PhpValue index) => GetItemValue(index.ToIntStringKey()); public void RemoveKey(IntStringKey key) { if (key.IsInteger && Utilities.NumberUtils.IsInt32(key.Integer)) { _array.RemoveAt(unchecked((int)key.Integer)); } else { throw new ArgumentException(nameof(key)); } } public void RemoveKey(PhpValue index) => RemoveKey(index.ToIntStringKey()); public void SetItemAlias(IntStringKey key, PhpAlias alias) { if (key.IsInteger && Utilities.NumberUtils.IsInt32(key.Integer)) { _array[unchecked((int)key.Integer)] = ToObject(alias.Value); } else { throw new ArgumentException(nameof(key)); } } public void SetItemAlias(PhpValue index, PhpAlias alias) => SetItemAlias(index.ToIntStringKey(), alias); public void SetItemValue(IntStringKey key, PhpValue value) { if (key.IsInteger && Utilities.NumberUtils.IsInt32(key.Integer)) { _array[unchecked((int)key.Integer)] = ToObject(value); } else { throw new ArgumentException(nameof(key)); } } public void SetItemValue(PhpValue index, PhpValue value) => SetItemValue(index.ToIntStringKey(), value); } /// <summary> /// Helper class representing array access for classes with CLR "get_Item" / "set_Item" indexer method. /// </summary> sealed class GetSetItemAsPhpArray : IPhpArray { readonly object/*!*/_instance; public GetSetItemAsPhpArray(object/*!*/instance) { _instance = instance ?? throw new ArgumentNullException(nameof(instance)); } public int Count => throw new NotSupportedException(); public void AddValue(PhpValue value) => throw new NotSupportedException(); public PhpAlias EnsureItemAlias(IntStringKey key) { var item = GetItemValue(key); return PhpValue.EnsureAlias(ref item); } public IPhpArray EnsureItemArray(IntStringKey key) { var item = GetItemValue(key); return PhpValue.EnsureArray(ref item); } public object EnsureItemObject(IntStringKey key) { var item = GetItemValue(key); return PhpValue.EnsureObject(ref item); } public PhpValue GetItemValue(IntStringKey key) => GetItemValue((PhpValue)key); public PhpValue GetItemValue(PhpValue index) { var getter = _instance.GetPhpTypeInfo().RuntimeMethods[TypeMethods.MagicMethods.get_item]; if (getter != null) { // TODO: Context is null, should no be used but ... return getter.Invoke(null, _instance, index); } else { throw new NotSupportedException(); } } public void RemoveKey(IntStringKey key) => RemoveKey((PhpValue)key); public void RemoveKey(PhpValue index) => throw new NotSupportedException(); public void SetItemAlias(IntStringKey key, PhpAlias alias) => SetItemAlias((PhpValue)key, alias); public void SetItemAlias(PhpValue index, PhpAlias alias) { throw new NotImplementedException(); } public void SetItemValue(IntStringKey key, PhpValue value) => SetItemValue((PhpValue)key, value); public void SetItemValue(PhpValue index, PhpValue value) { var setter = _instance.GetPhpTypeInfo().RuntimeMethods[TypeMethods.MagicMethods.set_item]; if (setter != null) { // TODO: Context is null, should no be used but ... setter.Invoke(null, _instance, index, value); } else { throw new NotSupportedException(); } } } public static IPhpArray EnsureArray(ArrayAccess obj) { Debug.Assert(obj != null); return new ArrayAccessAsPhpArray(obj); } public static IPhpArray EnsureArray(object obj) { // IPhpArray if (obj is IPhpArray) return (IPhpArray)obj; // ArrayAccess if (obj is ArrayAccess) return EnsureArray((ArrayAccess)obj); // IList if (obj is IList) return new ListAsPhpArray((IList)obj); // TODO: IDictionary // get_Item if (obj.GetPhpTypeInfo().RuntimeMethods[TypeMethods.MagicMethods.get_item] != null) { return new GetSetItemAsPhpArray(obj); } // Fatal error: Uncaught Error: Cannot use object of type {0} as array PhpException.Throw(PhpError.Error, Resources.ErrResources.object_used_as_array, obj.GetPhpTypeInfo().Name); throw new ArgumentException(nameof(obj)); } /// <summary> /// Gets <see cref="IPhpArray"/> instance providing access to the value with array operators. /// Returns <c>null</c> if underlaying value does provide array access. /// </summary> public static IPhpArray GetArrayAccess(ref PhpValue value) => value.TypeCode switch { // TODO // CONSIDER: what is this? PhpTypeCode.PhpArray => value.Array, PhpTypeCode.String => PhpValue.EnsureArray(ref value), PhpTypeCode.MutableString => value.MutableStringBlob, PhpTypeCode.Object => EnsureArray(value.Object), PhpTypeCode.Alias => value.Alias.EnsureArray(), _ => null, }; /// <summary> /// Gets <see cref="IPhpArray"/> to be used as R-value of <c>list</c> expression. /// </summary> public static IPhpArray GetListAccess(PhpValue value) { switch (value.TypeCode) { case PhpTypeCode.PhpArray: return value.Array; case PhpTypeCode.Object: return EnsureArray(value.Object); case PhpTypeCode.Alias: return GetListAccess(value.Alias.Value); default: // TODO: some kind of debug log would be nice, PHP does not do that return PhpArray.Empty; } } /// <summary> /// Gets <see cref="IPhpArray"/> to be used as R-value of <c>list</c> expression. /// </summary> public static IPhpArray GetListAccess(object value) => EnsureArray(value); /// <summary> /// Implements <c>[]</c> operator on <see cref="string"/>. /// </summary> /// <param name="value">String to be accessed as array.</param> /// <param name="index">Index.</param> /// <returns>Character on index or empty string if index is our of range.</returns> public static string GetItemValue(string value, long index) { return (value != null && index >= 0 && index < value.Length) ? value[unchecked((int)index)].ToString() : string.Empty; // TODO: quiet ? } /// <summary> /// Implements <c>[]</c> operator on <see cref="string"/>. /// </summary> public static string GetItemValue(string value, IntStringKey key) { var index = key.IsInteger ? key.Integer : Convert.StringToLongInteger(key.String); return GetItemValue(value, index); } /// <summary> /// Implements <c>[]</c> operator on <see cref="string"/> with <c>isset</c> semantics. /// </summary> public static string GetItemValueOrNull(string value, IntStringKey key) { var index = key.IsInteger ? key.Integer : Convert.StringToLongInteger(key.String); return (value != null && index >= 0 && index < value.Length) ? value[unchecked((int)index)].ToString() : null; } /// <summary> /// Implements <c>[]</c> operator on <see cref="string"/>. /// </summary> public static string GetItemValue(string value, PhpValue index, bool quiet) { if (value != null && index.TryToIntStringKey(out var key)) { long i; if (key.IsInteger) { i = key.Integer; } else { if (quiet) return null; i = Convert.StringToLongInteger(key.String); } if (i >= 0 && i < value.Length) { return value[(int)i].ToString(); } } // if (quiet) { // used by isset() and empty() return null; } else { PhpException.Throw(PhpError.Warning, Resources.ErrResources.illegal_string_offset, index.ToString()); return string.Empty; } } /// <summary> /// Shortcut for calling <c>ord($s[$i])</c> on a <see cref="PhpValue"/> /// without any extra allocation. /// </summary> public static long GetItemOrdValue(PhpValue value, long index) { switch (value.TypeCode) { case PhpTypeCode.String: return GetItemOrdValue(value.String, index); case PhpTypeCode.MutableString: return GetItemOrdValue(value.MutableString, index); case PhpTypeCode.Alias: return GetItemOrdValue(value.Alias.Value, index); default: var item = value.GetArrayItem(index); if (item.IsMutableString(out var itemPhpString)) { return itemPhpString.IsEmpty ? 0 : itemPhpString[0]; } else { var str = item.ToStringUtf8(); return string.IsNullOrEmpty(str) ? 0 : str[0]; } } } /// <summary> /// Shortcut for calling <c>ord($s[$i])</c> on a <see cref="string"/> /// without any extra allocation. /// </summary> public static long GetItemOrdValue(string value, long index) { if (value != null && index >= 0 && index < value.Length) { return value[(int)index]; } // PhpException.Throw(PhpError.Warning, Resources.ErrResources.illegal_string_offset, index.ToString()); return 0; } /// <summary> /// Shortcut for calling <c>ord($s[$i])</c> on a <see cref="PhpString"/> /// without any extra allocation. /// </summary> public static long GetItemOrdValue(PhpString value, long index) { if (index >= 0 && index < value.Length) { return value[(int)index]; } PhpException.Throw(PhpError.Warning, Resources.ErrResources.illegal_string_offset, index.ToString()); return 0; } public static object EnsureItemObject(this IPhpArray array, PhpValue index) { if (index.TryToIntStringKey(out var key)) { return array.EnsureItemObject(key); } else { throw PhpException.TypeErrorException(Resources.ErrResources.illegal_offset_type); } } public static IPhpArray EnsureItemArray(this IPhpArray array, PhpValue index) { if (index.TryToIntStringKey(out var key)) { return array.EnsureItemArray(key); } else { throw PhpException.TypeErrorException(Resources.ErrResources.illegal_offset_type); } } public static PhpAlias EnsureItemAlias(this IPhpArray array, PhpValue index, bool quiet) { if (index.TryToIntStringKey(out var key)) { return array.EnsureItemAlias(key); } else { if (!quiet) { PhpException.IllegalOffsetType(); } return PhpAlias.Create(PhpValue.Null); } } /// <summary> /// Implements <c>[]</c> operator on <see cref="PhpValue"/>. /// </summary> public static PhpValue GetItemValue(PhpValue value, PhpValue index, bool quiet = false) { switch (value.TypeCode) { case PhpTypeCode.PhpArray: return value.Array.GetItemValue(index); // , quiet); case PhpTypeCode.String: var item = GetItemValue(value.String, index, quiet); if (quiet && string.IsNullOrEmpty(item)) { return PhpValue.Null; } return item; case PhpTypeCode.MutableString: return value.MutableStringBlob.GetItemValue(index); // quiet); case PhpTypeCode.Object: return Operators.GetItemValue(value.Object, index, quiet); case PhpTypeCode.Alias: return value.Alias.Value.GetArrayItem(index, quiet); default: // TODO: warning return PhpValue.Null; } } /// <summary> /// Implements <c>[]</c> operator on <see cref="PhpValue"/>. /// </summary> public static PhpValue GetItemValue(object obj, PhpValue index, bool quiet = false) { // IPhpArray.GetItemValue if (obj is IPhpArray arr) { return arr.GetItemValue(index); // , quiet); } // ArrayAccess.offsetGet() if (obj is ArrayAccess arracces) { return arracces.offsetGet(index); } // IList[] if (obj is IList list) { if (index.TryToIntStringKey(out var key) && key.IsInteger) { if (key.Integer >= 0 && key.Integer < list.Count) { return PhpValue.FromClr(list[(int)key.Integer]); } else if (!quiet) { PhpException.UndefinedOffset(key); } } else if (!quiet) { PhpException.IllegalOffsetType(); } return PhpValue.Null; } // TODO: IDictionary // get_Item if (obj != null) { var getter = obj.GetPhpTypeInfo().RuntimeMethods[TypeMethods.MagicMethods.get_item]; if (getter != null) { return getter.Invoke(null, obj, index); } } // if (!quiet) { PhpException.ObjectUsedAsArray(PhpVariable.GetClassName(obj)); } // return PhpValue.Null; } public static bool TryGetItemValue(this PhpArray value, string index, out PhpValue item) { if (value != null && value.TryGetValue(index, out item) && IsSet(item)) { return true; } else { item = default; return false; } } public static bool TryGetItemValue(this PhpArray value, PhpValue index, out PhpValue item) { if (value != null && index.TryToIntStringKey(out var key) && value.TryGetValue(key, out item) && IsSet(item)) { return true; } else { item = default; return false; } } public static bool TryGetItemValue(this PhpValue value, PhpValue index, out PhpValue item) { if (value.IsPhpArray(out var array)) { // Specialized call for array return TryGetItemValue(array, index, out item); } else { // Otherwise use the original semantics of isset($x[$y]) ? $x[$y] : ...; if (offsetExists(value, index)) { item = GetItemValue(value, index); return true; } else { item = default; return false; } } } /// <summary> /// /// </summary> public static PhpAlias EnsureItemAlias_Old(PhpValue value, PhpValue index, bool quiet = false) { Debug.WriteLineIf(value.IsNull, "NULL value won't be changed to array!"); return EnsureItemAlias(ref value, index, quiet); } /// <summary> /// Implements <c>&amp;[]</c> operator on <see cref="PhpValue"/>. /// Ensures the value is an array and item at given <paramref name="index"/> is an alias. /// </summary> public static PhpAlias EnsureItemAlias(ref PhpValue value, PhpValue index, bool quiet = false) { switch (value.TypeCode) { case PhpTypeCode.Null: // TODO: Err: Warning: Creating default object from empty value var arr = new PhpArray(); value = PhpValue.Create(arr); return arr.EnsureItemAlias(index, quiet); case PhpTypeCode.PhpArray: return value.Array.EnsureItemAlias(index, quiet); case PhpTypeCode.String: throw new NotImplementedException(); case PhpTypeCode.MutableString: throw new NotImplementedException(); case PhpTypeCode.Object: if (value.Object is IPhpArray array) { return EnsureItemAlias(array, index, quiet); } if (!quiet) // NOTE: PHP does not report this error (?) { PhpException.Throw(PhpError.Error, Resources.ErrResources.object_used_as_array, value.Object.GetPhpTypeInfo().Name); } break; case PhpTypeCode.Alias: return value.Alias.EnsureItemAlias(index, quiet); } // TODO: Warning return PhpAlias.Create(PhpValue.Null); } public static bool offsetExists(this PhpArray value, long index) => value != null && value.TryGetValue((int)index, out var x) && IsSet(x); public static bool offsetExists(this PhpArray value, string index) => value != null && value.TryGetValue(index, out var x) && IsSet(x); public static bool offsetExists(this PhpArray value, PhpValue index) => value != null && index.TryToIntStringKey(out var key) && value.TryGetValue(key, out var x) && IsSet(x); public static bool offsetExists(this string value, PhpValue index) { return index.TryToIntStringKey(out var key) && key.IsInteger && offsetExists(value, key.Integer); } public static bool offsetExists(this string value, long index) { return value != null && index >= 0 && index < value.Length; } public static bool offsetExists(this PhpString value, long index) { return index >= 0 && index < value.Length; } public static bool offsetExists(object obj, PhpValue index) { if (obj is ArrayAccess arrrayAccess) { return arrrayAccess.offsetExists(index); } else if (obj is IPhpArray arr) { return IsSet(arr.GetItemValue(index)); } else if (obj is IList list) { return index.TryToIntStringKey(out var key) && key.IsInteger && key.Integer >= 0 && key.Integer < list.Count; } // TODO: IDictionary return false; } public static bool offsetExists(PhpAlias alias, PhpValue index) => offsetExists(alias.Value, index); public static bool offsetExists(this PhpValue value, PhpValue index) { if (value.Object is PhpArray array) { return offsetExists(array, index); } else if (value.Object is string str) { return offsetExists(str, index); } else if (value.Object is PhpString.Blob blob) { return index.TryToIntStringKey(out var key) && key.IsInteger && key.Integer >= 0 && key.Integer < blob.Length; } else if (value.Object is PhpAlias alias) { return offsetExists(alias.Value, index); } else if (value.Object != null) { // class instance return offsetExists(value.Object, index); } // scalar or NULL return false; } #endregion #region Object public static bool PropertyExists(RuntimeTypeHandle caller, object instance, PhpValue prop) { var tinfo = instance.GetPhpTypeInfo(); // 1. instance property // 2. runtime property // 3. __isset // false throw new NotImplementedException(); } public static PhpValue PropertyGetValue(RuntimeTypeHandle caller, object instance, PhpValue propertyName) { var tinfo = instance.GetPhpTypeInfo(); // 1. instance property // 2. runtime property // 3. __get // error throw new NotImplementedException(); } public static void PropertySetValue(RuntimeTypeHandle caller, object instance, PhpValue prop, PhpValue value) { var tinfo = instance.GetPhpTypeInfo(); // 1. instance property // 2. overwrite runtime property // 3. __set ?? runtime property // error throw new NotImplementedException(); } public static void PropertyUnset(RuntimeTypeHandle caller, object instance, PhpValue prop) { var tinfo = instance.GetPhpTypeInfo(); // 1. instance property // 2. unset runtime property // 3. __unset throw new NotImplementedException(); } /// <summary> /// Gets <see cref="PhpTypeInfo"/> from a string or an object instance. /// </summary> /// <param name="ctx">Current runtime context.</param> /// <param name="object">String or object. Other value types cause an exception.</param> /// <returns>Corresponding <see cref="PhpTypeInfo"/> descriptor. Cannot be <c>null</c>.</returns> public static PhpTypeInfo TypeNameOrObjectToType(Context ctx, PhpValue @object) { object obj; string str; if ((obj = (@object.AsObject())) != null) { return obj.GetType().GetPhpTypeInfo(); } else if ((str = PhpVariable.AsString(@object)) != null) { return ctx.GetDeclaredType(str, true); } else { throw new ArgumentException(); } } /// <summary> /// Resolves the runtime property by looking into runtime properties and eventually invoking the <c>__get</c> magic method. /// </summary> public static PhpValue RuntimePropertyGetValue(Context/*!*/ctx, object/*!*/instance, string propertyName, bool quiet) { return RuntimePropertyGetValue(ctx, instance.GetPhpTypeInfo(), instance, propertyName, quiet); } /// <summary> /// Resolves the runtime property by looking into runtime properties and eventually invoking the <c>__get</c> magic method. /// </summary> public static PhpValue RuntimePropertyGetValue(Context/*!*/ctx, PhpTypeInfo/*!*/type, object/*!*/instance, string propertyName, bool quiet) { var runtimeFields = type.GetRuntimeFields(instance); if (runtimeFields != null && runtimeFields.TryGetValue(propertyName, out var value)) { return value; } var __get = type.RuntimeMethods[TypeMethods.MagicMethods.__get]; if (__get != null) { // NOTE: magic methods must have public visibility, therefore the visibility check is unnecessary // int subkey1 = access.Write() ? 1 : access.Unset() ? 2 : access.Isset() ? 3 : 4; int subkey = propertyName.GetHashCode() ^ (1 << 4/*subkey1*/); using (var token = new Context.RecursionCheckToken(ctx, instance, subkey)) { if (!token.IsInRecursion) { return __get.Invoke(ctx, instance, propertyName); } } } // if (!quiet) { PhpException.UndefinedProperty(type.Name, propertyName); } // empty return PhpValue.Null; } #endregion #region self, parent /// <summary> /// Gets <see cref="PhpTypeInfo"/> of self. /// Throws in case of self being used out of class context. /// </summary> public static PhpTypeInfo GetSelf(RuntimeTypeHandle self) { if (self.Equals(default(RuntimeTypeHandle))) { PhpException.ThrowSelfOutOfClass(); } // return self.GetPhpTypeInfo(); } /// <summary> /// Gets <see cref="PhpTypeInfo"/> of self or <c>null</c>. /// </summary> public static PhpTypeInfo GetSelfOrNull(RuntimeTypeHandle self) => self.GetPhpTypeInfo(); /// <summary> /// Gets <see cref="PhpTypeInfo"/> of parent. /// Throws in case of parent being used out of class context or within a parentless class. /// </summary> public static PhpTypeInfo GetParent(RuntimeTypeHandle self) => GetParent(self.GetPhpTypeInfo()); /// <summary> /// Gets <see cref="PhpTypeInfo"/> of parent. /// Throws in case of parent being used out of class context or within a parentless class. /// </summary> public static PhpTypeInfo GetParent(PhpTypeInfo self) { if (self == null) { PhpException.Throw(PhpError.Error, Resources.ErrResources.parent_used_out_of_class); } else { var t = self.BaseType; if (t != null) { return t; } else { PhpException.Throw(PhpError.Error, Resources.ErrResources.parent_accessed_in_parentless_class); } } // throw new ArgumentException(nameof(self)); } #endregion #region GetForeachEnumerator /// <summary> /// Provides the <see cref="IPhpEnumerator"/> interface by wrapping a user-implemeted <see cref="Iterator"/>. /// </summary> /// <remarks> /// Instances of this class are iterated when <c>foreach</c> is used on object of a class /// that implements <see cref="Iterator"/> or <see cref="IteratorAggregate"/>. /// </remarks> [DebuggerNonUserCode, DebuggerStepThrough] private sealed class PhpIteratorEnumerator : IPhpEnumerator { readonly Iterator _iterator; bool _hasmoved; public PhpIteratorEnumerator(Iterator iterator) { Debug.Assert(iterator != null); _iterator = iterator; Reset(); } public bool AtEnd { get { throw new NotImplementedException(); } } public KeyValuePair<PhpValue, PhpValue> Current => new KeyValuePair<PhpValue, PhpValue>(CurrentKey, CurrentValue); public PhpValue CurrentKey => _iterator.key().DeepCopy(); public PhpValue CurrentValue => _iterator.current().DeepCopy(); public PhpAlias CurrentValueAliased { get { var value = _iterator.current(); return PhpValue.EnsureAlias(ref value); } } object IEnumerator.Current => Current; public void Dispose() { } public bool MoveFirst() { Reset(); return _iterator.valid(); } public bool MoveLast() { throw new NotImplementedException(); } public bool MoveNext() { if (_hasmoved) { _iterator.next(); } else { _hasmoved = true; } return _iterator.valid(); } public bool MovePrevious() { throw new NotImplementedException(); } public void Reset() { _hasmoved = false; _iterator.rewind(); } } /// <summary> /// Provides <see cref="IPhpEnumerator"/> implementation enumerating class instance fields and runtime fields. /// </summary> private sealed class PhpFieldsEnumerator : IPhpEnumerator { readonly IEnumerator<KeyValuePair<IntStringKey, PhpValue>> _enumerator; bool _valid; public PhpFieldsEnumerator(object obj, RuntimeTypeHandle caller) { Debug.Assert(obj != null); _enumerator = TypeMembersUtils.EnumerateVisibleInstanceFields(obj, caller).GetEnumerator(); _valid = true; } public bool AtEnd => !_valid; public KeyValuePair<PhpValue, PhpValue> Current { get { var current = _enumerator.Current; return new KeyValuePair<PhpValue, PhpValue>(PhpValue.Create(current.Key), current.Value); } } public PhpValue CurrentKey => PhpValue.Create(_enumerator.Current.Key); public PhpValue CurrentValue => _enumerator.Current.Value.GetValue().DeepCopy(); public PhpAlias CurrentValueAliased { get { var value = _enumerator.Current.Value; return PhpValue.EnsureAlias(ref value); } } object IEnumerator.Current => _enumerator.Current; public void Dispose() => _enumerator.Dispose(); public bool MoveFirst() { Reset(); return MoveNext(); } public bool MoveLast() { throw new NotImplementedException(); } public bool MoveNext() { return (_valid = _enumerator.MoveNext()); } public bool MovePrevious() { throw new NotSupportedException(); } public void Reset() { throw new NotSupportedException(); } } /// <summary> /// Implements empty enumeration. /// </summary> private sealed class PhpEmptyEnumerator : IPhpEnumerator { public static readonly IPhpEnumerator Instance = new PhpEmptyEnumerator(); private PhpEmptyEnumerator() { } public bool AtEnd => false; public KeyValuePair<PhpValue, PhpValue> Current => default(KeyValuePair<PhpValue, PhpValue>); public PhpValue CurrentKey => PhpValue.Null; public PhpValue CurrentValue => PhpValue.Null; public PhpAlias CurrentValueAliased => PhpAlias.Create(PhpValue.Null); object IEnumerator.Current => null; public void Dispose() { } public bool MoveFirst() => false; public bool MoveLast() => false; public bool MoveNext() => false; public bool MovePrevious() => false; public void Reset() { } } #region ClrEnumeratorFactory abstract class ClrEnumeratorFactory { public static IPhpEnumerator CreateEnumerator(IEnumerable enumerable) { Debug.Assert(enumerable != null); // special cases before using reflection if (enumerable is IEnumerable<(PhpValue, PhpValue)> valval) return new ValueTupleEnumerator<PhpValue, PhpValue>(valval); if (enumerable is IDictionary) return new DictionaryEnumerator(((IDictionary)enumerable).GetEnumerator()); if (enumerable is IEnumerable<KeyValuePair<object, object>> kv) return new KeyValueEnumerator<object, object>(kv); if (enumerable is IEnumerable<object>) return new EnumerableEnumerator(enumerable.GetEnumerator()); // TODO: cache following for the enumerable type // find IEnumerable<> foreach (var iface_type in enumerable.GetType().GetInterfaces()) { if (iface_type.IsGenericType && iface_type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { var item_type = iface_type.GenericTypeArguments[0]; if (item_type.IsGenericType) { // ValueTuple<A, B> if (item_type.GetGenericTypeDefinition() == typeof(ValueTuple<,>)) { return (ClrEnumerator)Activator.CreateInstance( typeof(ValueTupleEnumerator<,>).MakeGenericType(item_type.GetGenericArguments()), enumerable); } // KeyValuePair<A, B> if (item_type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) { return (ClrEnumerator)Activator.CreateInstance( typeof(KeyValueEnumerator<,>).MakeGenericType(item_type.GetGenericArguments()), enumerable); } } } } // generic return new EnumerableEnumerator(enumerable.GetEnumerator()); } abstract class ClrEnumerator : IPhpEnumerator { abstract protected IEnumerator Enumerator { get; } /// <summary> /// Current key and value. /// </summary> PhpValue _key, _value; abstract protected void FetchCurrent(ref PhpValue key, ref PhpValue value); public bool AtEnd => throw new NotSupportedException(); public PhpValue CurrentValue => _value; public PhpAlias CurrentValueAliased => _value.IsAlias ? _value.Alias : throw new InvalidOperationException(); public PhpValue CurrentKey => _key; public KeyValuePair<PhpValue, PhpValue> Current => new KeyValuePair<PhpValue, PhpValue>(CurrentKey, CurrentValue); object IEnumerator.Current => Enumerator.Current; public void Dispose() { _key = _value = PhpValue.Null; (Enumerator as IDisposable)?.Dispose(); } public virtual bool MoveFirst() { Enumerator.Reset(); return MoveNext(); } public virtual bool MoveLast() { throw new NotImplementedException(); } public virtual bool MoveNext() { if (Enumerator.MoveNext()) { FetchCurrent(ref _key, ref _value); return true; } else { return false; } } public virtual bool MovePrevious() { throw new NotSupportedException(); } void IEnumerator.Reset() => Enumerator.Reset(); } /// <summary> /// Enumerator of <see cref="IEnumerable"/>. /// </summary> sealed class EnumerableEnumerator : ClrEnumerator { readonly IEnumerator _enumerator; protected override IEnumerator Enumerator => _enumerator; long _key; public override bool MoveFirst() { _key = -1; return base.MoveFirst(); } public override bool MoveNext() { _key++; return base.MoveNext(); } protected override void FetchCurrent(ref PhpValue key, ref PhpValue value) { key = _key; value = PhpValue.FromClr(_enumerator.Current); } public EnumerableEnumerator(IEnumerator enumerator) { Debug.Assert(enumerator != null); _enumerator = enumerator; _key = -1; } } /// <summary> /// Enumerator of <see cref="IDictionary"/> /// </summary> sealed class DictionaryEnumerator : ClrEnumerator { readonly IDictionaryEnumerator _enumerator; protected override IEnumerator Enumerator => _enumerator; protected override void FetchCurrent(ref PhpValue key, ref PhpValue value) { var entry = _enumerator.Entry; key = PhpValue.FromClr(entry.Key); value = PhpValue.FromClr(entry.Value); } public DictionaryEnumerator(IDictionaryEnumerator enumerator) { Debug.Assert(enumerator != null); _enumerator = enumerator; } } sealed class ValueTupleEnumerator<K, V> : ClrEnumerator { readonly IEnumerator<(K, V)> _enumerator; protected override IEnumerator Enumerator => _enumerator; protected override void FetchCurrent(ref PhpValue key, ref PhpValue value) { var entry = _enumerator.Current; key = PhpValue.FromClr(entry.Item1); value = PhpValue.FromClr(entry.Item2); } public ValueTupleEnumerator(IEnumerable<(K, V)> enumerable) { Debug.Assert(enumerable != null); _enumerator = enumerable.GetEnumerator(); } } sealed class KeyValueEnumerator<K, V> : ClrEnumerator { readonly IEnumerator<KeyValuePair<K, V>> _enumerator; protected override IEnumerator Enumerator => _enumerator; protected override void FetchCurrent(ref PhpValue key, ref PhpValue value) { var entry = _enumerator.Current; key = PhpValue.FromClr(entry.Key); value = PhpValue.FromClr(entry.Value); } public KeyValueEnumerator(IEnumerable<KeyValuePair<K, V>> enumerable) { Debug.Assert(enumerable != null); _enumerator = enumerable.GetEnumerator(); } } } #endregion /// <summary> /// Gets <see cref="Iterator"/> object enumerator. /// </summary> /// <returns>Instance of the enumerator. Cannot be <c>null</c>.</returns> public static IPhpEnumerator GetForeachEnumerator(Iterator it) { Debug.Assert(it != null); return new PhpIteratorEnumerator(it); } /// <summary> /// Resolves object enumerator. /// </summary> /// <exception cref="Exception">Object cannot be enumerated.</exception> /// <returns>Instance of the object enumerator. Cannot be <c>null</c>.</returns> public static IPhpEnumerator GetForeachEnumerator(object obj, bool aliasedValues, RuntimeTypeHandle caller) { Debug.Assert(obj != null); if (obj is Iterator) { return GetForeachEnumerator((Iterator)obj); } else if (obj is IteratorAggregate) { var last_obj = obj; do { obj = ((IteratorAggregate)obj).getIterator(); } while (obj is IteratorAggregate); if (obj is Iterator) { return GetForeachEnumerator((Iterator)obj); } else { var errmessage = string.Format(Resources.ErrResources.getiterator_must_return_traversable, last_obj.GetType().GetPhpTypeInfo().Name); // throw new (SPL)Exception(ctx, message, 0, null) //Library.SPL.Exception.ThrowSplException( // _ctx => new Library.SPL.Exception(_ctx, true), // context, // string.Format(CoreResources.getiterator_must_return_traversable, last_obj.TypeName), 0, null); throw new ArgumentException(errmessage); } } else if (obj is IPhpEnumerable phpenumerable) { return phpenumerable.GetForeachEnumerator(aliasedValues, caller); } else if (obj is IEnumerable enumerable) { // IDictionaryEnumerator, IEnumerable<ValueTuple>, IEnumerable<KeyValuePair>, IEnumerable, ... return GetForeachEnumerator(enumerable); } else { // PHP property enumeration return new PhpFieldsEnumerator(obj, caller); } } /// <summary> /// Gets <see cref="IPhpEnumerator"/> from regular .NET <see cref="IEnumerable"/>. /// Enumerator is reflected to properly unwrap <c>key</c> and <c>value</c> of PHP enumeration. /// Supported interfaces are <see cref="IDictionaryEnumerator"/>, <see cref="IEnumerable{ValueTuple}"/>, <see cref="IEnumerable{KeyValuePair}"/>, <see cref="IEnumerable"/> etc. /// See <see cref="ClrEnumeratorFactory"/> for more details. /// </summary> internal static IPhpEnumerator GetForeachEnumerator(IEnumerable enumerable) => ClrEnumeratorFactory.CreateEnumerator(enumerable); /// <summary> /// Gets PHP enumerator of <c>NULL</c> or <b>empty</b> value. /// </summary> public static IPhpEnumerator GetEmptyForeachEnumerator() => PhpEmptyEnumerator.Instance; /// <summary> /// Gets enumerator object for given value. /// </summary> public static IPhpEnumerator GetForeachEnumerator(PhpValue value, bool aliasedValues, RuntimeTypeHandle caller) => value.GetForeachEnumerator(aliasedValues, caller); /// <summary> /// Gets enumerator of array entries. /// This is internal implementation that avoids allocations in common cases. /// </summary> public static OrderedDictionary.FastEnumerator GetFastEnumerator(PhpArray array, bool aliasedValue) { Debug.Assert(array != null); if (array.Count == 0) { // follows call to MoveNext() which ends the enumeration // keep array as it is, it won't be accessed anyways } else if (aliasedValue) { // ensure array is not shared with another variable array.EnsureWritable(); } else { // create lazy copy array.table.AddRef(); } return array.GetFastEnumerator(); } #endregion #region Copy, Unpack /// <summary> /// Gets copy of given value. /// </summary> public static PhpValue DeepCopy(PhpValue value) => value.DeepCopy(); /// <summary> /// Deep copies the value in-place. /// Called when this has been passed by value and inplace dereferencing and copying is necessary. /// </summary> [DebuggerNonUserCode, DebuggerStepThrough] public static void PassValue(ref PhpValue value) { switch (value.TypeCode) { case PhpTypeCode.MutableString: // lazy copy value.MutableStringBlob.AddRef(); break; case PhpTypeCode.PhpArray: // lazy copy value = new PhpValue(value.Array.DeepCopy()); break; case PhpTypeCode.Alias: // dereference & lazy copy value = value.Alias.Value.DeepCopy(); break; } } /// <summary> /// Performs <c>clone</c> operation on given object. /// </summary> public static object Clone(Context ctx, object value) { if (value is IPhpCloneable cloneable) { value = cloneable.Clone(); } else if (value != null) { value = CloneRaw(ctx, value); } else { PhpException.Throw(PhpError.Error, Resources.ErrResources.clone_called_on_non_object); } // return value; } /// <summary> /// Performs memberwise clone of the object. /// Calling <c>__clone</c> eventually. /// </summary> public static object CloneRaw(Context ctx, object value) { if (value == null) throw new ArgumentNullException(nameof(value)); var tinfo = value.GetPhpTypeInfo(); // memberwise clone var newobj = tinfo.CreateUninitializedInstance(ctx); if (newobj != null) { Serialization.MemberwiseClone(tinfo, value, newobj); // value = newobj; // __clone(), only if __clone() is public var __clone = tinfo.RuntimeMethods[TypeMethods.MagicMethods.__clone]; if (__clone != null && __clone.IsPublic()) { __clone.Invoke(ctx, value); } } else { PhpException.Throw(PhpError.Error, Resources.ErrResources.class_instantiation_failed, tinfo.Name); } // return value; } /// <summary> /// Every property of type <see cref="PhpValue"/> will be deeply copied inplace, including runtime fields. /// Calling <c>__clone</c> eventually. /// </summary> public static object CloneInPlace(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); var tinfo = value.GetPhpTypeInfo(); // clone runtime fields: if (tinfo.RuntimeFieldsHolder != null) { var runtimefields = (PhpArray)tinfo.RuntimeFieldsHolder.GetValue(value); tinfo.RuntimeFieldsHolder.SetValue(value, runtimefields?.Clone()); } // deep copy instance fields (of type PhpValue) foreach (var p in tinfo.DeclaredFields.InstanceProperties.OfType<PhpPropertyInfo.ClrFieldProperty>()) { if (p.Field.FieldType == typeof(PhpValue)) { var oldvalue = (PhpValue)p.Field.GetValue(value); p.Field.SetValue(value, (object)oldvalue.DeepCopy()); } } // __clone(), only if __clone() is public var __clone = tinfo.RuntimeMethods[TypeMethods.MagicMethods.__clone]; if (__clone != null && __clone.IsPublic()) { __clone.Invoke(null, value); // 'ctx' is not needed ... probably } // return value; } /// <summary> /// The method implements <c>...</c> unpack operator. /// Unpacks <paramref name="argument"/> into <paramref name="stack"/>. /// </summary> /// <param name="stack">The list with unpacked arguments.</param> /// <param name="argument">Value to be unpacked.</param> /// <param name="byrefs">Bit mask of parameters that are passed by reference. Arguments corresponding to <c>1</c>-bit are aliased.</param> public static void Unpack(List<PhpValue> stack, PhpValue argument, ulong byrefs) { // https://wiki.php.net/rfc/argument_unpacking switch (argument.TypeCode) { case PhpTypeCode.PhpArray: Unpack(stack, argument.Array, byrefs); break; case PhpTypeCode.Object: if (argument.Object is Traversable traversable) { Unpack(stack, traversable, byrefs); break; } else if (argument.Object is Array array) { Unpack(stack, array, byrefs); break; } else { goto default; } case PhpTypeCode.Alias: Unpack(stack, argument.Alias.Value, byrefs); break; default: // TODO: Warning: Only arrays and Traversables can be unpacked // do not add item to the arguments list // stack.Add(argument); break; } } /// <summary> /// The method implements <c>...</c> unpack operator. /// Unpacks <paramref name="array"/> into <paramref name="stack"/>. /// </summary> /// <param name="stack">The list with unpacked arguments.</param> /// <param name="array">Value to be unpacked.</param> /// <param name="byrefs">Bit mask of parameters that are passed by reference. Arguments corresponding to <c>1</c>-bit are aliased.</param> public static void Unpack(List<PhpValue> stack, PhpArray array, ulong byrefs) { Debug.Assert(array != null); var enumerator = array.GetFastEnumerator(); while (enumerator.MoveNext()) { if (enumerator.CurrentKey.IsString) { // TODO: E_RECOVERABLE error break; // no further arguments will be unpacked } if ((byrefs & (1ul << stack.Count)) == 0) { // pass by value stack.Add(enumerator.CurrentValue); } else { // pass by reference stack.Add(PhpValue.Create(enumerator.CurrentValueAliased)); } } } /// <summary> /// The method implements <c>...</c> unpack operator. /// Unpacks <paramref name="array"/> into <paramref name="stack"/>. /// </summary> /// <param name="stack">The list with unpacked arguments.</param> /// <param name="array">Value to be unpacked.</param> /// <param name="byrefs">Bit mask of parameters that are passed by reference. Arguments corresponding to <c>1</c>-bit are aliased.</param> static void Unpack(List<PhpValue> stack, Array array, ulong byrefs) { for (int i = 0; i < array.Length; i++) { stack.Add(PhpValue.FromClr(array.GetValue(i))); } } /// <summary> /// The method implements <c>...</c> unpack operator. /// Unpacks <paramref name="traversable"/> into <paramref name="stack"/>. /// </summary> /// <param name="stack">The list with unpacked arguments.</param> /// <param name="traversable">Value to be unpacked.</param> /// <param name="byrefs">Bit mask of parameters that are passed by reference. Arguments corresponding to <c>1</c>-bit are aliased.</param> public static void Unpack(List<PhpValue> stack, Traversable traversable, ulong byrefs) { Debug.Assert(traversable != null); if (traversable is IteratorAggregate aggr) { Unpack(stack, aggr.getIterator(), byrefs); } else if (traversable is Iterator iterator) { iterator.rewind(); while (iterator.valid()) { Debug.Assert((byrefs & (1ul << stack.Count)) == 0, "Cannot pass by-reference when unpacking a Traversable"); //{ // // TODO: Warning: Cannot pass by-reference argument {stack.Count + 1} of {function_name}() by unpacking a Traversable, passing by-value instead //} stack.Add(iterator.current()); iterator.next(); } } else { throw new ArgumentException(); } } #endregion #region ReadConstant /// <summary> /// Gets constant value, throws <c>notice</c> if constant is not defined. /// </summary> public static PhpValue ReadConstant(Context ctx, string name, ref int idx) { Debug.Assert(name != null, nameof(name)); if (ctx.TryGetConstant(name, out var value, ref idx)) { return value; } else { // Warning: undefined constant PhpException.Throw(PhpError.Notice, Resources.ErrResources.undefined_constant, name); return name; } } /// <summary> /// Gets constant value, throws <c>notice</c> if constant is not defined. /// </summary> public static PhpValue ReadConstant(Context ctx, string name, ref int idx, string fallbackName) { Debug.Assert(name != null, nameof(name)); Debug.Assert(fallbackName != null, nameof(fallbackName)); if (ctx.TryGetConstant(name, out var value, ref idx) || ctx.TryGetConstant(fallbackName, out value)) { return value; } else { // Warning: undefined constant PhpException.Throw(PhpError.Notice, Resources.ErrResources.undefined_constant, fallbackName); return fallbackName; } } /// <summary> /// Constant declaration. /// </summary> public static void DeclareConstant(Context ctx, string name, ref int idx, PhpValue value) { ctx.DefineConstant(name, value, ref idx, ignorecase: false); } #endregion #region Closure public static RoutineInfo AnonymousRoutine(string name, RuntimeMethodHandle handle) => new PhpAnonymousRoutineInfo(name, handle); /// <summary> /// Create <see cref="Closure"/> with specified anonymous function and used parameters. /// </summary> public static Closure BuildClosure(Context/*!*/ctx, IPhpCallable routine, object @this, RuntimeTypeHandle scope, PhpTypeInfo statictype, PhpArray/*!*/parameter, PhpArray/*!*/@static) => new Closure(ctx, routine, @this, scope, statictype, parameter, @static); public static Context Context(this Closure closure) => closure._ctx; /// <summary>Resolves late static bound type of closiure. Can be <c>null</c> reference.</summary> public static PhpTypeInfo Static(this Closure closure) { if (closure._this != null) { // typeof $this return closure._this.GetPhpTypeInfo(); } if (closure._statictype != null) { // static return closure._statictype; } // self or NULL return closure._scope.GetPhpTypeInfo(); } public static RuntimeTypeHandle Scope(this Closure closure) => closure._scope; public static object This(this Closure closure) => closure._this; /// <summary> /// Gets internal <see cref="IPhpCallable"/> object invoked by the closure. /// </summary> public static IPhpCallable Callable(this Closure closure) => closure._callable; #endregion #region Generator /// <summary> /// Create <see cref="Generator"/> with specified state machine function and parameters. /// </summary> public static Generator BuildGenerator(Context ctx, PhpArray locals, PhpArray tmpLocals, GeneratorStateMachineDelegate smmethod, RuntimeMethodHandle ownerhandle) => new Generator(ctx, locals, tmpLocals, smmethod, ownerhandle); public static int GetGeneratorState(Generator g) => g._state; public static void SetGeneratorState(Generator g, int newState) => g._state = newState; /// <summary> /// In case generator has an exception, throws it. /// The current exception is then nullified. /// </summary> [DebuggerNonUserCode, DebuggerHidden] public static void HandleGeneratorException(Generator g) { var exception = g._currException; g._currException = null; if (exception != null) { throw exception; } } /// <summary>Set yielded value from generator where key is not specified.</summary> public static void SetGeneratorCurrent(Generator g, PhpValue value) { g._currValue = value; g._currKey = (PhpValue)(++g._maxNumericalKey); } /// <summary> /// Sets yielded value from generator with key. /// This operator does not update auto-incremented Generator key. /// </summary> public static void SetGeneratorCurrentFrom(Generator g, PhpValue value, PhpValue key) { g._currValue = value; g._currKey = key; } /// <summary>Set yielded value from generator with key.</summary> public static void SetGeneratorCurrent(Generator g, PhpValue value, PhpValue key) { SetGeneratorCurrentFrom(g, value, key); // update the Generator auto-increment key if (key.IsLong(out var ikey) && ikey > g._maxNumericalKey) { g._maxNumericalKey = ikey; } } public static PhpValue GetGeneratorSentItem(Generator g) => g._currSendItem; public static void SetGeneratorReturnedValue(Generator g, PhpValue value) => g._returnValue = value; public static object GetGeneratorThis(Generator g) => g._this; public static Generator SetGeneratorThis(this Generator generator, object @this) { generator._this = @this; return generator; } /// <summary> /// Resolves generator's <c>static</c> type. /// </summary> /// <returns><see cref="PhpTypeInfo"/> refering to the lazy static bound type. Cannot be <c>null</c>.</returns> public static PhpTypeInfo GetGeneratorLazyStatic(this Generator generator) { return generator._static ?? generator._this?.GetPhpTypeInfo() ?? throw new InvalidOperationException(); } public static Generator SetGeneratorLazyStatic(this Generator generator, PhpTypeInfo @static) { generator._static = @static; return generator; } public static Context GetGeneratorContext(Generator g) => g._ctx; public static GeneratorStateMachineDelegate GetGeneratorMethod(Generator g) => g._stateMachineMethod; public static MethodInfo GetGeneratorOwnerMethod(Generator g) => (MethodInfo)MethodBase.GetMethodFromHandle(g._ownerhandle); public static Generator SetGeneratorDynamicScope(this Generator g, RuntimeTypeHandle scope) { g._scope = scope; return g; } public static RuntimeTypeHandle GetGeneratorDynamicScope(this Generator g) => g._scope; #endregion #region Dynamic /// <summary> /// Performs dynamic code evaluation in given context. /// </summary> /// <returns>Evaluated code return value.</returns> public static PhpValue Eval(Context ctx, PhpArray locals, object @this, RuntimeTypeHandle self, string code, string currentpath, int line, int column) { Debug.Assert(ctx != null); Debug.Assert(locals != null); if (string.IsNullOrEmpty(code)) { return PhpValue.Null; } var script = Core.Context.DefaultScriptingProvider.CreateScript( new Context.ScriptOptions() { Context = ctx, Location = new Location(Path.Combine(ctx.RootPath, currentpath), line, column), EmitDebugInformation = Debugger.IsAttached, // CONSIDER // DOC IsSubmission = true, }, code); // return script.Evaluate(ctx, locals, @this, self); } #endregion #region Paths /// <summary> /// Normalizes path's slashes for the current platform. /// </summary> public static string NormalizePath(string value) => Utilities.CurrentPlatform.NormalizeSlashes(value); #endregion #region BindTargetToMethod /// <summary> /// Helper lightweight class to reuse already bound <see cref="PhpInvokable"/> to be used as <see cref="PhpCallable"/> /// by calling it on a given target. /// </summary> sealed class BoundTargetCallable : IPhpCallable { readonly object _target; readonly PhpInvokable _invokable; public BoundTargetCallable(object target, PhpInvokable invokable) { _target = target; _invokable = invokable; } public PhpValue Invoke(Context ctx, params PhpValue[] arguments) => _invokable.Invoke(ctx, _target, arguments); public PhpValue ToPhpValue() => PhpValue.Null; } /// <summary> /// Creates an <see cref="IPhpCallable"/> from an instance method, binding the target to call the method on. /// </summary> public static IPhpCallable BindTargetToMethod(object targetInstance, RoutineInfo routine) { if (routine is PhpMethodInfo methodInfo) { return new BoundTargetCallable(targetInstance, methodInfo.PhpInvokable); } return PhpCallback.CreateInvalid(); } #endregion } }
34.526863
234
0.515009
[ "Apache-2.0" ]
Mattlk13/peachpie
src/Peachpie.Runtime/Operators.cs
79,690
C#
using System; using System.Drawing; using DotNetCommons.WinForms.Graphics; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DotNetCommons.WinForms.Test.Graphics { [TestClass] public class ImageProcessorTest { [TestMethod] public void TestScaleMax() { var size = new Size(3344, 2210); var result = ImageProcessor.ScaleMax(size, new Size(640, 480)); Assert.AreEqual(640, result.Width); Assert.AreEqual(423, result.Height); } [TestMethod] public void TestScaleMin() { var size = new Size(3344, 2210); var result = ImageProcessor.ScaleMin(size, new Size(640, 480)); Assert.AreEqual(726, result.Width); Assert.AreEqual(480, result.Height); } } }
26.09375
75
0.607186
[ "MIT" ]
mgefvert/DotNetCommons
test/DotNetCommons.WinForms.Test/Graphics/ImageProcessorTest.cs
837
C#
namespace EventTraceKit.VsExtension.Resources.Styles { using System.Windows; using System.Windows.Media; using Microsoft.VisualStudio; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell.Interop; public class FontAndColorsResourceDictionary : ResourceDictionary { private readonly IVsFontAndColorStorage fncStorage; public FontAndColorsResourceDictionary(IVsFontAndColorStorage fncStorage) { this.fncStorage = fncStorage; } protected override void OnGettingValue(object key, ref object value, out bool canCache) { if (!(value is FontAndColorsResourceKey resourceKey)) { base.OnGettingValue(key, ref value, out canCache); return; } if (key is FontAndColorsResourceKey) value = RealizeValue(resourceKey); else value = base[resourceKey]; canCache = true; } private FontFamily GetFontFamily(FontAndColorsResourceKey key) { const __FCSTORAGEFLAGS flags = __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS; fncStorage.OpenCategory(key.Category, (uint)flags); try { var fontInfos = new FontInfo[1]; if (fncStorage.GetFont(null, fontInfos) != VSConstants.S_OK) return null; if (fontInfos[0].bFaceNameValid == 1) return new FontFamily(fontInfos[0].bstrFaceName); return null; } finally { fncStorage.CloseCategory(); } } private double GetFontSize(FontAndColorsResourceKey key) { const __FCSTORAGEFLAGS flags = __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS; const double defaultFontSize = 9; fncStorage.OpenCategory(key.Category, (uint)flags); try { var fontInfos = new FontInfo[1]; if (fncStorage.GetFont(null, fontInfos) != VSConstants.S_OK) return defaultFontSize; if (fontInfos[0].bPointSizeValid == 1) return FontUtils.FontSizeFromPointSize(fontInfos[0].wPointSize); return defaultFontSize; } finally { fncStorage.CloseCategory(); } } private uint GetRgbaColorValue(FontAndColorsResourceKey key) { const __FCSTORAGEFLAGS flags = __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS; fncStorage.OpenCategory(key.Category, (uint)flags); try { var itemInfos = new ColorableItemInfo[1]; if (fncStorage.GetItem(key.Name, itemInfos) != VSConstants.S_OK) return 0xFF000000; uint color; switch (key.KeyType) { case FontAndColorsResourceKeyType.ForegroundColor: case FontAndColorsResourceKeyType.ForegroundBrush: color = itemInfos[0].crForeground; break; case FontAndColorsResourceKeyType.BackgroundColor: case FontAndColorsResourceKeyType.BackgroundBrush: color = itemInfos[0].crBackground; break; default: color = 0; break; } color |= 0xFF000000; return color; } finally { fncStorage.CloseCategory(); } } private static bool IsBrushKeyType(FontAndColorsResourceKeyType keyType) { return keyType == FontAndColorsResourceKeyType.BackgroundBrush || keyType == FontAndColorsResourceKeyType.ForegroundBrush; } private object RealizeValue(FontAndColorsResourceKey key) { if (key.KeyType == FontAndColorsResourceKeyType.FontFamily) return GetFontFamily(key); if (key.KeyType == FontAndColorsResourceKeyType.FontSize) return GetFontSize(key); Color color = GetRgbaColorValue(key).ToColorFromRgba(); if (!IsBrushKeyType(key.KeyType)) return color; var brush = new SolidColorBrush(color); brush.Freeze(); return brush; } } }
35.263158
95
0.557143
[ "MIT" ]
gix/event-trace-kit
src/EventTraceKit.VsExtension/Resources/Styles/FontAndColorsResourceDictionary.cs
4,690
C#
using System; using UnityEngine; using SwrveUnity.Helpers; namespace SwrveUnity.Messaging { /// <summary> /// Used internally to render in-app message personalized text using Unity IMGUI. /// </summary> public class SwrveTextWidgetView : SwrveWidgetView, ISwrveButtonView { protected readonly SwrveWidget widget; protected readonly SwrveTextViewStyle textViewStyle; protected readonly SwrveMessageFormatCalibration calibration; private bool Pressed = false; /// <summary> /// Pointer bounds. /// </summary> public Rect PointerRect; // Visible for tests public GUIContent content; public GUIStyle style; public SwrveButton button; public bool isButton; public Vector2 scrollPosition = Vector2.zero; public Color backgroundColor; protected Color clickTintColor; public SwrveTextWidgetView(SwrveWidget widget, string resolvedText, SwrveInAppMessageConfig inAppConfig, SwrveTextViewStyle textViewStyle, SwrveMessageFormatCalibration calibration) { this.widget = widget; this.textViewStyle = textViewStyle; this.calibration = calibration; content = new GUIContent(resolvedText); style = new GUIStyle(); style.alignment = TextAnchor.MiddleCenter; style.normal.textColor = textViewStyle.TextForegroundColor; style.font = textViewStyle.TextFont; if (widget.IsMultiLine) { style.wordWrap = true; SetTextAlignment(); int relativeFontSize = SwrveHelper.CalibrateRelativeFontSizeToPlatform(calibration, textViewStyle.FontSize); style.fontSize = relativeFontSize; if (!widget.IsScrollable) { FitMultiLineSizeToImage(widget.Size.X, widget.Size.Y, relativeFontSize); } } backgroundColor = textViewStyle.TextBackgroundColor; clickTintColor = inAppConfig.ButtonClickTintColor; isButton = (widget is SwrveButton); if (isButton) { button = (SwrveButton)widget; } } public override string GetTexturePath() { if (isButton) { return this.button.Image; } else { return ((SwrveImage)widget).File; } } public override void SetTexture(Texture2D texture) { this.Texture = texture; if (Texture != null) { style.fontSize = SwrveHelper.GetTextSizeToFitImage(style, content.text, Texture.width, Texture.height); } } public void ProcessButtonDown(Vector3 mousePosition) { if (isButton && PointerRect.Contains(mousePosition)) { Pressed = true; } } public SwrveButtonClickResult ProcessButtonUp(Vector3 mousePosition, SwrveMessageTextTemplatingResolver templatingResolver) { SwrveButtonClickResult clickResult = null; if (isButton && PointerRect.Contains(mousePosition) && Pressed) { string resolvedAction = templatingResolver.ActionResolution[button]; clickResult = new SwrveButtonClickResult(button, resolvedAction); } Pressed = false; return clickResult; } private void FitMultiLineSizeToImage(int maxWidth, int maxHeight, int relativeFontSize) { int currentFontSize = relativeFontSize; float contentHeight = style.CalcHeight(content, maxWidth); if (contentHeight > maxHeight) { // due to a scaling issues with CalcHeight in Unity currentFontSize = 1; style.fontSize = currentFontSize; contentHeight = style.CalcHeight(content, maxWidth); while ((contentHeight < maxHeight && currentFontSize < 130)) { currentFontSize++; style.fontSize = currentFontSize; contentHeight = style.CalcHeight(content, maxWidth); } // remove one as we set it as it went over the loop style.fontSize = currentFontSize - 1; } } private void SetTextAlignment() { switch (textViewStyle.HorizontalAlignment) { case TextAlignment.Left: style.alignment = TextAnchor.UpperLeft; break; case TextAlignment.Center: style.alignment = TextAnchor.UpperCenter; break; case TextAlignment.Right: style.alignment = TextAnchor.UpperRight; break; default: style.alignment = TextAnchor.UpperLeft; break; } } public override void Render(float scale, int centerx, int centery, bool rotatedFormat) { if (Texture != null) { int textureWidth = Texture.width; int textureHeight = Texture.height; float computedSize = scale; Point centerPoint = widget.GetCenteredPosition(textureWidth, textureHeight, computedSize, scale); centerPoint.X += centerx; centerPoint.Y += centery; Rect.x = centerPoint.X; Rect.y = centerPoint.Y; Rect.width = textureWidth * computedSize; Rect.height = textureHeight * computedSize; if (isButton) { if (rotatedFormat) { // Rotate 90 degrees the hit area Point widgetCenter = button.GetCenter(textureWidth, textureHeight, computedSize); PointerRect.x = centerx - (widget.Position.Y * scale) + widgetCenter.Y; PointerRect.y = centery + (widget.Position.X * scale) + widgetCenter.X; PointerRect.width = Rect.height; PointerRect.height = Rect.width; } else { PointerRect = Rect; } } ImgGUI.color = (Pressed) ? backgroundColor * clickTintColor : backgroundColor; ImgGUI.DrawTexture(Rect, Texture2D.whiteTexture, ScaleMode.StretchToFill, true, 0.0f); ImgGUI.color = (Pressed) ? Color.white * clickTintColor : Color.white; ImgGUI.Label(Rect, content, style); } else if (widget.IsMultiLine) { int textureWidth = widget.Size.X; int textureHeight = widget.Size.Y; float computedSize = scale; Point centerPoint = widget.GetCenteredPosition(textureWidth, textureHeight, computedSize, scale); centerPoint.X += centerx; centerPoint.Y += centery; Rect.x = centerPoint.X; Rect.y = centerPoint.Y; Rect.width = textureWidth * computedSize; Rect.height = textureHeight * computedSize; ImgGUI.color = (Pressed) ? backgroundColor * clickTintColor : backgroundColor; ImgGUI.DrawTexture(Rect, Texture2D.whiteTexture, ScaleMode.StretchToFill, true, 0.0f); ImgGUI.color = (Pressed) ? Color.white * clickTintColor : Color.white; // calculate how high the content is after generation, if the content height is too large, make it scrollable float textHeight = style.CalcHeight(content, Rect.width); // we need to know the size of the text we're passing through so calculate the offset of the text for scrolling with the same style in mind float offset = style.CalcHeight(new GUIContent("I"), Rect.width); if (widget.IsScrollable && textHeight > Rect.height) { // Add padding to account for the scrollbar size RectOffset rectOffset = new RectOffset(0, 30, 0, 0); style.padding = rectOffset; scrollPosition = ImgGUI.ClickEventScrollView(Rect, scrollPosition, new Rect(Rect.x, Rect.y, Rect.width - offset, textHeight + offset), false, false); ImgGUI.Label(Rect, content, style); ImgGUI.EndScrollView(); } else { ImgGUI.Label(Rect, content, style); } } } // Visible for tests public SwrveButton GetButton() { return button; } } }
37.846473
189
0.548624
[ "Apache-2.0" ]
Swrve/swrve-unity-sdk
unity3d/Assets/Swrve/SwrveSDK/Messaging/Views/SwrveTextWidgetView.cs
9,121
C#
using HADotNet.Core; using HADotNet.Core.Clients; using NUnit.Framework; using System; using System.Threading.Tasks; namespace HADotNet.Core.Tests { public class ErrorLogTests { private Uri Instance { get; set; } private string ApiKey { get; set; } [SetUp] public void Setup() { Instance = new Uri(Environment.GetEnvironmentVariable("HADotNet:Tests:Instance")); ApiKey = Environment.GetEnvironmentVariable("HADotNet:Tests:ApiKey"); ClientFactory.Initialize(Instance, ApiKey); } [Test] public async Task ShouldRetrieveErrorLogList() { var client = ClientFactory.GetClient<ErrorLogClient>(); var log = await client.GetErrorLogEntries(); Assert.IsNotNull(log); Assert.AreNotEqual(0, log.LogEntries.Count); Assert.AreNotEqual(0, log.Errors.Count); Assert.AreNotEqual(0, log.Warnings.Count); Assert.AreEqual(7, log[7].Count); } } }
29.189189
95
0.599074
[ "Apache-2.0" ]
Devqon/HADotNet
HADotNet.Core.Tests/ErrorLogTests.cs
1,080
C#
using System.Collections.Generic; using System.Linq; using AonWeb.FluentHttp.Settings; namespace AonWeb.FluentHttp.Client { public class HttpClientBuilderFactory : IHttpClientBuilderFactory { public HttpClientBuilderFactory() :this(null) { } protected HttpClientBuilderFactory(IEnumerable<IBuilderConfiguration<IHttpClientBuilder>> configurations) { Configurations = (configurations ?? Enumerable.Empty<IBuilderConfiguration<IHttpClientBuilder>>()).ToList(); } public IList<IBuilderConfiguration<IHttpClientBuilder>> Configurations { get; } public virtual IHttpClientBuilder Create() { var builder = new HttpClientBuilder(new HttpClientSettings()); ApplyConfigurations(Configurations, builder); return builder; } protected static void ApplyConfigurations(IEnumerable<IBuilderConfiguration<IHttpClientBuilder>> configurations, IHttpClientBuilder builder) { if (configurations == null) return; foreach (var configuration in configurations) { configuration.Configure(builder); } } } }
31.538462
148
0.663415
[ "MIT" ]
andrewescutia/fluent-http
AonWeb.FluentHttp/Client/HttpClientBuilderFactory.cs
1,232
C#
using System; using System.Windows.Forms; namespace GemsLogger.Writers { /// <summary> /// Logs the output to a ListBox control. /// </summary> public class ListBoxWriter : ILogWriter { /// <summary> /// The list box control. /// </summary> private readonly ListBox _listbox; /// <summary> /// Adds a string to the list control. /// </summary> private void Append(string pMsg) { bool scrollBottom = (_listbox.SelectedIndex == -1); _listbox.Items.Add(pMsg); if (_listbox.Items.Count == 500) { _listbox.Items.RemoveAt(0); } if (scrollBottom) { _listbox.TopIndex = _listbox.Items.Count - 1; } int width = pMsg.Length * 7; if (_listbox.HorizontalExtent < width) { _listbox.HorizontalExtent = width; } } /// <summary> /// Closes the writer. /// </summary> void ILogWriter.Close() { } /// <summary> /// Opens the writer /// </summary> void ILogWriter.Open() { } /// <summary> /// Writes a line to the writer. /// </summary> void ILogWriter.Write(Logger.eLEVEL level, string prefix, string msg) { if (_listbox.InvokeRequired) { _listbox.BeginInvoke(new Action(()=>Append(msg))); } else { Append(msg); } } /// <summary> /// Constructor /// </summary> public ListBoxWriter(ListBox listBox) { _listbox = listBox; } } }
23.075949
77
0.456391
[ "MIT" ]
thinkingmedia/gems-logger
GemsLogger/Writers/ListBoxWriter.cs
1,825
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TreasureGuide.Entities { using System; public enum CacheItemType : int { FullReset = 0, Unit = 1, Stage = 2, Ship = 3 } }
27.681818
85
0.45977
[ "MIT" ]
NakamaNetwork/nakama.legacy
Source/TreasureGuide.Entities/CacheItemType.cs
609
C#
using LD44.Collections.Pool; using UnityEngine; namespace LD44.Effects { public class DestructablePiggyManager : MonoBehaviour { public GameObject DestructablePiggyPrefab; public int Capacity = 32; private GameObjectPool<DestructablePiggy> _pool; void Start() { _pool = new GameObjectPool<DestructablePiggy>(DestructablePiggyPrefab, Capacity); foreach(var item in _pool.InactiveItems) { item.Initiate(); } } public void Execute(Transform location, Material material) { var piggy = _pool.Pop(); piggy.Reset(); piggy.transform.position = location.position; piggy.transform.rotation = location.rotation; piggy.Explode(material); } void Update() { for(var i = 0; i < _pool.ActiveItems.Count; i++) { var item = _pool.ActiveItems[i]; if(item.Dead) { _pool.Push(item); i--; } } } } }
26.204545
93
0.516045
[ "MIT" ]
eriksk/LD44
Assets/_Project/Scripts/Effects/DestructablePiggyManager.cs
1,153
C#
using System; namespace Machine.Specifications.Runner.ReSharper.Tasks { [Serializable] public class MspecBehaviorSpecificationRemoteTask : MspecRemoteTask { public MspecBehaviorSpecificationRemoteTask(string testId, string? ignoreReason, bool runAllChildren, bool runExplicitly) : base(testId, ignoreReason, runAllChildren, runExplicitly) { } public MspecBehaviorSpecificationRemoteTask(string contextTypeName, string behaviorFieldName, string specificationFieldName, string? ignoreReason) : base($"{contextTypeName}::{specificationFieldName}", ignoreReason) { ContextTypeName = contextTypeName; BehaviorFieldName = behaviorFieldName; SpecificationFieldName = specificationFieldName; } public string? ContextTypeName { get; set; } public string? BehaviorFieldName { get; set; } public string? SpecificationFieldName { get; set; } public static MspecBehaviorSpecificationRemoteTask ToClient(string testId, string? ignoreReason, bool runAllChildren, bool runExplicitly) { return new(testId, ignoreReason, runAllChildren, runExplicitly); } public static MspecBehaviorSpecificationRemoteTask ToServer(string contextTypeName, string behaviorFieldName, string specificationFieldName, string? ignoreReason) { return new(contextTypeName, behaviorFieldName, specificationFieldName, ignoreReason); } } }
40.052632
170
0.714849
[ "MIT" ]
machine/machine.specifications.runner.resharper
src/Machine.Specifications.Runner.ReSharper.Tasks/MspecBehaviorSpecificationRemoteTask.cs
1,524
C#
using System; using System.Data.SqlClient; public partial class DeleteRoute : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string sessionID = Request.QueryString["sessionID"]; string phoneNumber = Request.QueryString["phoneNumber"]; // our helper class to get data DbXmlReader reader = new DbXmlReader(); Response.AppendHeader("Content-Type", "text/xml"); // actually we are getting a response back here, but the result will be a deleted route on the webpage Response.Write(reader.getXmlString("prcDeleteRoute", new SqlParameter("@sessionID", sessionID), new SqlParameter("@phoneNumber", phoneNumber))); } }
31.708333
111
0.654402
[ "MIT" ]
Xcoderoid/GpsTracker
servers/dotNet/DeleteRoute.aspx.cs
761
C#
// // ResolveStep.cs // // Author: // Jb Evain (jbevain@gmail.com) // // (C) 2006 Jb Evain // // 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.Collections.Generic; namespace Mono.Linker.Steps { public abstract class ResolveStep : BaseStep { readonly List<string> _unResolved; protected ResolveStep () { _unResolved = new List<string> (); } public bool AllMarkerResolved { get { return _unResolved.Count == 0; } } public string [] GetUnresolvedMarkers () { return _unResolved.ToArray (); } protected void AddUnresolveMarker (string signature) { _unResolved.Add (signature); } } }
28.827586
73
0.730263
[ "MIT" ]
GrabYourPitchforks/linker
src/linker/Linker.Steps/ResolveStep.cs
1,674
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("RuleBasedAdaptationAsset")] [assembly: AssemblyDescription("The Player-centric rule-and-pattern-based adaptation asset uses metrics of player's performance, emotional status and/or playing style for realization of dynamical adaptation of various game features such as adaptation of player-driven game tasks and/or game assistance, dynamic adjustment of task difficulty, and/or adjustment of properties of audiovisual content and effects.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Sofia University")] [assembly: AssemblyProduct("RuleBasedAdaptationAsset")] [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 #if PORTABLE // #else [assembly: Guid("263e0137-6d05-4fee-b807-a28660319e58")] #endif // 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")]
44.95122
412
0.768313
[ "Apache-2.0" ]
ddessy/PlayerCentricRuleBasedAdaptation
PlayerCentricRuleBasedAdaptationSource/RuleBasedAdaptation/Properties/AssemblyInfo.cs
1,846
C#
using Microsoft.EntityFrameworkCore; using GradeBook.Models; namespace GradeBook.DAL { public class GradebookContext : DbContext { public GradebookContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Account>() .HasIndex(i => i.Login) .IsUnique(); modelBuilder.Entity<Teacher>() .HasOne(i => i.Account) .WithOne(i => i.Teacher) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<Student>() .HasOne(i => i.Account) .WithOne(i => i.Student) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<Student>() .HasOne(i => i.Group) .WithMany(i => i.Students) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<GradebookTeacher>() .HasKey(i => new { i.GradebookRefId, i.TeacherRefId }); modelBuilder.Entity<GradebookTeacher>() .HasOne(i => i.Gradebook) .WithMany(i => i.GradebookTeachers) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<GradebookTeacher>() .HasOne(i => i.Teacher) .WithMany(i => i.GradebookTeachers) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<SemesterSubject>() .HasKey(i => new { i.SemesterRefId, i.SubjectRefId }); modelBuilder.Entity<SemesterSubject>() .HasOne(i => i.Semester) .WithMany(i => i.SemesterSubjects) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<SemesterSubject>() .HasOne(i => i.Subject) .WithMany(i => i.Semesters) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<SemesterSubject>() .HasOne(i => i.AssestmentType) .WithMany(i => i.Semesters) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<FinalGrade>() .HasIndex(i => new {i.GradebookRefId, i.StudentRefId}) .IsUnique(); modelBuilder.Entity<FinalGrade>() .HasOne(i => i.Gradebook) .WithMany(i => i.FinalGrades) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<FinalGrade>() .HasOne(i => i.Student) .WithMany(i => i.FinalGrades) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<FinalGrade>() .HasOne(i => i.Teacher) .WithMany(i => i.FinalGrades) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<Grade>() .HasOne(i => i.Gradebook) .WithMany(i => i.Grades) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<Grade>() .HasOne(i => i.Student) .WithMany(i => i.Grades) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<Grade>() .HasOne(i => i.Teacher) .WithMany(i => i.Grades) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<Gradebook>() .HasIndex(i => new {i.SemesterRefId, i.SubjectRefId}) .IsUnique(); modelBuilder.Entity<GradebookTeacher>() .HasIndex(i => new {i.GradebookRefId, i.TeacherRefId}) .IsUnique(); modelBuilder.Entity<GradebookTeacher>() .HasOne(i => i.Gradebook) .WithMany(i => i.GradebookTeachers) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<GradebookTeacher>() .HasOne(i => i.Teacher) .WithMany(i => i.GradebookTeachers) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<Group>() .HasIndex(i => i.Code) .IsUnique(); modelBuilder.Entity<Group>() .HasOne(i => i.Speciality) .WithMany(i => i.Groups) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<Semester>() .HasIndex(i => new {i.GroupRefId, i.CourseNumber, i.SemesterNumber}) .IsUnique(); modelBuilder.Entity<Semester>() .HasOne(i => i.Group) .WithMany(i => i.Semesters) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<SemesterSubject>() .HasIndex(i => new {i.SemesterRefId, i.SubjectRefId}) .IsUnique(); modelBuilder.Entity<SemesterSubject>() .HasOne(i => i.AssestmentType) .WithMany(i => i.Semesters) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<SemesterSubject>() .HasOne(i => i.Semester) .WithMany(i => i.SemesterSubjects) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<SemesterSubject>() .HasOne(i => i.Subject) .WithMany(i => i.Semesters) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<Specialty>() .HasIndex(i => i.Code) .IsUnique(); modelBuilder.Entity<Specialty>() .HasIndex(i => i.Name) .IsUnique(); modelBuilder.Entity<Subject>() .HasIndex(i => i.Name) .IsUnique(); modelBuilder.Entity<Gradebook>() .HasOne(i => i.Semester) .WithMany(i => i.Gradebooks) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<Gradebook>() .HasOne(i => i.SemesterSubject) .WithOne(i => i.Gradebook) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<Gradebook>() .HasOne(i => i.Subject) .WithMany(i => i.Gradebooks) .OnDelete(DeleteBehavior.Cascade); } } }
39.773006
84
0.509641
[ "MIT" ]
DenHaydash/gradebook-svc
GradeBook.DAL/GradebookContext.cs
6,485
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using RazorEngine.Configuration; using RazorEngine.Templating; using RazorEngine.Text; namespace Grammophone.TemplateRendering.RazorEngine { /// <summary> /// Implements the <see cref="IRenderProvider"/> using the RazorEngine library. /// It is thread-save as required by the interface contract. /// Thus it should be configured for a singleton lifetime. /// </summary> public class RazorEngineRenderProvider : IRenderProvider { #region Private fields /// <summary> /// The RazorEngine service. /// </summary> private IRazorEngineService razorEngineService; #endregion #region Construction /// <summary> /// Create with HTML escaping rules. /// </summary> /// <param name="templateFolderRoots"> /// A collection of folder roots to search for Razor templates. /// These can be relative paths, which will be transformed to absolute /// based on the application's root. /// </param> public RazorEngineRenderProvider(string[] templateFolderRoots) : this(templateFolderRoots, EncodingMode.Html) { } /// <summary> /// Create with HTML escaping rules. /// </summary> /// <param name="templateFolderRoot"> /// A folder root to search for Razor templates. /// It can be relative a path, which will be transformed to absolute /// based on the application's root. /// </param> public RazorEngineRenderProvider(string templateFolderRoot) : this(templateFolderRoot, EncodingMode.Html) { } /// <summary> /// Create. /// </summary> /// <param name="templateFolderRoots"> /// A collection of folder roots to search for Razor templates. /// These can be relative paths, which will be transformed to absolute /// based on the application's root. /// </param> /// <param name="encodingMode"> /// The escaping to use for strings generated from templates. /// </param> public RazorEngineRenderProvider(string[] templateFolderRoots, EncodingMode encodingMode) { if (templateFolderRoots == null) throw new ArgumentNullException(nameof(templateFolderRoots)); Initialize(templateFolderRoots.SelectMany(f => NormalizePath(f)), encodingMode); } /// <summary> /// Create. /// </summary> /// <param name="templateFolderRoot"> /// A folder root to search for Razor templates. /// It can be relative a path, which will be transformed to absolute /// based on the application's root. /// </param> /// <param name="encodingMode"> /// The escaping to use for strings generated from templates. /// </param> public RazorEngineRenderProvider(string templateFolderRoot, EncodingMode encodingMode) { if (templateFolderRoot == null) throw new ArgumentNullException(nameof(templateFolderRoot)); Initialize(NormalizePath(templateFolderRoot), encodingMode); } #endregion #region Public properties /// <summary> /// The list of folders to search for Razor templates. /// </summary> /// <remarks> /// These folder names are always absolute. If relative folders were passed in /// the contstructor, these are converted to absolute, starting from the /// application's root. /// </remarks> public IEnumerable<string> TemplateFolderRoots { get; private set; } #endregion #region public methods /// <summary> /// Cleanup the engine and attempt to remove temporary files. /// </summary> public void Dispose() { this.razorEngineService.Dispose(); } /// <summary> /// Render a template. /// </summary> /// <param name="templateKey"> /// The relative to <see cref="TemplateFolderRoots"/> filename /// of the Razor template, preferably without the .cshtml or .vbhtml /// suffix. /// </param> /// <param name="textWriter"> /// The writer used for output. /// </param> /// <param name="dynamicProperties"> /// The items in the dictionary become properties of the ViewBag. /// </param> public void Render(string templateKey, TextWriter textWriter, IDictionary<string, object> dynamicProperties) { var engineKey = this.razorEngineService.GetKey(templateKey); this.razorEngineService.RunCompile( engineKey, textWriter, viewBag: new DynamicViewBag(dynamicProperties)); } /// <summary> /// Render a template using a strong-type <paramref name="model"/>. /// </summary> /// <typeparam name="M">The type of the model.</typeparam> /// <param name="templateKey"> /// The relative to <see cref="TemplateFolderRoots"/> filename /// of the Razor template, preferably without the .cshtml or .vbhtml /// suffix. /// </param> /// <param name="textWriter"> /// The writer used for output. /// </param> /// <param name="model">The object to be set as Model.</param> /// <param name="dynamicProperties"> /// If present, the items in the dictionary become properties of the ViewBag. /// </param> public void Render<M>(string templateKey, TextWriter textWriter, M model, IDictionary<string, object> dynamicProperties = null) { var engineKey = this.razorEngineService.GetKey(templateKey); this.razorEngineService.RunCompile( engineKey, textWriter, modelType: typeof(M), model: model, viewBag: dynamicProperties != null ? new DynamicViewBag(dynamicProperties) : null); } #endregion #region Private methods /// <summary> /// If <paramref name="pathName"/> is a relative one, it converts it /// to absolute by combining it with the application's root or bin directory /// whichever are available. /// </summary> /// <param name="pathName">The path name.</param> /// <returns>Returns the normalized path names.</returns> private static IEnumerable<string> NormalizePath(string pathName) { // Is this an absolute or a relative path? if (!Path.IsPathRooted(pathName)) { // If not, translate it according to the AppDomain's base and bin folders. if (AppDomain.CurrentDomain.RelativeSearchPath != null && AppDomain.CurrentDomain.RelativeSearchPath != AppDomain.CurrentDomain.BaseDirectory) { yield return Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath, pathName); } yield return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, pathName); } else { yield return pathName; } } /// <summary> /// Finishes constructor work. /// </summary> private void Initialize(IEnumerable<string> templateFolderRoots, EncodingMode encodingMode) { if (templateFolderRoots == null) throw new ArgumentNullException(nameof(templateFolderRoots)); this.TemplateFolderRoots = templateFolderRoots; var configuration = new TemplateServiceConfiguration() { #if DEBUG Debug = true, #endif TemplateManager = new ResolvePathTemplateManager(templateFolderRoots), }; switch (encodingMode) { case EncodingMode.RawText: configuration.EncodedStringFactory = new RawStringFactory(); break; default: configuration.EncodedStringFactory = new HtmlEncodedStringFactory(); break; } this.razorEngineService = RazorEngineService.Create(configuration); } #endregion } }
30.278481
129
0.703317
[ "MIT" ]
grammophone/Grammophone.TemplateRendering.RazorEngine
RazorEngineRenderProvider.cs
7,178
C#
// ============================================================================================================== // Microsoft patterns & practices // CQRS Journey project // ============================================================================================================== // ©2012 Microsoft. All rights reserved. Certain content used with permission from contributors // http://go.microsoft.com/fwlink/p/?LinkID=258575 // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed under the License is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. // ============================================================================================================== namespace Infrastructure.Sql.Messaging.Implementation { using System; using System.Data; using System.Data.Entity.Infrastructure; using System.Data.SqlClient; using System.Globalization; using System.Threading; using System.Threading.Tasks; public class MessageReceiver : IMessageReceiver, IDisposable { private readonly IDbConnectionFactory connectionFactory; private readonly string name; private readonly string readQuery; private readonly string deleteQuery; private readonly TimeSpan pollDelay; private readonly object lockObject = new object(); private CancellationTokenSource cancellationSource; public MessageReceiver(IDbConnectionFactory connectionFactory, string name, string tableName) : this(connectionFactory, name, tableName, TimeSpan.FromMilliseconds(100)) { } public MessageReceiver(IDbConnectionFactory connectionFactory, string name, string tableName, TimeSpan pollDelay) { this.connectionFactory = connectionFactory; this.name = name; this.pollDelay = pollDelay; this.readQuery = string.Format( CultureInfo.InvariantCulture, @"SELECT TOP (1) {0}.[Id] AS [Id], {0}.[Body] AS [Body], {0}.[DeliveryDate] AS [DeliveryDate], {0}.[CorrelationId] AS [CorrelationId] FROM {0} WITH (UPDLOCK, READPAST) WHERE ({0}.[DeliveryDate] IS NULL) OR ({0}.[DeliveryDate] <= @CurrentDate) ORDER BY {0}.[Id] ASC", tableName); this.deleteQuery = string.Format( CultureInfo.InvariantCulture, "DELETE FROM {0} WHERE Id = @Id", tableName); } public event EventHandler<MessageReceivedEventArgs> MessageReceived = (sender, args) => { }; public void Start() { lock (this.lockObject) { if (this.cancellationSource == null) { this.cancellationSource = new CancellationTokenSource(); Task.Factory.StartNew( () => this.ReceiveMessages(this.cancellationSource.Token), this.cancellationSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Current); } } } public void Stop() { lock (this.lockObject) { using (this.cancellationSource) { if (this.cancellationSource != null) { this.cancellationSource.Cancel(); this.cancellationSource = null; } } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { this.Stop(); } ~MessageReceiver() { Dispose(false); } /// <summary> /// Receives the messages in an endless loop. /// </summary> private void ReceiveMessages(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { if (!this.ReceiveMessage()) { Thread.Sleep(this.pollDelay); } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "Does not contain user input.")] protected bool ReceiveMessage() { using (var connection = this.connectionFactory.CreateConnection(this.name)) { var currentDate = GetCurrentDate(); connection.Open(); using (var transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)) { try { long messageId = -1; Message message = null; using (var command = connection.CreateCommand()) { command.Transaction = transaction; command.CommandType = CommandType.Text; command.CommandText = this.readQuery; ((SqlCommand)command).Parameters.Add("@CurrentDate", SqlDbType.DateTime).Value = currentDate; using (var reader = command.ExecuteReader()) { if (!reader.Read()) { return false; } var body = (string)reader["Body"]; var deliveryDateValue = reader["DeliveryDate"]; var deliveryDate = deliveryDateValue == DBNull.Value ? (DateTime?)null : new DateTime?((DateTime)deliveryDateValue); var correlationIdValue = reader["CorrelationId"]; var correlationId = (string)(correlationIdValue == DBNull.Value ? null : correlationIdValue); message = new Message(body, deliveryDate, correlationId); messageId = (long)reader["Id"]; } } this.MessageReceived(this, new MessageReceivedEventArgs(message)); using (var command = connection.CreateCommand()) { command.Transaction = transaction; command.CommandType = CommandType.Text; command.CommandText = this.deleteQuery; ((SqlCommand)command).Parameters.Add("@Id", SqlDbType.BigInt).Value = messageId; command.ExecuteNonQuery(); } transaction.Commit(); } catch (Exception) { try { transaction.Rollback(); } catch { } throw; } } } return true; } protected virtual DateTime GetCurrentDate() { return DateTime.UtcNow; } } }
39.365854
185
0.481908
[ "Apache-2.0" ]
wayne-o/delete-me
source/Infrastructure/Sql/Infrastructure.Sql/Messaging/Implementation/MessageReceiver.cs
8,073
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("UnitTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UnitTests")] [assembly: AssemblyCopyright("Copyright © 2014")] [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("ae428994-8b4b-4f52-8e39-14d90ab1be52")] // 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.594595
84
0.744069
[ "MIT" ]
stallboy/ReView
UnitTests/Properties/AssemblyInfo.cs
1,394
C#
/* http://www.cgsoso.com/forum-211-1.html CG搜搜 Unity3d 每日Unity3d插件免费更新 更有VIP资源! CGSOSO 主打游戏开发,影视设计等CG资源素材。 插件如若商用,请务必官网购买! daily assets update for try. U should buy the asset from home store if u use it in your project! */ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Paddings; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Macs { /** * DES based CBC Block Cipher MAC according to ISO9797, algorithm 3 (ANSI X9.19 Retail MAC) * * This could as well be derived from CBCBlockCipherMac, but then the property mac in the base * class must be changed to protected */ public class ISO9797Alg3Mac : IMac { private byte[] mac; private byte[] buf; private int bufOff; private IBlockCipher cipher; private IBlockCipherPadding padding; private int macSize; private KeyParameter lastKey2; private KeyParameter lastKey3; /** * create a Retail-MAC based on a CBC block cipher. This will produce an * authentication code of the length of the block size of the cipher. * * @param cipher the cipher to be used as the basis of the MAC generation. This must * be DESEngine. */ public ISO9797Alg3Mac( IBlockCipher cipher) : this(cipher, cipher.GetBlockSize() * 8, null) { } /** * create a Retail-MAC based on a CBC block cipher. This will produce an * authentication code of the length of the block size of the cipher. * * @param cipher the cipher to be used as the basis of the MAC generation. * @param padding the padding to be used to complete the last block. */ public ISO9797Alg3Mac( IBlockCipher cipher, IBlockCipherPadding padding) : this(cipher, cipher.GetBlockSize() * 8, padding) { } /** * create a Retail-MAC based on a block cipher with the size of the * MAC been given in bits. This class uses single DES CBC mode as the basis for the * MAC generation. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * </p> * @param cipher the cipher to be used as the basis of the MAC generation. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. */ public ISO9797Alg3Mac( IBlockCipher cipher, int macSizeInBits) : this(cipher, macSizeInBits, null) { } /** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. This class uses single DES CBC mode as the basis for the * MAC generation. The final block is decrypted and then encrypted using the * middle and right part of the key. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * </p> * @param cipher the cipher to be used as the basis of the MAC generation. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. * @param padding the padding to be used to complete the last block. */ public ISO9797Alg3Mac( IBlockCipher cipher, int macSizeInBits, IBlockCipherPadding padding) { if ((macSizeInBits % 8) != 0) throw new ArgumentException("MAC size must be multiple of 8"); if (!(cipher is DesEngine)) throw new ArgumentException("cipher must be instance of DesEngine"); this.cipher = new CbcBlockCipher(cipher); this.padding = padding; this.macSize = macSizeInBits / 8; mac = new byte[cipher.GetBlockSize()]; buf = new byte[cipher.GetBlockSize()]; bufOff = 0; } public string AlgorithmName { get { return "ISO9797Alg3"; } } public void Init( ICipherParameters parameters) { Reset(); if (!(parameters is KeyParameter || parameters is ParametersWithIV)) throw new ArgumentException("parameters must be an instance of KeyParameter or ParametersWithIV"); // KeyParameter must contain a double or triple length DES key, // however the underlying cipher is a single DES. The middle and // right key are used only in the final step. KeyParameter kp; if (parameters is KeyParameter) { kp = (KeyParameter)parameters; } else { kp = (KeyParameter)((ParametersWithIV)parameters).Parameters; } KeyParameter key1; byte[] keyvalue = kp.GetKey(); if (keyvalue.Length == 16) { // Double length DES key key1 = new KeyParameter(keyvalue, 0, 8); this.lastKey2 = new KeyParameter(keyvalue, 8, 8); this.lastKey3 = key1; } else if (keyvalue.Length == 24) { // Triple length DES key key1 = new KeyParameter(keyvalue, 0, 8); this.lastKey2 = new KeyParameter(keyvalue, 8, 8); this.lastKey3 = new KeyParameter(keyvalue, 16, 8); } else { throw new ArgumentException("Key must be either 112 or 168 bit long"); } if (parameters is ParametersWithIV) { cipher.Init(true, new ParametersWithIV(key1, ((ParametersWithIV)parameters).GetIV())); } else { cipher.Init(true, key1); } } public int GetMacSize() { return macSize; } public void Update( byte input) { if (bufOff == buf.Length) { cipher.ProcessBlock(buf, 0, mac, 0); bufOff = 0; } buf[bufOff++] = input; } public void BlockUpdate( byte[] input, int inOff, int len) { if (len < 0) throw new ArgumentException("Can't have a negative input length!"); int blockSize = cipher.GetBlockSize(); int resultLen = 0; int gapLen = blockSize - bufOff; if (len > gapLen) { Array.Copy(input, inOff, buf, bufOff, gapLen); resultLen += cipher.ProcessBlock(buf, 0, mac, 0); bufOff = 0; len -= gapLen; inOff += gapLen; while (len > blockSize) { resultLen += cipher.ProcessBlock(input, inOff, mac, 0); len -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, buf, bufOff, len); bufOff += len; } public int DoFinal( byte[] output, int outOff) { int blockSize = cipher.GetBlockSize(); if (padding == null) { // pad with zeroes while (bufOff < blockSize) { buf[bufOff++] = 0; } } else { if (bufOff == blockSize) { cipher.ProcessBlock(buf, 0, mac, 0); bufOff = 0; } padding.AddPadding(buf, bufOff); } cipher.ProcessBlock(buf, 0, mac, 0); // Added to code from base class DesEngine deseng = new DesEngine(); deseng.Init(false, this.lastKey2); deseng.ProcessBlock(mac, 0, mac, 0); deseng.Init(true, this.lastKey3); deseng.ProcessBlock(mac, 0, mac, 0); // **** Array.Copy(mac, 0, output, outOff, macSize); Reset(); return macSize; } /** * Reset the mac generator. */ public void Reset() { Array.Clear(buf, 0, buf.Length); bufOff = 0; // reset the underlying cipher. cipher.Reset(); } } } #endif
24.843537
102
0.670044
[ "MIT" ]
zhoumingliang/test-git-subtree
Assets/RotateMe/Scripts/Best HTTP (Pro)/BestHTTP/SecureProtocol/crypto/macs/ISO9797Alg3Mac.cs
7,398
C#
using System.Threading; namespace GitHub.Unity { class GitBranchDeleteTask : ProcessTask<string> { private readonly string arguments; public GitBranchDeleteTask(string branch, bool deleteUnmerged, CancellationToken token, IOutputProcessor<string> processor = null) : base(token, processor ?? new SimpleOutputProcessor()) { Guard.ArgumentNotNullOrWhiteSpace(branch, "branch"); arguments = !deleteUnmerged ? $"branch -d {branch}" : $"branch -D {branch}"; } public override string Name { get { return "git branch"; } } public override string ProcessArguments { get { return arguments; } } public override TaskAffinity Affinity { get { return TaskAffinity.Exclusive; } } } }
35.909091
88
0.655696
[ "MIT" ]
CapnRat/github-for-unity
src/GitHub.Api/Git/Tasks/GitBranchDeleteTask.cs
790
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace wolftrack.Models { public class Pack { public int PackId { get; set; } public string Name{ get; set; } public List<Wolf> Wolves { get; set; } public Pack() { Wolves = new List<Wolf>(); } } }
19.578947
46
0.577957
[ "MIT" ]
MrSpyretos/Wolftrack
wolftrack/wolftrack/Models/Pack.cs
374
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEditor; using UnityEngine; namespace FMODUnity { [CustomEditor(typeof(StudioParameterTrigger))] public class StudioParameterTriggerEditor : Editor { StudioEventEmitter targetEmitter; SerializedProperty emitters; SerializedProperty trigger; SerializedProperty tag; bool[] expanded; void OnEnable() { emitters = serializedObject.FindProperty("Emitters"); trigger = serializedObject.FindProperty("TriggerEvent"); tag = serializedObject.FindProperty("CollisionTag"); targetEmitter = null; for (int i = 0; i < emitters.arraySize; i++) { targetEmitter = emitters.GetArrayElementAtIndex(i).FindPropertyRelative("Target").objectReferenceValue as StudioEventEmitter; if (targetEmitter != null) { expanded = new bool[targetEmitter.GetComponents<StudioEventEmitter>().Length]; break; } } } public override void OnInspectorGUI() { var newTargetEmitter = EditorGUILayout.ObjectField("Target", targetEmitter, typeof(StudioEventEmitter), true) as StudioEventEmitter; if (newTargetEmitter != targetEmitter) { emitters.ClearArray(); targetEmitter = newTargetEmitter; if (targetEmitter == null) { serializedObject.ApplyModifiedProperties(); return; } List<StudioEventEmitter> newEmitters = new List<StudioEventEmitter>(); targetEmitter.GetComponents<StudioEventEmitter>(newEmitters); expanded = new bool[newEmitters.Count]; foreach (var emitter in newEmitters) { emitters.InsertArrayElementAtIndex(0); emitters.GetArrayElementAtIndex(0).FindPropertyRelative("Target").objectReferenceValue = emitter; } } if (targetEmitter == null) { return; } EditorGUILayout.PropertyField(trigger, new GUIContent("Trigger")); if (trigger.enumValueIndex >= 3 && trigger.enumValueIndex <= 6) { tag.stringValue = EditorGUILayout.TagField("Collision Tag", tag.stringValue); } var localEmitters = new List<StudioEventEmitter>(); targetEmitter.GetComponents<StudioEventEmitter>(localEmitters); int emitterIndex = 0; foreach (var emitter in localEmitters) { SerializedProperty emitterProperty = null; for(int i = 0; i < emitters.arraySize; i++) { if (emitters.GetArrayElementAtIndex(i).FindPropertyRelative("Target").objectReferenceValue == emitter) { emitterProperty = emitters.GetArrayElementAtIndex(i); break; } } // New emitter component added to game object since we last looked if (emitterProperty == null) { emitters.InsertArrayElementAtIndex(0); emitterProperty = emitters.GetArrayElementAtIndex(0); emitterProperty.FindPropertyRelative("Target").objectReferenceValue = emitter; } if (!String.IsNullOrEmpty(emitter.Event)) { expanded[emitterIndex] = EditorGUILayout.Foldout(expanded[emitterIndex], emitter.Event); if (expanded[emitterIndex]) { var eventRef = EventManager.EventFromPath(emitter.Event); foreach (var paramRef in eventRef.Parameters) { bool set = false; int index = -1; for (int i = 0; i < emitterProperty.FindPropertyRelative("Params").arraySize; i++) { if (emitterProperty.FindPropertyRelative("Params").GetArrayElementAtIndex(i).FindPropertyRelative("Name").stringValue == paramRef.Name) { index = i; set = true; break; } } EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(paramRef.Name); bool newSet = GUILayout.Toggle(set, ""); if (!set && newSet) { index = 0; emitterProperty.FindPropertyRelative("Params").InsertArrayElementAtIndex(0); emitterProperty.FindPropertyRelative("Params").GetArrayElementAtIndex(0).FindPropertyRelative("Name").stringValue = paramRef.Name; emitterProperty.FindPropertyRelative("Params").GetArrayElementAtIndex(0).FindPropertyRelative("Value").floatValue = 0; } if (set && !newSet) { emitterProperty.FindPropertyRelative("Params").DeleteArrayElementAtIndex(index); } set = newSet; EditorGUI.BeginDisabledGroup(!set); if (set) { var valueProperty = emitterProperty.FindPropertyRelative("Params").GetArrayElementAtIndex(index).FindPropertyRelative("Value"); valueProperty.floatValue = EditorGUILayout.Slider(valueProperty.floatValue, paramRef.Min, paramRef.Max); } else { EditorGUILayout.Slider(0, paramRef.Min, paramRef.Max); } EditorGUI.EndDisabledGroup(); EditorGUILayout.EndHorizontal(); } } } emitterIndex++; } serializedObject.ApplyModifiedProperties(); } } }
43.826923
168
0.488372
[ "MIT" ]
Canvastudio/Prometheus
Code/Prometheus/Assets/Plugins/Editor/FMOD/StudioParameterTriggerEditor.cs
6,839
C#
namespace midorg { public class Address { public string Street { get; set; } public string Building { get; set; } public string Floor { get; set; } public int FloorNumber { get; set; } public GpsLocation GpsLocation { get; set; } public string City { get; set; } public string Country { get; set; } public string State { get; set; } public string PostalCode { get; set; } } }
20.347826
52
0.564103
[ "Apache-2.0" ]
dynamicdeploy/mid
mid/midorg/Address.cs
470
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ace.Application { public interface IAceSessionAppService { IAceSession AceSession { get; set; } } }
18.642857
45
0.693487
[ "Apache-2.0" ]
a574676848/Ace
src/DotNetCore/Ace/Application/IAceSessionAppService.cs
263
C#
using System; namespace SFA.DAS.VacancyServices.Wage { public struct NationalMinimumWageRates { internal NationalMinimumWageRates(DateTime validFrom, DateTime validTo, decimal apprenticeMinimumWage, decimal under18NationalMinimumWage, decimal between18AndUnder21NationalMinimumWage, decimal between21AndUnder25NationalMinimumWage, decimal over25NationalMinimumWage) { ValidFrom = validFrom; ValidTo = validTo; ApprenticeMinimumWage = apprenticeMinimumWage; Under18NationalMinimumWage = under18NationalMinimumWage; Between18AndUnder21NationalMinimumWage = between18AndUnder21NationalMinimumWage; Between21AndUnder25NationalMinimumWage = between21AndUnder25NationalMinimumWage; Over25NationalMinimumWage = over25NationalMinimumWage; } public DateTime ValidFrom { get; } public DateTime ValidTo { get; } public decimal ApprenticeMinimumWage { get; } public decimal Under18NationalMinimumWage { get; } public decimal Between18AndUnder21NationalMinimumWage { get; } public decimal Between21AndUnder25NationalMinimumWage { get; } public decimal Over25NationalMinimumWage { get; } } }
48.384615
277
0.742448
[ "MIT" ]
SkillsFundingAgency/das-shared-packages
VacancyServices.Wage/SFA.DAS.VacancyServices.Wage/NationalMinimumWageRates.cs
1,260
C#
using System; using System.Collections.Generic; using Android.Runtime; using Java.Interop; namespace Com.Payment.Paymentsdk.Apms.Model { // Metadata.xml XPath class reference: path="/api/package[@name='com.payment.paymentsdk.apms.model']/class[@name='ApmsBodyBuilder']" [global::Android.Runtime.Register ("com/payment/paymentsdk/apms/model/ApmsBodyBuilder", DoNotGenerateAcw=true)] public sealed partial class ApmsBodyBuilder : global::Java.Lang.Object { static readonly JniPeerMembers _members = new XAPeerMembers ("com/payment/paymentsdk/apms/model/ApmsBodyBuilder", typeof (ApmsBodyBuilder)); internal static IntPtr class_ref { get { return _members.JniPeerType.PeerReference.Handle; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] public override global::Java.Interop.JniPeerMembers JniPeerMembers { get { return _members; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] protected override IntPtr ThresholdClass { get { return _members.JniPeerType.PeerReference.Handle; } } [global::System.Diagnostics.DebuggerBrowsable (global::System.Diagnostics.DebuggerBrowsableState.Never)] [global::System.ComponentModel.EditorBrowsable (global::System.ComponentModel.EditorBrowsableState.Never)] protected override global::System.Type ThresholdType { get { return _members.ManagedPeerType; } } internal ApmsBodyBuilder (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) { } // Metadata.xml XPath constructor reference: path="/api/package[@name='com.payment.paymentsdk.apms.model']/class[@name='ApmsBodyBuilder']/constructor[@name='ApmsBodyBuilder' and count(parameter)=1 and parameter[1][@type='com.payment.paymentsdk.integrationmodels.PaymentSdkConfigurationDetails']]" [Register (".ctor", "(Lcom/payment/paymentsdk/integrationmodels/PaymentSdkConfigurationDetails;)V", "")] public unsafe ApmsBodyBuilder (global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkConfigurationDetails ptConfigData) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { const string __id = "(Lcom/payment/paymentsdk/integrationmodels/PaymentSdkConfigurationDetails;)V"; if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue ((ptConfigData == null) ? IntPtr.Zero : ((global::Java.Lang.Object) ptConfigData).Handle); var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), __args); SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef); _members.InstanceMethods.FinishCreateInstance (__id, this, __args); } finally { global::System.GC.KeepAlive (ptConfigData); } } // Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.apms.model']/class[@name='ApmsBodyBuilder']/method[@name='build' and count(parameter)=0]" [Register ("build", "()Lcom/payment/paymentsdk/sharedclasses/model/request/TransactionRequestBody;", "")] public unsafe global::Com.Payment.Paymentsdk.Sharedclasses.Model.Request.TransactionRequestBody Build () { const string __id = "build.()Lcom/payment/paymentsdk/sharedclasses/model/request/TransactionRequestBody;"; try { var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null); return global::Java.Lang.Object.GetObject<global::Com.Payment.Paymentsdk.Sharedclasses.Model.Request.TransactionRequestBody> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { } } // Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.apms.model']/class[@name='ApmsBodyBuilder']/method[@name='setApms' and count(parameter)=1 and parameter[1][@type='java.util.List&lt;? extends com.payment.paymentsdk.integrationmodels.PaymentSdkApms&gt;']]" [Register ("setApms", "(Ljava/util/List;)Lcom/payment/paymentsdk/apms/model/ApmsBodyBuilder;", "")] public unsafe global::Com.Payment.Paymentsdk.Apms.Model.ApmsBodyBuilder SetApms (global::System.Collections.Generic.IList<global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkApms> apms) { const string __id = "setApms.(Ljava/util/List;)Lcom/payment/paymentsdk/apms/model/ApmsBodyBuilder;"; IntPtr native_apms = global::Android.Runtime.JavaList<global::Com.Payment.Paymentsdk.Integrationmodels.PaymentSdkApms>.ToLocalJniHandle (apms); try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue (native_apms); var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, __args); return global::Java.Lang.Object.GetObject<global::Com.Payment.Paymentsdk.Apms.Model.ApmsBodyBuilder> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { JNIEnv.DeleteLocalRef (native_apms); global::System.GC.KeepAlive (apms); } } // Metadata.xml XPath method reference: path="/api/package[@name='com.payment.paymentsdk.apms.model']/class[@name='ApmsBodyBuilder']/method[@name='setDeviceInfo' and count(parameter)=1 and parameter[1][@type='com.payment.paymentsdk.sharedclasses.model.request.PtDeviceInfo']]" [Register ("setDeviceInfo", "(Lcom/payment/paymentsdk/sharedclasses/model/request/PtDeviceInfo;)Lcom/payment/paymentsdk/apms/model/ApmsBodyBuilder;", "")] public unsafe global::Com.Payment.Paymentsdk.Apms.Model.ApmsBodyBuilder SetDeviceInfo (global::Com.Payment.Paymentsdk.Sharedclasses.Model.Request.PtDeviceInfo deviceInfo) { const string __id = "setDeviceInfo.(Lcom/payment/paymentsdk/sharedclasses/model/request/PtDeviceInfo;)Lcom/payment/paymentsdk/apms/model/ApmsBodyBuilder;"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue ((deviceInfo == null) ? IntPtr.Zero : ((global::Java.Lang.Object) deviceInfo).Handle); var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, __args); return global::Java.Lang.Object.GetObject<global::Com.Payment.Paymentsdk.Apms.Model.ApmsBodyBuilder> (__rm.Handle, JniHandleOwnership.TransferLocalRef); } finally { global::System.GC.KeepAlive (deviceInfo); } } } }
62.114286
298
0.775836
[ "MIT" ]
amr-Magdy-PT/xamarin-paytabs-binding
android/PaymentSDK.Binding/obj/Debug/generated/src/Com.Payment.Paymentsdk.Apms.Model.ApmsBodyBuilder.cs
6,522
C#
using System; namespace Editor_Mono.Cecil { public enum AssemblyHashAlgorithm : uint { None, Reserved = 32771u, SHA1 } }
12.727273
42
0.664286
[ "MIT" ]
2823896/cshotfix
CSHotFix_SimpleFramework/Assets/CSHotFixLibaray/Editor/Injector/MonoCecil/Mono.Cecil/AssemblyHashAlgorithm.cs
140
C#
// Copyright (c) 2014 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.Windows.Forms; namespace PyWalker { /// <summary> /// Class with program entry point. /// </summary> internal sealed class Program { /// <summary> /// Program entry point. /// </summary> [STAThread] private static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
37.285714
93
0.745849
[ "MIT" ]
galich/SharpDevelop
src/AddIns/BackendBindings/Python/PyWalker/Program.cs
1,568
C#
using Nefarius.ViGEm.Client.Targets; using Nefarius.ViGEm.Client.Targets.Xbox360; using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Linq; namespace BetterJoyForCemu { public partial class MainForm : Form { public bool nonOriginal = Boolean.Parse(ConfigurationManager.AppSettings["NonOriginalController"]); public List<Button> con, loc; public bool calibrate; public List<KeyValuePair<string, float[]>> caliData; private Timer countDown; private int count; public List<int> xG, yG, zG, xA, yA, zA; public MainForm() { xG = new List<int>(); yG = new List<int>(); zG = new List<int>(); xA = new List<int>(); yA = new List<int>(); zA = new List<int>(); caliData = new List<KeyValuePair<string, float[]>> { new KeyValuePair<string, float[]>("0", new float[6] {0,0,0,-710,0,0}) }; InitializeComponent(); if (!nonOriginal) AutoCalibrate.Hide(); con = new List<Button> { con1, con2, con3, con4 }; loc = new List<Button> { loc1, loc2, loc3, loc4 }; //list all options string[] myConfigs = ConfigurationManager.AppSettings.AllKeys; Size childSize = new Size(87, 20); for (int i = 0; i != myConfigs.Length; i++) { settingsTable.RowCount++; settingsTable.Controls.Add(new Label() { Text = myConfigs[i], TextAlign = ContentAlignment.BottomLeft, AutoEllipsis = true, Size = childSize }, 0, i); var value = ConfigurationManager.AppSettings[myConfigs[i]]; Control childControl; if (value == "true" || value == "false") { childControl = new CheckBox() { Checked = Boolean.Parse(value), Size = childSize }; } else { childControl = new TextBox() { Text = value, Size = childSize }; } childControl.MouseClick += cbBox_Changed; settingsTable.Controls.Add(childControl, 1, i); } } private void HideToTray() { this.WindowState = FormWindowState.Minimized; notifyIcon.Visible = true; notifyIcon.BalloonTipText = "Double click the tray icon to maximise!"; notifyIcon.ShowBalloonTip(0); this.ShowInTaskbar = false; this.Hide(); } private void ShowFromTray() { this.Show(); this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; this.FormBorderStyle = FormBorderStyle.FixedSingle; this.Icon = Properties.Resources.betterjoyforcemu_icon; notifyIcon.Visible = false; } private void MainForm_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { HideToTray(); } } private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e) { ShowFromTray(); } private void MainForm_Load(object sender, EventArgs e) { Config.Init(caliData); Program.Start(); passiveScanBox.Checked = Config.IntValue("ProgressiveScan") == 1; startInTrayBox.Checked = Config.IntValue("StartInTray") == 1; if (Config.IntValue("StartInTray") == 1) { HideToTray(); } else { ShowFromTray(); } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { try { Program.Stop(); Environment.Exit(0); } catch { } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { // this does not work, for some reason. Fix before release try { Program.Stop(); Close(); Environment.Exit(0); } catch { } } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { donationLink.LinkVisited = true; System.Diagnostics.Process.Start("http://paypal.me/DavidKhachaturov/5"); } private void passiveScanBox_CheckedChanged(object sender, EventArgs e) { Config.SetValue("ProgressiveScan", passiveScanBox.Checked ? "1" : "0"); Config.Save(); } public void AppendTextBox(string value) { // https://stackoverflow.com/questions/519233/writing-to-a-textbox-from-another-thread if (InvokeRequired) { this.Invoke(new Action<string>(AppendTextBox), new object[] { value }); return; } console.AppendText(value); } bool toRumble = Boolean.Parse(ConfigurationManager.AppSettings["EnableRumble"]); bool showAsXInput = Boolean.Parse(ConfigurationManager.AppSettings["ShowAsXInput"]); bool showAsDS4 = Boolean.Parse(ConfigurationManager.AppSettings["ShowAsDS4"]); public void locBtnClick(object sender, EventArgs e) { Button bb = sender as Button; if (bb.Tag.GetType() == typeof(Button)) { Button button = bb.Tag as Button; if (button.Tag.GetType() == typeof(Joycon)) { Joycon v = (Joycon)button.Tag; v.SetRumble(160.0f, 320.0f, 1.0f, 300); } } } public void conBtnClick(object sender, EventArgs e) { Button button = sender as Button; if (button.Tag.GetType() == typeof(Joycon)) { Joycon v = (Joycon)button.Tag; if (v.other == null && !v.isPro) { // needs connecting to other joycon (so messy omg) bool succ = false; if (Program.mgr.j.Count == 1) { // when want to have a single joycon in vertical mode v.other = v; // hacky; implement check in Joycon.cs to account for this succ = true; } else { foreach (Joycon jc in Program.mgr.j) { if (!jc.isPro && jc.isLeft != v.isLeft && jc != v && jc.other == null) { v.other = jc; jc.other = v; //Set both Joycon LEDs to the one with the lowest ID byte led = jc.LED <= v.LED ? jc.LED : v.LED; jc.LED = led; v.LED = led; jc.SetPlayerLED(led); v.SetPlayerLED(led); if (v.out_xbox != null) { v.out_xbox.Disconnect(); v.out_xbox = null; } if (v.out_ds4 != null) { v.out_ds4.Disconnect(); v.out_ds4 = null; } // setting the other joycon's button image foreach (Button b in con) if (b.Tag == jc) b.BackgroundImage = jc.isLeft ? Properties.Resources.jc_left : Properties.Resources.jc_right; succ = true; break; } } } if (succ) foreach (Button b in con) if (b.Tag == v) b.BackgroundImage = v.isLeft ? Properties.Resources.jc_left : Properties.Resources.jc_right; } else if (v.other != null && !v.isPro) { // needs disconnecting from other joycon ReenableViGEm(v); ReenableViGEm(v.other); button.BackgroundImage = v.isLeft ? Properties.Resources.jc_left_s : Properties.Resources.jc_right_s; foreach (Button b in con) if (b.Tag == v.other) b.BackgroundImage = v.other.isLeft ? Properties.Resources.jc_left_s : Properties.Resources.jc_right_s; //Set original Joycon LEDs v.other.LED = (byte)(0x1 << v.other.PadId); v.LED = (byte)(0x1 << v.PadId); v.other.SetPlayerLED(v.other.LED); v.SetPlayerLED(v.LED); v.other.other = null; v.other = null; } } } private void startInTrayBox_CheckedChanged(object sender, EventArgs e) { Config.SetValue("StartInTray", startInTrayBox.Checked ? "1" : "0"); Config.Save(); } private void btn_open3rdP_Click(object sender, EventArgs e) { _3rdPartyControllers partyForm = new _3rdPartyControllers(); partyForm.ShowDialog(); } private void settingsApply_Click(object sender, EventArgs e) { var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var settings = configFile.AppSettings.Settings; for (int row = 0; row < ConfigurationManager.AppSettings.AllKeys.Length; row++) { var valCtl = settingsTable.GetControlFromPosition(1, row); var KeyCtl = settingsTable.GetControlFromPosition(0, row).Text; if (valCtl.GetType() == typeof(CheckBox) && settings[KeyCtl] != null) { settings[KeyCtl].Value = ((CheckBox)valCtl).Checked.ToString().ToLower(); } else if (valCtl.GetType() == typeof(TextBox) && settings[KeyCtl] != null) { settings[KeyCtl].Value = ((TextBox)valCtl).Text.ToLower(); } } try { configFile.Save(ConfigurationSaveMode.Modified); } catch (ConfigurationErrorsException) { AppendTextBox("Error writing app settings.\r\n"); } ConfigurationManager.AppSettings["AutoPowerOff"] = "false"; // Prevent joycons poweroff when applying settings Application.Restart(); Environment.Exit(0); } void ReenableViGEm(Joycon v) { if (showAsXInput && v.out_xbox == null) { v.out_xbox = new Controller.OutputControllerXbox360(); if (toRumble) v.out_xbox.FeedbackReceived += v.ReceiveRumble; v.out_xbox.Connect(); } if (showAsDS4 && v.out_ds4 == null) { v.out_ds4 = new Controller.OutputControllerDualShock4(); if (toRumble) v.out_ds4.FeedbackReceived += v.Ds4_FeedbackReceived; v.out_ds4.Connect(); } } private void foldLbl_Click(object sender, EventArgs e) { rightPanel.Visible = !rightPanel.Visible; foldLbl.Text = rightPanel.Visible ? "<" : ">"; } private void cbBox_Changed(object sender, EventArgs e) { var coord = settingsTable.GetPositionFromControl(sender as Control); var valCtl = settingsTable.GetControlFromPosition(coord.Column, coord.Row); var KeyCtl = settingsTable.GetControlFromPosition(coord.Column - 1, coord.Row).Text; try { var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var settings = configFile.AppSettings.Settings; if (valCtl.GetType() == typeof(CheckBox) && settings[KeyCtl] != null) { settings[KeyCtl].Value = ((CheckBox)valCtl).Checked.ToString().ToLower(); } else if (valCtl.GetType() == typeof(TextBox) && settings[KeyCtl] != null) { settings[KeyCtl].Value = ((TextBox)valCtl).Text.ToLower(); } if (KeyCtl == "HomeLEDOn") { bool on = settings[KeyCtl].Value.ToLower() == "true"; foreach (Joycon j in Program.mgr.j) { j.SetHomeLight(on); } } configFile.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name); } catch (ConfigurationErrorsException) { AppendTextBox("Error writing app settings\r\n"); Trace.WriteLine(String.Format("rw {0}, column {1}, {2}, {3}", coord.Row, coord.Column, sender.GetType(), KeyCtl)); } } private void StartCalibrate(object sender, EventArgs e) { if (Program.mgr.j.Count == 0) { this.console.Text = "Please connect a single pro controller."; return; } if (Program.mgr.j.Count > 1) { this.console.Text = "Please calibrate one controller at a time (disconnect others)."; return; } this.AutoCalibrate.Enabled = false; countDown = new Timer(); this.count = 4; this.CountDown(null, null); countDown.Tick += new EventHandler(CountDown); countDown.Interval = 1000; countDown.Enabled = true; } private void StartGetData() { this.xG.Clear(); this.yG.Clear(); this.zG.Clear(); this.xA.Clear(); this.yA.Clear(); this.zA.Clear(); countDown = new Timer(); this.count = 3; this.calibrate = true; countDown.Tick += new EventHandler(CalcData); countDown.Interval = 1000; countDown.Enabled = true; } private void btn_reassign_open_Click(object sender, EventArgs e) { Reassign mapForm = new Reassign(); mapForm.ShowDialog(); } private void CountDown(object sender, EventArgs e) { if (this.count == 0) { this.console.Text = "Calibrating..."; countDown.Stop(); this.StartGetData(); } else { this.console.Text = "Plese keep the controller flat." + "\r\n"; this.console.Text += "Calibration will start in " + this.count + " seconds."; this.count--; } } private void CalcData(object sender, EventArgs e) { if (this.count == 0) { countDown.Stop(); this.calibrate = false; string serNum = Program.mgr.j.First().serial_number; int serIndex = this.findSer(serNum); float[] Arr = new float[6] { 0, 0, 0, 0, 0, 0 }; if (serIndex == -1) { this.caliData.Add(new KeyValuePair<string, float[]>( serNum, Arr )); } else { Arr = this.caliData[serIndex].Value; } Random rnd = new Random(); Arr[0] = (float)quickselect_median(this.xG, rnd.Next); Arr[1] = (float)quickselect_median(this.yG, rnd.Next); Arr[2] = (float)quickselect_median(this.zG, rnd.Next); Arr[3] = (float)quickselect_median(this.xA, rnd.Next); Arr[4] = (float)quickselect_median(this.yA, rnd.Next); Arr[5] = (float)quickselect_median(this.zA, rnd.Next) - 4010; //Joycon.cs acc_sen 16384 this.console.Text += "Calibration completed!!!" + "\r\n"; Config.SaveCaliData(this.caliData); Program.mgr.j.First().getActiveData(); this.AutoCalibrate.Enabled = true; } else { this.count--; } } private double quickselect_median(List<int> l, Func<int, int> pivot_fn) { int ll = l.Count; if (ll % 2 == 1) { return this.quickselect(l, ll / 2, pivot_fn); } else { return 0.5 * (quickselect(l, ll / 2 - 1, pivot_fn) + quickselect(l, ll / 2, pivot_fn)); } } private int quickselect(List<int> l, int k, Func<int, int> pivot_fn) { if (l.Count == 1 && k == 0) { return l[0]; } int pivot = l[pivot_fn(l.Count)]; List<int> lows = l.Where(x => x < pivot).ToList(); List<int> highs = l.Where(x => x > pivot).ToList(); List<int> pivots = l.Where(x => x == pivot).ToList(); if (k < lows.Count) { return quickselect(lows, k, pivot_fn); } else if (k < (lows.Count + pivots.Count)) { return pivots[0]; } else { return quickselect(highs, k - lows.Count - pivots.Count, pivot_fn); } } public float[] activeCaliData(string serNum) { for (int i = 0; i < this.caliData.Count; i++) { if (this.caliData[i].Key == serNum) { return this.caliData[i].Value; } } return this.caliData[0].Value; } private int findSer(string serNum) { for (int i = 0; i < this.caliData.Count; i++) { if (this.caliData[i].Key == serNum) { return i; } } return -1; } } }
41.342529
166
0.513123
[ "MIT" ]
johannesugb/BetterJoy
BetterJoyForCemu/MainForm.cs
17,986
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SuperSimpleBlobStore.DataAccess.Model { public class BlobContents { public int Id { get; set; } public byte[] Content { get; set; } } }
19.466667
47
0.691781
[ "MIT" ]
richardprice/SuperSimpleBlobStore
SuperSimpleBlobStore.DataAccess/Model/BlobContents.cs
294
C#
using System; namespace aXon.Models.Base { public abstract class BaseModel { public Guid Id { get; set; } } }
14.555556
36
0.610687
[ "BSD-3-Clause" ]
tmassey/mtos
aXon.Models/Base/BaseModel.cs
133
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using ThScoreFileConverter; using ThScoreFileConverter.Models.Th12; using ThScoreFileConverterTests.Models.Th10.Stubs; using IClearData = ThScoreFileConverter.Models.Th10.IClearData< ThScoreFileConverter.Models.Th12.CharaWithTotal, ThScoreFileConverter.Models.Th10.StageProgress>; using ISpellCard = ThScoreFileConverter.Models.Th10.ISpellCard<ThScoreFileConverter.Models.Level>; using StageProgress = ThScoreFileConverter.Models.Th10.StageProgress; namespace ThScoreFileConverterTests.Models.Th12 { [TestClass] public class CareerReplacerTests { internal static IReadOnlyDictionary<CharaWithTotal, IClearData> ClearDataDictionary { get; } = new List<IClearData> { ClearDataTests.MakeValidStub(), }.ToDictionary(element => element.Chara); [TestMethod] public void CareerReplacerTest() { var replacer = new CareerReplacer(ClearDataDictionary); Assert.IsNotNull(replacer); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void CareerReplacerTestNull() { _ = new CareerReplacer(null); Assert.Fail(TestUtils.Unreachable); } [TestMethod] public void CareerReplacerTestEmpty() { var dictionary = new Dictionary<CharaWithTotal, IClearData>(); var replacer = new CareerReplacer(dictionary); Assert.IsNotNull(replacer); } [TestMethod] public void ReplaceTestClearCount() { var replacer = new CareerReplacer(ClearDataDictionary); Assert.AreEqual("126", replacer.Replace("%T12C003RB1")); } [TestMethod] public void ReplaceTestTrialCount() { var replacer = new CareerReplacer(ClearDataDictionary); Assert.AreEqual("459", replacer.Replace("%T12C003RB2")); } [TestMethod] public void ReplaceTestTotalClearCount() { var outputSeparator = Settings.Instance.OutputNumberGroupSeparator; var replacer = new CareerReplacer(ClearDataDictionary); Settings.Instance.OutputNumberGroupSeparator = true; Assert.AreEqual("20,340", replacer.Replace("%T12C000RB1")); Settings.Instance.OutputNumberGroupSeparator = false; Assert.AreEqual("20340", replacer.Replace("%T12C000RB1")); Settings.Instance.OutputNumberGroupSeparator = outputSeparator; } [TestMethod] public void ReplaceTestTotalTrialCount() { var outputSeparator = Settings.Instance.OutputNumberGroupSeparator; var replacer = new CareerReplacer(ClearDataDictionary); Settings.Instance.OutputNumberGroupSeparator = true; Assert.AreEqual("57,969", replacer.Replace("%T12C000RB2")); Settings.Instance.OutputNumberGroupSeparator = false; Assert.AreEqual("57969", replacer.Replace("%T12C000RB2")); Settings.Instance.OutputNumberGroupSeparator = outputSeparator; } [TestMethod] public void ReplaceTestEmpty() { var dictionary = new Dictionary<CharaWithTotal, IClearData>(); var replacer = new CareerReplacer(dictionary); Assert.AreEqual("0", replacer.Replace("%T12C003RB1")); } [TestMethod] public void ReplaceTestEmptyCards() { var dictionary = new List<IClearData> { new ClearDataStub<CharaWithTotal, StageProgress>() { Chara = CharaWithTotal.ReimuB, Cards = new Dictionary<int, ISpellCard>(), }, }.ToDictionary(element => element.Chara); var replacer = new CareerReplacer(dictionary); Assert.AreEqual("0", replacer.Replace("%T12C003RB1")); } [TestMethod] public void ReplaceTestInvalidFormat() { var replacer = new CareerReplacer(ClearDataDictionary); Assert.AreEqual("%T12X003RB1", replacer.Replace("%T12X003RB1")); } [TestMethod] public void ReplaceTestInvalidNumber() { var replacer = new CareerReplacer(ClearDataDictionary); Assert.AreEqual("%T12C114RB1", replacer.Replace("%T12C114RB1")); } [TestMethod] public void ReplaceTestInvalidChara() { var replacer = new CareerReplacer(ClearDataDictionary); Assert.AreEqual("%T12C003XX1", replacer.Replace("%T12C003XX1")); } [TestMethod] public void ReplaceTestInvalidType() { var replacer = new CareerReplacer(ClearDataDictionary); Assert.AreEqual("%T12C003RBX", replacer.Replace("%T12C003RBX")); } } }
34.445205
102
0.631139
[ "BSD-2-Clause" ]
fossabot/ThScoreFileConverter
ThScoreFileConverterTests/Models/Th12/CareerReplacerTests.cs
5,031
C#
namespace WinSysInfo.PEView.Model { /// <summary> /// The following values are defined for base type, although Microsoft /// tools generally do not use this field and set the LSB to 0. Instead, /// Visual C++ debug information is used to indicate types. However, the /// possible COFF values are listed here for completeness. /// </summary> public enum EnumSymbolBaseType { IMAGE_SYM_TYPE_NULL = 0, ///< No type information or unknown base type. IMAGE_SYM_TYPE_VOID = 1, ///< Used with void pointers and functions. IMAGE_SYM_TYPE_CHAR = 2, ///< A character (signed byte). IMAGE_SYM_TYPE_SHORT = 3, ///< A 2-byte signed integer. IMAGE_SYM_TYPE_INT = 4, ///< A natural integer type on the target. IMAGE_SYM_TYPE_LONG = 5, ///< A 4-byte signed integer. IMAGE_SYM_TYPE_FLOAT = 6, ///< A 4-byte floating-point number. IMAGE_SYM_TYPE_DOUBLE = 7, ///< An 8-byte floating-point number. IMAGE_SYM_TYPE_STRUCT = 8, ///< A structure. IMAGE_SYM_TYPE_UNION = 9, ///< An union. IMAGE_SYM_TYPE_ENUM = 10, ///< An enumerated type. IMAGE_SYM_TYPE_MOE = 11, ///< A member of enumeration (a specific value). IMAGE_SYM_TYPE_BYTE = 12, ///< A byte; unsigned 1-byte integer. IMAGE_SYM_TYPE_WORD = 13, ///< A word; unsigned 2-byte integer. IMAGE_SYM_TYPE_UINT = 14, ///< An unsigned integer of natural size. IMAGE_SYM_TYPE_DWORD = 15 ///< An unsigned 4-byte integer. } }
52.586207
81
0.647213
[ "MIT" ]
subha007/SimpleSystemInfo
WinSysInfo.PEView/Model/Enum/EnumSymbolBaseType.cs
1,527
C#
using HBK.Storage.Dashboard.DataSource; using Microsoft.AspNetCore.Components; using MudBlazor; namespace HBK.Storage.Dashboard.Pages.FileEntities { public partial class PublishAccessTokenDialog { /// <summary> /// 取得或設定 Dialog 中使用的字定義屬性(解決 Dialog 無法反白選取的問題) /// <seealso cref="https://github.com/MudBlazor/MudBlazor/issues/1186"/> /// </summary> public Dictionary<string, object> DialogAttributes { get; set; } = new() { { "tabindex", "10" }, }; [Parameter] public FileEntityResponse FileEntity { get; set; } public FileAccessTokenType FileAccessTokenType { get; set; } public string FileLink { get; set; } public string HandlerIndicate { get; set; } = string.Empty; public int AccessTimesLimit { get; set; } = 10; public int ExpireAfterMinute { get; set; } = 60; public async Task PublishAsync() { PostFileAccessTokenResponse result = null; if (this.FileAccessTokenType == FileAccessTokenType.Normal) { result = await this.HBKStorageApi.FileaccesstokensPOSTAsync(base.StateContainer.StorageProviderResponse.Storage_provider_id, new PostFileAccessTokenRequest() { Access_times_limit = this.AccessTimesLimit, Expire_after_minutes = this.ExpireAfterMinute, File_access_token_type = FileAccessTokenType.Normal, File_entity_id = this.FileEntity.File_entity_id, Handler_indicate = this.HandlerIndicate }); } else if (this.FileAccessTokenType == FileAccessTokenType.Normal_no_limit) { result = await this.HBKStorageApi.FileaccesstokensPOSTAsync(base.StateContainer.StorageProviderResponse.Storage_provider_id, new PostFileAccessTokenRequest() { File_access_token_type = FileAccessTokenType.Normal_no_limit, File_entity_id = this.FileEntity.File_entity_id, Handler_indicate = this.HandlerIndicate, Expire_after_minutes = this.ExpireAfterMinute }); } if (result != null) { this.FileLink = this.HBKStorageApi.BaseUrl + $"docs?esic={result.Token}"; } base.StateHasChanged(); } public async Task CopyLinkToClipboardAsync() { await base.ClipboardService.WriteTextAsync(this.FileLink); this.Snackbar.Add("已複製到剪貼簿", Severity.Success); } } }
39.352941
173
0.606502
[ "MIT" ]
nightsoul357/HBK-Storage
HBK.Storage.Dashboard/Pages/FileEntities/PublishAccessTokenDialog.razor.cs
2,742
C#
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using SixLabors.ImageSharp.Metadata.Profiles.Exif; using Xunit; namespace SixLabors.ImageSharp.Tests.Metadata.Profiles.Exif.Values { public class ExifValuesTests { public static TheoryData<ExifTag> ByteTags => new TheoryData<ExifTag> { { ExifTag.FaxProfile }, { ExifTag.ModeNumber }, { ExifTag.GPSAltitudeRef } }; public static TheoryData<ExifTag> ByteArrayTags => new TheoryData<ExifTag> { { ExifTag.ClipPath }, { ExifTag.VersionYear }, { ExifTag.XMP }, { ExifTag.CFAPattern2 }, { ExifTag.TIFFEPStandardID }, { ExifTag.XPTitle }, { ExifTag.XPComment }, { ExifTag.XPAuthor }, { ExifTag.XPKeywords }, { ExifTag.XPSubject }, { ExifTag.GPSVersionID }, }; public static TheoryData<ExifTag> DoubleArrayTags => new TheoryData<ExifTag> { { ExifTag.PixelScale }, { ExifTag.IntergraphMatrix }, { ExifTag.ModelTiePoint }, { ExifTag.ModelTransform } }; public static TheoryData<ExifTag> LongTags => new TheoryData<ExifTag> { { ExifTag.SubfileType }, { ExifTag.SubIFDOffset }, { ExifTag.GPSIFDOffset }, { ExifTag.T4Options }, { ExifTag.T6Options }, { ExifTag.XClipPathUnits }, { ExifTag.YClipPathUnits }, { ExifTag.ProfileType }, { ExifTag.CodingMethods }, { ExifTag.T82ptions }, { ExifTag.JPEGInterchangeFormat }, { ExifTag.JPEGInterchangeFormatLength }, { ExifTag.MDFileTag }, { ExifTag.StandardOutputSensitivity }, { ExifTag.RecommendedExposureIndex }, { ExifTag.ISOSpeed }, { ExifTag.ISOSpeedLatitudeyyy }, { ExifTag.ISOSpeedLatitudezzz }, { ExifTag.FaxRecvParams }, { ExifTag.FaxRecvTime }, { ExifTag.ImageNumber }, }; public static TheoryData<ExifTag> LongArrayTags => new TheoryData<ExifTag> { { ExifTag.FreeOffsets }, { ExifTag.FreeByteCounts }, { ExifTag.ColorResponseUnit }, { ExifTag.TileOffsets }, { ExifTag.SMinSampleValue }, { ExifTag.SMaxSampleValue }, { ExifTag.JPEGQTables }, { ExifTag.JPEGDCTables }, { ExifTag.JPEGACTables }, { ExifTag.StripRowCounts }, { ExifTag.IntergraphRegisters }, { ExifTag.TimeZoneOffset } }; public static TheoryData<ExifTag> NumberTags => new TheoryData<ExifTag> { { ExifTag.ImageWidth }, { ExifTag.ImageLength }, { ExifTag.TileWidth }, { ExifTag.TileLength }, { ExifTag.BadFaxLines }, { ExifTag.ConsecutiveBadFaxLines }, { ExifTag.PixelXDimension }, { ExifTag.PixelYDimension } }; public static TheoryData<ExifTag> NumberArrayTags => new TheoryData<ExifTag> { { ExifTag.StripOffsets }, { ExifTag.TileByteCounts }, { ExifTag.ImageLayer } }; public static TheoryData<ExifTag> RationalTags => new TheoryData<ExifTag> { { ExifTag.XPosition }, { ExifTag.YPosition }, { ExifTag.XResolution }, { ExifTag.YResolution }, { ExifTag.BatteryLevel }, { ExifTag.ExposureTime }, { ExifTag.FNumber }, { ExifTag.MDScalePixel }, { ExifTag.CompressedBitsPerPixel }, { ExifTag.ApertureValue }, { ExifTag.MaxApertureValue }, { ExifTag.SubjectDistance }, { ExifTag.FocalLength }, { ExifTag.FlashEnergy2 }, { ExifTag.FocalPlaneXResolution2 }, { ExifTag.FocalPlaneYResolution2 }, { ExifTag.ExposureIndex2 }, { ExifTag.Humidity }, { ExifTag.Pressure }, { ExifTag.Acceleration }, { ExifTag.FlashEnergy }, { ExifTag.FocalPlaneXResolution }, { ExifTag.FocalPlaneYResolution }, { ExifTag.ExposureIndex }, { ExifTag.DigitalZoomRatio }, { ExifTag.GPSAltitude }, { ExifTag.GPSDOP }, { ExifTag.GPSSpeed }, { ExifTag.GPSTrack }, { ExifTag.GPSImgDirection }, { ExifTag.GPSDestBearing }, { ExifTag.GPSDestDistance }, }; public static TheoryData<ExifTag> RationalArrayTags => new TheoryData<ExifTag> { { ExifTag.WhitePoint }, { ExifTag.PrimaryChromaticities }, { ExifTag.YCbCrCoefficients }, { ExifTag.ReferenceBlackWhite }, { ExifTag.GPSLatitude }, { ExifTag.GPSLongitude }, { ExifTag.GPSTimestamp }, { ExifTag.GPSDestLatitude }, { ExifTag.GPSDestLongitude }, { ExifTag.LensSpecification } }; public static TheoryData<ExifTag> ShortTags => new TheoryData<ExifTag> { { ExifTag.OldSubfileType }, { ExifTag.Compression }, { ExifTag.PhotometricInterpretation }, { ExifTag.Thresholding }, { ExifTag.CellWidth }, { ExifTag.CellLength }, { ExifTag.FillOrder }, { ExifTag.Orientation }, { ExifTag.SamplesPerPixel }, { ExifTag.PlanarConfiguration }, { ExifTag.GrayResponseUnit }, { ExifTag.ResolutionUnit }, { ExifTag.CleanFaxData }, { ExifTag.InkSet }, { ExifTag.NumberOfInks }, { ExifTag.DotRange }, { ExifTag.Indexed }, { ExifTag.OPIProxy }, { ExifTag.JPEGProc }, { ExifTag.JPEGRestartInterval }, { ExifTag.YCbCrPositioning }, { ExifTag.Rating }, { ExifTag.RatingPercent }, { ExifTag.ExposureProgram }, { ExifTag.Interlace }, { ExifTag.SelfTimerMode }, { ExifTag.SensitivityType }, { ExifTag.MeteringMode }, { ExifTag.LightSource }, { ExifTag.FocalPlaneResolutionUnit2 }, { ExifTag.SensingMethod2 }, { ExifTag.Flash }, { ExifTag.ColorSpace }, { ExifTag.FocalPlaneResolutionUnit }, { ExifTag.SensingMethod }, { ExifTag.CustomRendered }, { ExifTag.ExposureMode }, { ExifTag.WhiteBalance }, { ExifTag.FocalLengthIn35mmFilm }, { ExifTag.SceneCaptureType }, { ExifTag.GainControl }, { ExifTag.Contrast }, { ExifTag.Saturation }, { ExifTag.Sharpness }, { ExifTag.SubjectDistanceRange }, { ExifTag.GPSDifferential } }; public static TheoryData<ExifTag> ShortArrayTags => new TheoryData<ExifTag> { { ExifTag.BitsPerSample }, { ExifTag.MinSampleValue }, { ExifTag.MaxSampleValue }, { ExifTag.GrayResponseCurve }, { ExifTag.ColorMap }, { ExifTag.ExtraSamples }, { ExifTag.PageNumber }, { ExifTag.TransferFunction }, { ExifTag.Predictor }, { ExifTag.HalftoneHints }, { ExifTag.SampleFormat }, { ExifTag.TransferRange }, { ExifTag.DefaultImageColor }, { ExifTag.JPEGLosslessPredictors }, { ExifTag.JPEGPointTransforms }, { ExifTag.YCbCrSubsampling }, { ExifTag.CFARepeatPatternDim }, { ExifTag.IntergraphPacketData }, { ExifTag.ISOSpeedRatings }, { ExifTag.SubjectArea }, { ExifTag.SubjectLocation } }; public static TheoryData<ExifTag> SignedRationalTags => new TheoryData<ExifTag> { { ExifTag.ShutterSpeedValue }, { ExifTag.BrightnessValue }, { ExifTag.ExposureBiasValue }, { ExifTag.AmbientTemperature }, { ExifTag.WaterDepth }, { ExifTag.CameraElevationAngle } }; public static TheoryData<ExifTag> SignedRationalArrayTags => new TheoryData<ExifTag> { { ExifTag.Decode } }; public static TheoryData<ExifTag> StringTags => new TheoryData<ExifTag> { { ExifTag.ImageDescription }, { ExifTag.Make }, { ExifTag.Model }, { ExifTag.Software }, { ExifTag.DateTime }, { ExifTag.Artist }, { ExifTag.HostComputer }, { ExifTag.Copyright }, { ExifTag.DocumentName }, { ExifTag.PageName }, { ExifTag.InkNames }, { ExifTag.TargetPrinter }, { ExifTag.ImageID }, { ExifTag.MDLabName }, { ExifTag.MDSampleInfo }, { ExifTag.MDPrepDate }, { ExifTag.MDPrepTime }, { ExifTag.MDFileUnits }, { ExifTag.SEMInfo }, { ExifTag.SpectralSensitivity }, { ExifTag.DateTimeOriginal }, { ExifTag.DateTimeDigitized }, { ExifTag.SubsecTime }, { ExifTag.SubsecTimeOriginal }, { ExifTag.SubsecTimeDigitized }, { ExifTag.RelatedSoundFile }, { ExifTag.FaxSubaddress }, { ExifTag.OffsetTime }, { ExifTag.OffsetTimeOriginal }, { ExifTag.OffsetTimeDigitized }, { ExifTag.SecurityClassification }, { ExifTag.ImageHistory }, { ExifTag.ImageUniqueID }, { ExifTag.OwnerName }, { ExifTag.SerialNumber }, { ExifTag.LensMake }, { ExifTag.LensModel }, { ExifTag.LensSerialNumber }, { ExifTag.GDALMetadata }, { ExifTag.GDALNoData }, { ExifTag.GPSLatitudeRef }, { ExifTag.GPSLongitudeRef }, { ExifTag.GPSSatellites }, { ExifTag.GPSStatus }, { ExifTag.GPSMeasureMode }, { ExifTag.GPSSpeedRef }, { ExifTag.GPSTrackRef }, { ExifTag.GPSImgDirectionRef }, { ExifTag.GPSMapDatum }, { ExifTag.GPSDestLatitudeRef }, { ExifTag.GPSDestLongitudeRef }, { ExifTag.GPSDestBearingRef }, { ExifTag.GPSDestDistanceRef }, { ExifTag.GPSDateStamp } }; public static TheoryData<ExifTag> UndefinedTags => new TheoryData<ExifTag> { { ExifTag.FileSource }, { ExifTag.SceneType } }; public static TheoryData<ExifTag> UndefinedArrayTags => new TheoryData<ExifTag> { { ExifTag.JPEGTables }, { ExifTag.OECF }, { ExifTag.ExifVersion }, { ExifTag.ComponentsConfiguration }, { ExifTag.MakerNote }, { ExifTag.UserComment }, { ExifTag.FlashpixVersion }, { ExifTag.SpatialFrequencyResponse }, { ExifTag.SpatialFrequencyResponse2 }, { ExifTag.Noise }, { ExifTag.CFAPattern }, { ExifTag.DeviceSettingDescription }, { ExifTag.ImageSourceData }, { ExifTag.GPSProcessingMethod }, { ExifTag.GPSAreaInformation } }; [Theory] [MemberData(nameof(ByteTags))] public void ExifByteTests(ExifTag tag) { const byte expected = byte.MaxValue; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue((int)expected)); Assert.True(value.TrySetValue(expected)); var typed = (ExifByte)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(ByteArrayTags))] public void ExifByteArrayTests(ExifTag tag) { byte[] expected = new[] { byte.MaxValue }; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue(expected)); var typed = (ExifByteArray)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(DoubleArrayTags))] public void ExifDoubleArrayTests(ExifTag tag) { double[] expected = new[] { double.MaxValue }; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue(expected)); var typed = (ExifDoubleArray)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(LongTags))] public void ExifLongTests(ExifTag tag) { const uint expected = uint.MaxValue; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue(expected)); var typed = (ExifLong)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(LongArrayTags))] public void ExifLongArrayTests(ExifTag tag) { uint[] expected = new[] { uint.MaxValue }; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue(expected)); var typed = (ExifLongArray)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(NumberTags))] public void ExifNumberTests(ExifTag tag) { Number expected = ushort.MaxValue; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue((uint)expected)); Assert.True(value.TrySetValue((int)expected)); Assert.True(value.TrySetValue(expected)); var typed = (ExifNumber)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(NumberArrayTags))] public void ExifNumberArrayTests(ExifTag tag) { Number[] expected = new[] { new Number(uint.MaxValue) }; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue(expected)); var typed = (ExifNumberArray)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(RationalTags))] public void ExifRationalTests(ExifTag tag) { var expected = new Rational(21, 42); ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue(new SignedRational(expected.ToDouble()))); Assert.True(value.TrySetValue(expected)); var typed = (ExifRational)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(RationalArrayTags))] public void ExifRationalArrayTests(ExifTag tag) { Rational[] expected = new[] { new Rational(21, 42) }; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue(expected)); var typed = (ExifRationalArray)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(ShortTags))] public void ExifShortTests(ExifTag tag) { const ushort expected = (ushort)short.MaxValue; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue((int)expected)); Assert.True(value.TrySetValue((short)expected)); Assert.True(value.TrySetValue(expected)); var typed = (ExifShort)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(ShortArrayTags))] public void ExifShortArrayTests(ExifTag tag) { ushort[] expected = new[] { ushort.MaxValue }; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue(expected)); var typed = (ExifShortArray)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(SignedRationalTags))] public void ExifSignedRationalTests(ExifTag tag) { var expected = new SignedRational(21, 42); ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue(expected)); var typed = (ExifSignedRational)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(SignedRationalArrayTags))] public void ExifSignedRationalArrayTests(ExifTag tag) { SignedRational[] expected = new[] { new SignedRational(21, 42) }; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue(expected)); var typed = (ExifSignedRationalArray)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(StringTags))] public void ExifStringTests(ExifTag tag) { const string expected = "ImageSharp"; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(0M)); Assert.True(value.TrySetValue(expected)); var typed = (ExifString)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(UndefinedTags))] public void ExifUndefinedTests(ExifTag tag) { const byte expected = byte.MaxValue; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue((int)expected)); Assert.True(value.TrySetValue(expected)); var typed = (ExifByte)value; Assert.Equal(expected, typed.Value); } [Theory] [MemberData(nameof(UndefinedArrayTags))] public void ExifUndefinedArrayTests(ExifTag tag) { byte[] expected = new[] { byte.MaxValue }; ExifValue value = ExifValues.Create(tag); Assert.False(value.TrySetValue(expected.ToString())); Assert.True(value.TrySetValue(expected)); var typed = (ExifByteArray)value; Assert.Equal(expected, typed.Value); } } }
35.125899
92
0.554378
[ "Apache-2.0" ]
asmodat/ImageSharp
tests/ImageSharp.Tests/Metadata/Profiles/Exif/Values/ExifValuesTests.cs
19,530
C#
using System; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using AutoMapper; using Moq; using tcs_service.Services; using tcs_service.Services.Interfaces; using Xunit; using WireMock.Server; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; using WireMock.Settings; using tcs_service_test.Helpers; using tcs_service.Helpers; namespace tcs_service_test.Services { public class LiveBannerServiceTest : IDisposable { private readonly WireMockServer server; private readonly IBannerService bannerApi; public LiveBannerServiceTest() { server = FluentMockServer.Start(new FluentMockServerSettings() { Urls = new[] { "http://localhost:9000/" } }); var httpClient = new HttpClient() { BaseAddress = new Uri("http://localhost:9000/") }; Mock<IHttpClientFactory> mockHttpFactory = new Mock<IHttpClientFactory>(); mockHttpFactory.Setup(x => x.CreateClient(It.IsAny<string>())) .Returns(() => httpClient); bannerApi = new LiveBannerService(mockHttpFactory.Object); } public void Dispose() { server.Dispose(); } [Theory] [InlineData("lbutche3@wvup.edu")] [InlineData("9109213123")] public async Task GetBannerInfo_StudentIdentifier_ShouldCallCorrectApiAndReturnBackStudentInfo(string identifier) { var bannerInfo = new BannerPersonInfo() { EmailAddress = identifier, WVUPID = Utils.ParseOrDefault(identifier, 11243213), FirstName = "Billy", LastName = "Loel", Teacher = false }; var cleanedIdentifier = identifier.Split("@")[0]; server .Given(Request.Create().WithPath($"/student/{cleanedIdentifier}").UsingGet()) .RespondWith( Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") .WithBodyAsJson(bannerInfo) ); var studentInfo = await bannerApi.GetBannerInfo(identifier); Assert.NotNull(studentInfo); Assert.False(studentInfo.Teacher); } [Theory] [InlineData("teacher@wvup.edu")] [InlineData("112452354")] public async Task GetBannerInfo_TeacherEmail_ShouldCallCorrectApiAndReturnBackTeacherInfo(string identifier) { var bannerInfo = new BannerPersonInfo() { EmailAddress = identifier, WVUPID = Utils.ParseOrDefault(identifier, 11243213), FirstName = "Barry", LastName = "LoppySomph", Teacher = true }; var cleanedIdentifier = identifier.Split("@")[0]; server .Given(Request.Create().WithPath($"/teacher/{cleanedIdentifier}").UsingGet()) .RespondWith( Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") .WithBodyAsJson(bannerInfo) ); var teacherInfo = await bannerApi.GetBannerInfo(identifier); Assert.NotNull(teacherInfo); Assert.True(teacherInfo.Teacher); } [Fact] public async Task GetBannerInfo_PersonNotFound_ShouldThrowTCSExceptionWithMessage() { var email = "whoami@wvup.edu"; var cleanedEmail = email.Split("@")[0]; server .Given(Request.Create().WithPath($"/teacher/{cleanedEmail}").UsingGet()) .RespondWith( Response.Create() .WithStatusCode(404) .WithHeader("Content-Type", "application/json") ); var exception = await Assert.ThrowsAsync<TCSException>(async () => await bannerApi.GetBannerInfo(email)); Assert.Equal($"Could not find information on: {email}", exception.Message); } [Fact] public async Task GetBannerInfo_BannerIsDown_ShouldThrowTCSExceptionWithMessage() { var email = "whoami@wvup.edu"; var cleanedEmail = email.Split("@")[0]; server .Given(Request.Create().WithPath($"/teacher/{cleanedEmail}").UsingGet()) .RespondWith( Response.Create() .WithStatusCode(503) .WithHeader("Content-Type", "application/json") ); var exception = await Assert.ThrowsAsync<TCSException>(async () => await bannerApi.GetBannerInfo(email)); Assert.Equal($"Banner is currently down", exception.Message); } [Fact] public async Task GetStudentGrade_ShouldCallCorrectApiAndReturnStudentGrade() { var studentId = 6789613; var semesterCode = 201901; var classCRN = 1476; server.Given(Request.Create() .WithPath($"/student/{studentId}/{semesterCode}/{classCRN}") .UsingGet()) .RespondWith( Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") .WithBodyAsJson(new { FinalGrade = "A", MidtermGrade = "B", CRN = classCRN, SubjectCode = "STEM", CourseNumber = "101" }) ); var result = await bannerApi.GetStudentGrade(studentId, classCRN, semesterCode); Assert.NotNull(result); Assert.Equal(classCRN, result.CRN); } [Fact] public async Task GetStudentGrade_BannerApiReturnsBack404_ShouldThrowTCSExceptionWithMessage() { var studentId = 6789613; var semesterCode = 201901; var classCRN = 1476; server.Given(Request.Create() .WithPath($"/student/{studentId}/{semesterCode}/{classCRN}") .UsingGet()) .RespondWith( Response.Create() .WithStatusCode(404) ); var exception = await Assert.ThrowsAsync<TCSException>(async () => await bannerApi.GetStudentGrade(studentId, classCRN, semesterCode)); Assert.Equal($"No information found for {studentId} during semester {semesterCode} for class {classCRN}", exception.Message); } [Fact] public async Task GetStudentGrade_BannerApiReturnsBadStatusCode_ShouldThrowTCSException() { var studentId = 6789613; var semesterCode = 201901; var classCRN = 1476; server.Given(Request.Create() .WithPath($"/student/{studentId}/{semesterCode}/{classCRN}") .UsingGet()) .RespondWith( Response.Create() .WithStatusCode(500) ); var exception = await Assert.ThrowsAsync<TCSException>(async () => await bannerApi.GetStudentGrade(studentId, classCRN, semesterCode)); Assert.Equal($"Banner is currently down", exception.Message); } } }
35.745098
147
0.578168
[ "MIT" ]
a2937/wvup-tcs
backend/tcs-service-test/Services/LiveBannerService.test.cs
7,292
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 ebs-2019-11-02.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.EBS { /// <summary> /// Configuration for accessing Amazon EBS service /// </summary> public partial class AmazonEBSConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.7.0.49"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonEBSConfig() { this.AuthenticationServiceName = "ebs"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "ebs"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2019-11-02"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
25.5375
101
0.578561
[ "Apache-2.0" ]
mikemissakian/aws-sdk-net
sdk/src/Services/EBS/Generated/AmazonEBSConfig.cs
2,043
C#
using Raider.Collections; using Raider.Infrastructure; using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace Raider.Data { public class BatchWriter<T> : IBatchWriter<T>, IDisposable { /// <summary> /// Constant used to indicate that the internal queue shouldn't be limited. /// </summary> public const int NoQueueLimit = BoundedConcurrentQueue<T>.Unbounded; private readonly int _batchSizeLimit; private readonly bool _eagerlyEmitFirstEvent; private readonly BoundedConcurrentQueue<T> _queue; private readonly BatchedConnectionStatus _status; private readonly Queue<T> _waitingBatch = new Queue<T>(); private readonly Action<string, object?, object?, object?>? _errorLogger; private readonly Func<T, bool>? _includeCallBack; private readonly Func<IEnumerable<T>, CancellationToken, Task<ulong>>? _writeBatchCallback; private readonly object _stateLock = new object(); private readonly PortableTimer _timer; private bool _unloading; private bool _started; public BatchWriter( IBatchWriterOptions? options, Action<string, object?, object?, object?>? errorLogger = null) // errorLogger = Action<format, arg0, arg1, arg2> { if (options == null) options = new BatchWriterOptions(); if (options.BatchSizeLimit <= 0) throw new ArgumentOutOfRangeException(nameof(options), "The batch size limit must be greater than zero."); if (options.Period <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(options), "The period must be greater than zero."); if (options.MinimumBackoffPeriod <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(options), "The MinimumBackoffPeriod must be greater than zero."); if (options.MaximumBackoffInterval <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(options), "The MaximumBackoffInterval must be greater than zero."); _errorLogger = errorLogger; _batchSizeLimit = options.BatchSizeLimit; _queue = new BoundedConcurrentQueue<T>(options.QueueLimit); _status = new BatchedConnectionStatus(options); _eagerlyEmitFirstEvent = options.EagerlyEmitFirstEvent; _timer = new PortableTimer(cancel => OnTick()); } public BatchWriter( Func<T, bool>? includeCallBack, Func<IEnumerable<T>, CancellationToken, Task<ulong>>? writeBatchCallback, BatchWriterOptions? options, Action<string, object?, object?, object?>? errorLogger = null) // errorLogger = Action<format, arg0, arg1, arg2> : this(options, errorLogger) { _includeCallBack = includeCallBack; _writeBatchCallback = writeBatchCallback; } public virtual bool Include(T obj) { if (_includeCallBack == null) return true; return _includeCallBack(obj); } protected virtual Task<ulong> WriteBatchAsync(IEnumerable<T> batch, CancellationToken cancellationToken = default) { if (_writeBatchCallback == null) throw new InvalidOperationException($"{nameof(_writeBatchCallback)} == null"); return _writeBatchCallback(batch, cancellationToken); } private void SetTimer(TimeSpan interval) { _timer.Start(interval); } /// <summary> /// Emit the provided log event to the sink. If the sink is being disposed or /// the app domain unloaded, then the event is ignored. /// </summary> /// <param name="obj">Log event to emit.</param> /// <exception cref="ArgumentNullException">The event is null.</exception> /// <remarks> /// The sink implements the contract that any events whose Emit() method has /// completed at the time of sink disposal will be flushed (or attempted to, /// depending on app domain state). /// </remarks> [DebuggerHidden] [DebuggerStepThrough] public void Write(T obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); if (_unloading) return; if (!_started) { lock (_stateLock) { if (_unloading) return; if (!_started) { _queue.TryEnqueue(obj); _started = true; if (_eagerlyEmitFirstEvent) { // Special handling to try to get the first event across as quickly // as possible to show we're alive! SetTimer(TimeSpan.Zero); } else { SetTimer(_status.NextInterval); } return; } } } _queue.TryEnqueue(obj); } [DebuggerHidden] [DebuggerStepThrough] private async Task OnTick() { try { bool batchWasFull; do { while (_waitingBatch.Count < _batchSizeLimit && _queue.TryDequeue(out T? next)) { if (next != null && Include(next)) _waitingBatch.Enqueue(next); } if (_waitingBatch.Count == 0) return; await WriteBatchAsync(_waitingBatch); batchWasFull = _waitingBatch.Count >= _batchSizeLimit; _waitingBatch.Clear(); _status.MarkSuccess(); } while (batchWasFull); // Otherwise, allow the period to elapse } catch (Exception ex) { _errorLogger?.Invoke("Exception while emitting periodic batch from {0}: {1}", this, ex, null); _status.MarkFailure(); } finally { if (_status.ShouldDropBatch) _waitingBatch.Clear(); if (_status.ShouldDropQueue) { while (_queue.TryDequeue(out _)) { } } lock (_stateLock) { if (!_unloading) SetTimer(_status.NextInterval); } } } private bool disposed; /// <summary> /// Free resources held by the sink. /// </summary> /// <param name="disposing">If true, called because the object is being disposed; if false, /// the object is being disposed from the finalizer.</param> protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { CloseAndFlush(); } disposed = true; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void CloseAndFlush() { lock (_stateLock) { if (!_started || _unloading) return; _unloading = true; } _timer.Dispose(); // This is the place where SynchronizationContext.Current is unknown and can be != null // so we prevent possible deadlocks here for sync-over-async downstream implementations ResetSyncContextAndWait(OnTick); } private static void ResetSyncContextAndWait(Func<Task> taskFactory) { var prevContext = SynchronizationContext.Current; SynchronizationContext.SetSynchronizationContext(null); try { taskFactory().Wait(); } finally { SynchronizationContext.SetSynchronizationContext(prevContext); } } } }
26.810277
116
0.691729
[ "Apache-2.0" ]
raider-net/Raider
src/Raider.Core/Data/BatchWriter.cs
6,785
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Channels; using System.Threading.Tasks; using Bizanc.io.Matching.Core.Domain; using Bizanc.io.Matching.Core.Repository; using Raven.Client.Documents; namespace Bizanc.io.Matching.Infra.Repository { public class TradeRepository : BaseRepository<Trade>, ITradeRepository { public async Task<ChannelReader<Trade>> ListAscending(string asset, DateTime from) { using (var s = Store.OpenAsyncSession()) { var query = s.Query<Trade>().Where(t => t.Asset == asset && t.Timestamp >= from).OrderBy(t => t.Timestamp); var channel = Channel.CreateUnbounded<Trade>(); await StreamResult(s, query, channel); return channel.Reader; } } public async Task<List<Trade>> ListDescending(string asset, DateTime from, int limit) { var result = new List<Trade>(); using (var s = Store.OpenAsyncSession()) { var query = s.Query<Trade>().Where(t => t.Asset == asset && t.Timestamp >= from).Take(limit).OrderByDescending(t => t.Timestamp); using (var stream = await s.Advanced.StreamAsync(query)) { while (await stream.MoveNextAsync()) result.Add(stream.Current.Document); } } return result; } } }
34.744186
145
0.585676
[ "MIT" ]
Menniti/Bizanc.io.Core
Bizanc.io.Matching.Infra/Repository/TradeRepository.cs
1,494
C#
using System; using System.Drawing; namespace Moway.Project.GraphicProject.Actions.Free { public class FreeTool : Tool { public FreeTool(string key) { this.index = Convert.ToInt32(Free.Index); this.key = key; this.text = Free.ToolText; this.type = ToolType.Basic; if (Free.Type == "Advanced") this.type = ToolType.Advanced; this.group = Free.Group; this.icon = Free.ToolIcon; this.toolTipText = Free.ToolTipText; } } }
25.863636
53
0.551845
[ "MIT" ]
Bizintek/mOway_SW_mOwayWorld
mOway_SW_mOwayWorld/MowayProject/GraphicProject/Actions/Free/FreeTool.cs
571
C#
public class StatModifier { public readonly float Value; public readonly StatModType Type; public readonly int Order; public readonly object Source; // Added this variable // "Main" constructor. Requires all variables. public StatModifier(float value, StatModType type, int order, object source) // Added "source" input parameter { Value = value; Type = type; Order = order; Source = source; // Assign Source to our new input parameter } // Requires Value and Type. Calls the "Main" constructor and sets Order and Source to their default values: (int)type and null, respectively. public StatModifier(float value, StatModType type) : this(value, type, (int)type, null) { } // Requires Value, Type and Order. Sets Source to its default value: null public StatModifier(float value, StatModType type, int order) : this(value, type, order, null) { } // Requires Value, Type and Source. Sets Order to its default value: (int)Type public StatModifier(float value, StatModType type, object source) : this(value, type, (int)type, source) { } } public enum StatModType { Flat = 100, Percent = 200, PercentMult = 300, }
40.096774
146
0.672566
[ "MIT" ]
Vumsy101/CharacterStatsPrototype
Assets/Scripts/Loot&StatsScripts/StatModifier.cs
1,245
C#
namespace Our.Umbraco.PersonalisationGroups.Providers.GeoLocation { public enum CountryCodeProvider { MaxMindDatabase, CdnHeader } }
18
66
0.697531
[ "MIT" ]
AndyButland/UmbracoPersonalisationGroupsCore
PersonalisationGroups/Providers/GeoLocation/CountryCodeProvider.cs
164
C#
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; namespace BasicServerHTTPlistener { internal class Program { private static void Main(string[] args) { if (!HttpListener.IsSupported) { Console.WriteLine("A more recent Windows version is required to use the HttpListener class."); return; } // Create a listener. HttpListener listener = new HttpListener(); // Trap Ctrl-C and exit Console.CancelKeyPress += delegate { listener.Stop(); System.Environment.Exit(0); }; // Add the prefixes. if (args.Length != 0) { foreach (string s in args) { listener.Prefixes.Add(s); // don't forget to authorize access to the TCP/IP addresses localhost:xxxx and localhost:yyyy // with netsh http add urlacl url=http://localhost:xxxx/ user="Tout le monde" // and netsh http add urlacl url=http://localhost:yyyy/ user="Tout le monde" // user="Tout le monde" is language dependent, use user=Everyone in english } } else { Console.WriteLine("Syntax error: the call must contain at least one web server url as argument"); } listener.Start(); foreach (string s in args) { Console.WriteLine("Listening for connections on " + s); } while (true) { // Note: The GetContext method blocks while waiting for a request. HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; string documentContents; using (Stream receiveStream = request.InputStream) { using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) { documentContents = readStream.ReadToEnd(); } } Console.WriteLine($"Received request for {request.Url}"); Console.WriteLine(documentContents); // Obtain a response object. HttpListenerResponse response = context.Response; string res; int i = 0; foreach (HttpRequestHeader headerEnum in Enum.GetValues(typeof(HttpRequestHeader))) { Console.WriteLine(i + " " + headerEnum); i++; } // Construct a response. string responseString = "<HTML><BODY>" + DisplayHeader(request) + "</BODY></HTML>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); // Get a response stream and write the response to it. response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); // You must close the output stream. output.Close(); } // Httplistener neither stop ... // listener.Stop(); } public static string DisplayHeader(HttpListenerRequest request) { System.Collections.Specialized.NameValueCollection headers = request.Headers; string res = ""; foreach (string key in headers.AllKeys) { string[] values = headers.GetValues(key); if (values.Length > 0) { Console.WriteLine("{0} : ", key); res += "<h4>" + key + " :</h4>"; foreach (string value in values) { Console.WriteLine(" - {0}", value); res += " - " + value + "</br>"; } } else { Console.WriteLine("No value in the header."); res = "No value in the header."; } } return res; } } }
36.838983
114
0.494594
[ "MIT" ]
NicaiseAlex/eiin839
TD1/HttpListener/BasicServerHttpListener/Program.cs
4,349
C#
using JetBrains.Annotations; namespace PowerAssert.Infrastructure.Nodes { class ConstantNode : Node { [NotNull] public string Text { get; set; } [CanBeNull] public string Value { get; set; } internal override void Walk(NodeWalker walker, int depth, bool wrap) { walker(Text, Value, depth); } } }
21.055556
76
0.585752
[ "MIT" ]
PowerAssert/PowerAssert.Net
PowerAssert/Infrastructure/Nodes/ConstantNode.cs
381
C#
using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace JasonSoft.Reflection { public static class ReflectionExtension { private const BindingFlags BINDING_FLAGS = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; private static readonly IDictionary<String, FastSetHandler> setHandlerCache = new Dictionary<String, FastSetHandler>(); private static readonly IDictionary<String, FastGetHandler> getHandlerCache = new Dictionary<String, FastGetHandler>(); private static readonly IDictionary<String, FastInstanceHandler> instanceHandlerCache = new Dictionary<String, FastInstanceHandler>(); private static readonly IDictionary<String, FastInstanceWithParameterHandler> instanceWithParameterHandlerCache = new Dictionary<String, FastInstanceWithParameterHandler>(); public static object CreaetInstance(this Type source) { lock(instanceHandlerCache) { FastInstanceHandler fastInstanceHandler = null; String key = source.FullName; if(instanceHandlerCache.ContainsKey(key)) { fastInstanceHandler = instanceHandlerCache[key]; } else { fastInstanceHandler = DynamicMethodHelper.CreateInstanceHandler(source); instanceHandlerCache.Add(key, fastInstanceHandler); } return fastInstanceHandler.Invoke(); } } public static T GetField<T>(this Object source, string fieldName) { if (fieldName.IsNullOrEmpty()) throw new ArgumentNullException("fieldName","fieldName of parameter can't be null"); Type targetType = source.GetType(); String key = targetType.FullName + "|" + fieldName; lock (getHandlerCache) { FastGetHandler fastGetHandler = null; if (getHandlerCache.ContainsKey(key)) { fastGetHandler = getHandlerCache[key]; } else { FieldInfo fieldInfo = targetType.GetField(fieldName, BINDING_FLAGS); if (fieldInfo == null) throw new InvalidOperationException("field name is not found"); fastGetHandler = DynamicMethodHelper.CreateFastGetHandler(fieldInfo); getHandlerCache.Add(key, fastGetHandler); } return (T)fastGetHandler(source); } } public static void SetField(this object source, string fieldName, object value) { if (fieldName.IsNullOrEmpty()) throw new ArgumentNullException("fieldName", "fieldName of parameter can't be null"); Type targetType = source.GetType(); String key = targetType.FullName + "|" + fieldName; lock (setHandlerCache) { FastSetHandler setHandler = null; if (setHandlerCache.ContainsKey(key)) { setHandler = setHandlerCache[key]; } else { FieldInfo fieldInfo = targetType.GetField(fieldName, BINDING_FLAGS); if (fieldInfo == null) throw new InvalidOperationException("field name is not found"); setHandler = DynamicMethodHelper.CreateFastSetHandler(fieldInfo); setHandlerCache.Add(key, setHandler); } setHandler(source, value); } } public static Object GetProperty(this object source, string propertyName) { if (propertyName.IsNullOrEmpty()) throw new ArgumentNullException("propertyName"); Type targetType = source.GetType(); String key = targetType.FullName + "|" + propertyName; lock (getHandlerCache) { FastGetHandler fastGetHandler = null; if (getHandlerCache.ContainsKey(key)) { fastGetHandler = getHandlerCache[key]; } else { PropertyInfo propInfo = targetType.GetProperty(propertyName, BINDING_FLAGS); if (propInfo == null) throw new InvalidOperationException("property name is not found"); fastGetHandler = DynamicMethodHelper.CreateFastGetHandler(propInfo); getHandlerCache.Add(key, fastGetHandler); } return fastGetHandler(source); } } public static T GetProperty<T>(this object source, string propertyName) { return (T) source.GetProperty(propertyName); } public static void SetProperty(this object source, string propertyName, object value) { if (propertyName.IsNullOrEmpty()) throw new ArgumentNullException("propertyName"); Type targetType = source.GetType(); String key = targetType.FullName + "|" + propertyName; lock (setHandlerCache) { FastSetHandler setHandler = null; if (setHandlerCache.ContainsKey(key)) { setHandler = setHandlerCache[key]; } else { PropertyInfo propInfo = targetType.GetProperty(propertyName, BINDING_FLAGS); if (propInfo == null) throw new InvalidOperationException("property name is not found"); setHandler = DynamicMethodHelper.CreateFastSetHandler(propInfo); setHandlerCache.Add(key, setHandler); } setHandler(source, value); } } public static DirectoryInfo GetDirectory(this Assembly source) { return new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); } } }
36.642857
181
0.578622
[ "Apache-2.0" ]
JasonSoft/JasonSoft
JasonSoft.Core/Reflection/ReflectionExtension.cs
6,158
C#
/// <copyright file="GeometryGraph.cs" company="Eötvös Loránd University (ELTE)"> /// Copyright (c) 2011-2019 Roberto Giachetta. Licensed under the /// Educational Community 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://opensource.org/licenses/ECL-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. /// </copyright> /// <author>Roberto Giachetta</author> using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ELTE.AEGIS.Geometry { /// <summary> /// Represents a graph form of geometry in spatial coordinate space. /// </summary> public class GeometryGraph : Geometry, IGeometryGraph { #region Public types /// <summary> /// Represents a graph enumerator implementing breath-first search. /// </summary> public sealed class BreadthFirstEnumerator : IEnumerator<IGraphVertex> { #region Private fields private GeometryGraph _localGraph; private Int32 _localVersion; private Queue<IGraphVertex> _queue; private HashSet<IGraphVertex> _finishedVertices; private IGraphVertex _current; private Boolean _disposed; #endregion #region IEnumerator properties /// <summary> /// Gets the element at the current position of the enumerator. /// </summary> /// <value>The element at the current position of the enumerator.</value> public IGraphVertex Current { get { return _current; } } /// <summary> /// Gets the element at the current position of the enumerator. /// </summary> /// <value>The element at the current position of the enumerator.</value> object IEnumerator.Current { get { return _current; } } #endregion #region Constructors and destructor /// <summary> /// Initializes a new instance of the <see cref="BreadthFirstEnumerator" /> class. /// </summary> /// <param name="graph">The graph.</param> internal BreadthFirstEnumerator(GeometryGraph graph) { _localGraph = graph; _localVersion = graph._version; _queue = new Queue<IGraphVertex>(); _finishedVertices = new HashSet<IGraphVertex>(); _disposed = false; Reset(); } /// <summary> /// Finalizes an instance of the <see cref="BreadthFirstEnumerator" /> class. /// </summary> ~BreadthFirstEnumerator() { Dispose(false); } #endregion #region IEnumerator methods /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns><c>true</c> if the enumerator was successfully advanced to the next element; <c>false</c> if the enumerator has passed the end of the collection.</returns> /// <exception cref="System.ObjectDisposedException">The object is disposed.</exception> /// <exception cref="System.InvalidOperationException">The collection was modified after the enumerator was created.</exception> public Boolean MoveNext() { if (_disposed) throw new ObjectDisposedException(GetType().FullName); if (_localVersion != _localGraph._version) throw new InvalidOperationException("The collection was modified after the enumerator was created."); if (_finishedVertices.Count == _localGraph._vertexList.Count) { _current = null; return false; } if (_queue.Count == 0){ for (Int32 i = 0; i < _localGraph._vertexList.Count; i++) { if (!_finishedVertices.Contains(_localGraph._vertexList[i])) { _queue.Enqueue(_localGraph._vertexList[i]); break; } } } _current = _queue.Dequeue(); _finishedVertices.Add(_current); foreach (IGraphEdge edge in _localGraph.OutEdges(_current)) { if (!_finishedVertices.Contains(edge.Target)) { _queue.Enqueue(edge.Target); } } return true; } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> /// <exception cref="System.ObjectDisposedException">The object is disposed.</exception> /// <exception cref="System.InvalidOperationException">The collection was modified after the enumerator was created.</exception> public void Reset() { if (_disposed) throw new ObjectDisposedException(GetType().FullName); if (_localVersion != _localGraph._version) throw new InvalidOperationException("The collection was modified after the enumerator was created."); _queue.Clear(); _finishedVertices.Clear(); _current = null; } #endregion #region IDisposeable methods /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (_disposed) return; Dispose(true); GC.SuppressFinalize(this); } #endregion #region Private methods /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <param name="disposing">A value indicating whether disposing is performed on the object.</param> private void Dispose(Boolean disposing) { _disposed = true; if (disposing) { _localGraph = null; _finishedVertices.Clear(); _finishedVertices = null; _queue.Clear(); _queue = null; _current = null; } } #endregion } /// <summary> /// Represents a graph enumerator implementing depth-first search. /// </summary> public sealed class DepthFirstEnumerator : IEnumerator<IGraphVertex> { #region Private fields private GeometryGraph _localGraph; private Int32 _localVersion; private Stack<IGraphVertex> _stack; private HashSet<IGraphVertex> _finishedVertices; private IGraphVertex _current; private Boolean _disposed; #endregion #region IEnumerator properties /// <summary> /// Gets the element at the current position of the enumerator. /// </summary> /// <value> /// The element at the current position of the enumerator. /// </value> public IGraphVertex Current { get { return _current; } } /// <summary> /// Gets the element at the current position of the enumerator. /// </summary> /// <value> /// The element at the current position of the enumerator.- /// </value> object IEnumerator.Current { get { return _current; } } #endregion #region Constructors and destructor /// <summary> /// Initializes a new instance of the <see cref="DepthFirstEnumerator" /> class. /// </summary> /// <param name="graph">The graph.</param> internal DepthFirstEnumerator(GeometryGraph localGraph) { _localGraph = localGraph; _localVersion = localGraph._version; _stack = new Stack<IGraphVertex>(); _finishedVertices = new HashSet<IGraphVertex>(); _disposed = false; Reset(); } /// <summary> /// Finalizes an instance of the <see cref="DepthFirstEnumerator" /> class. /// </summary> ~DepthFirstEnumerator() { Dispose(false); } #endregion #region IEnumerator methods /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns><c>true</c> if the enumerator was successfully advanced to the next element; <c>false</c> if the enumerator has passed the end of the collection.</returns> /// <exception cref="System.ObjectDisposedException">The object is disposed.</exception> /// <exception cref="System.InvalidOperationException">The collection was modified after the enumerator was created.</exception> public Boolean MoveNext() { if (_disposed) throw new ObjectDisposedException(GetType().FullName); if (_localVersion != _localGraph._version) throw new InvalidOperationException("The collection was modified after the enumerator was created."); if (_finishedVertices.Count == _localGraph._vertexList.Count) { _current = null; return false; } if (_stack.Count == 0) { for (Int32 i = 0; i < _localGraph._vertexList.Count; i++) { if (!_finishedVertices.Contains(_localGraph._vertexList[i])) { _stack.Push(_localGraph._vertexList[i]); break; } } } _current = _stack.Pop(); _finishedVertices.Add(_current); foreach (IGraphEdge edge in _localGraph.OutEdges(_current)) { if (!_finishedVertices.Contains(edge.Target)) { _stack.Push(edge.Target); } } return true; } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> /// <exception cref="System.ObjectDisposedException">The object is disposed.</exception> /// <exception cref="System.InvalidOperationException">The collection was modified after the enumerator was created.</exception> public void Reset() { if (_disposed) throw new ObjectDisposedException(GetType().FullName); if (_localVersion != _localGraph._version) throw new InvalidOperationException("The collection was modified after the enumerator was created."); _stack.Clear(); _finishedVertices.Clear(); _current = null; } #endregion #region IDisposeable methods /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (_disposed) return; Dispose(true); GC.SuppressFinalize(this); } #endregion #region Private methods /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <param name="disposing">A value indicating whether disposing is performed on the object.</param> private void Dispose(Boolean disposing) { _disposed = true; if (disposing) { _localGraph = null; _finishedVertices.Clear(); _finishedVertices = null; _stack.Clear(); _stack = null; _current = null; } } #endregion } #endregion #region Protected types /// <summary> /// Represents an equality comparer for vertices. /// </summary> protected class VertexEqualityComparer : IEqualityComparer<IGraphVertex> { #region IEqualityComparer methods /// <summary> /// Determines whether the specified objects are equal. /// </summary> /// <param name="x">The first object of type <see cref="GraphVertex" /> to compare.</param> /// <param name="y">The second object of type <see cref="GraphVertex" /> to compare.</param> /// <returns><c>true</c> if the specified objects are equal; otherwise, <c>false</c>.</returns> public Boolean Equals(IGraphVertex x, IGraphVertex y) { if (ReferenceEquals(x, null)) return ReferenceEquals(y, null); if (ReferenceEquals(x, y)) return true; return false; } /// <summary> /// Returns a hash code for the specified object. /// </summary> /// <param name="obj">The <see cref="GraphVertex" /> for which a hash code is to be returned.</param> /// <returns>A hash code for the specified object.</returns> /// <exception cref="System.ArgumentNullException">The type of obj is a reference type and obj is null.</exception> public Int32 GetHashCode(IGraphVertex obj) { if (obj == null) throw new ArgumentNullException("obj", "The type of obj is a reference type and obj is null."); return obj.GetHashCode(); } #endregion } /// <summary> /// Represents an equality comparer for edges. /// </summary> protected class EdgeEqualityComparer : IEqualityComparer<IGraphEdge> { #region IEqualityComparer methods /// <summary> /// Determines whether the specified objects are equal. /// </summary> /// <param name="x">The first object of type <see cref="GraphEdge" /> to compare.</param> /// <param name="y">The second object of type <see cref="GraphEdge" /> to compare.</param> /// <returns><c>true</c> if the specified objects are equal; otherwise, <c>false</c>.</returns> public Boolean Equals(IGraphEdge x, IGraphEdge y) { if (ReferenceEquals(x, null)) return ReferenceEquals(y, null); if (ReferenceEquals(x, y)) return true; return false; } /// <summary> /// Returns a hash code for the specified object. /// </summary> /// <param name="obj">The <see cref="GraphEdge" /> for which a hash code is to be returned.</param> /// <returns>A hash code for the specified object.</returns> /// <exception cref="System.ArgumentNullException">The type of obj is a reference type and obj is null.</exception> public Int32 GetHashCode(IGraphEdge obj) { if (obj == null) throw new ArgumentNullException("obj", "The type of obj is a reference type and obj is null."); return obj.GetHashCode(); } #endregion } #endregion #region Private static fields /// <summary> /// The empty edge set. This field is read-only. /// </summary> private static readonly ISet<IGraphEdge> EmptyEdgeSet = new HashSet<IGraphEdge>(); #endregion #region Protected fields /// <summary> /// The list of vertices. /// </summary> protected List<IGraphVertex> _vertexList; /// <summary> /// The list of edges. /// </summary> protected List<IGraphEdge> _edgeList; /// <summary> /// The version of the graph. /// </summary> protected Int32 _version; /// <summary> /// The adjacency dictionary of the source vertices. /// </summary> protected Dictionary<IGraphVertex, HashSet<IGraphEdge>> _adjacencySource; /// <summary> /// The adjacency dictionary of the target vertices. /// </summary> protected Dictionary<IGraphVertex, HashSet<IGraphEdge>> _adjacencyTarget; /// <summary> /// The comparer used for determining the equality of vertices. /// </summary> protected IEqualityComparer<IGraphVertex> _vertexEqualityComparer; /// <summary> /// The comparer used for determining the equality of edges. /// </summary> protected IEqualityComparer<IGraphEdge> _edgeEqualityComparer; #endregion #region IGeometry properties /// <summary> /// Gets the general name of the geometry. /// </summary> /// <value>The general name of the specific geometry.</value> public override String Name { get { return "Geometry graph"; } } /// <summary> /// Gets the inherent dimension of the geometry. /// </summary> public override Int32 Dimension { get { if (_adjacencySource.Count == 0) return 0; Double sourceDimensionValue = _adjacencySource.First().Key.Coordinate.Z; Boolean sourceIs2D = _adjacencySource.All(p => p.Key.Coordinate.Z == sourceDimensionValue); if (!sourceIs2D) return 3; return 2; } } /// <summary> /// Gets the centroid of the geometry. /// </summary> public override Coordinate Centroid { get { Double centroidX = 0, centroidY = 0, centroidZ = 0; Int32 count = 0; foreach (KeyValuePair<IGraphVertex, HashSet<IGraphEdge>> kvp in _adjacencySource) { centroidX += kvp.Key.Coordinate.X; centroidY += kvp.Key.Coordinate.Y; centroidZ += kvp.Key.Coordinate.Z; ++count; foreach (IGraphEdge edge in kvp.Value) { centroidX += (edge.Source.Coordinate.X + edge.Target.Coordinate.X) / 2; centroidY += (edge.Source.Coordinate.Y + edge.Target.Coordinate.Y) / 2; centroidZ += (edge.Source.Coordinate.Z + edge.Target.Coordinate.Z) / 2; ++count; } } centroidX /= count; centroidY /= count; centroidZ /= count; return PrecisionModel.MakePrecise(new Coordinate(centroidX, centroidY, centroidZ)); } } /// <summary> /// Gets a value indicating whether the geometry is empty. /// </summary> /// <value><c>true</c> if the geometry is considered to be empty; otherwise, <c>false</c>.</value> public override Boolean IsEmpty { get { return _adjacencySource.Count == 0; } } /// <summary> /// Gets a value indicating whether the geometry is simple. /// </summary> public override Boolean IsSimple { get { HashSet<Coordinate> nodeCoordinatePool = new HashSet<Coordinate>(); foreach (KeyValuePair<IGraphVertex, HashSet<IGraphEdge>> item in _adjacencySource) { if (nodeCoordinatePool.Contains(item.Key.Coordinate)) return false; else nodeCoordinatePool.Add(item.Key.Coordinate); HashSet<Coordinate> edgeCoordinatePool = new HashSet<Coordinate>(); foreach (IGraphEdge edge in item.Value) { if (_vertexEqualityComparer.Equals(edge.Source, edge.Target)) return false; if (edgeCoordinatePool.Contains(edge.Target.Coordinate)) return false; else edgeCoordinatePool.Add(item.Key.Coordinate); } } return true; } } /// <summary> /// Gets a value indicating whether the geometry is simple. /// </summary> /// <value><c>true</c> if the geometry is considered to be simple; otherwise, <c>false</c>.</value> public override Boolean IsValid { get { return _adjacencySource.Keys.All(vertex => vertex.Coordinate.IsValid); } } #endregion #region IGeometryGraph properties /// <summary> /// Gets the number of vertices. /// </summary> /// <value>The number of vertices in the graph.</value> public virtual Int32 VertexCount { get { return _adjacencySource.Count; } } /// <summary> /// Gets the number of edges. /// </summary> /// <value>The number of edges in the graph.</value> public virtual Int32 EdgeCount { get { return _edgeList != null ? _edgeList.Count : _adjacencySource.Values.Sum(hashSet => hashSet.Count); } } /// <summary> /// Gets the list of vertices. /// </summary> /// <value>The read-only list of vertices.</value> public virtual IList<IGraphVertex> Vertices { get { return _vertexList.AsReadOnly(); } } /// <summary> /// Gets the list of edges. /// </summary> /// <value>The read-only list of edges.</value> public virtual IList<IGraphEdge> Edges { get { if (_edgeList == null) { _edgeList = new List<IGraphEdge>(); foreach (HashSet<IGraphEdge> set in _adjacencySource.Values) { _edgeList.AddRange(set); } } return _edgeList.AsReadOnly(); } } /// <summary> /// Gets the <see cref="IEqualityComparer{IGraphVertex}" /> object used by the graph for comparing vertices. /// </summary> /// <value>The <see cref="IEqualityComparer{IGraphVertex}" /> object used by the graph for comparing vertices.</value> public IEqualityComparer<IGraphVertex> VertexComparer { get { return _vertexEqualityComparer; } } /// <summary> /// Gets the <see cref="IEqualityComparer{IGraphEdge}" /> object used by the graph for comparing edges. /// </summary> /// <value>The <see cref="IEqualityComparer{IGraphEdge}" /> object used by the graph for comparing edges.</value> public IEqualityComparer<IGraphEdge> EdgeComparer { get { return _edgeEqualityComparer; } } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="GeometryGraph" /> class. /// </summary> /// <param name="precisionModel">The precision model.</param> /// <param name="referenceSystem">The reference system.</param> /// <param name="metadata">The metadata.</param> public GeometryGraph(PrecisionModel precisionModel, IReferenceSystem referenceSystem, IDictionary<String, Object> metadata) : this(null, null, precisionModel, referenceSystem, metadata) { } /// <summary> /// Initializes a new instance of the <see cref="GeometryGraph" /> class. /// </summary> /// <param name="vertexEqualityComparer">The vertex equality comparer.</param> /// <param name="edgeEqualityComparer">The edge equality comparer.</param> /// <param name="precisionModel">The precision model.</param> /// <param name="referenceSystem">The reference system.</param> /// <param name="metadata">The metadata.</param> public GeometryGraph(IEqualityComparer<IGraphVertex> vertexEqualityComparer, IEqualityComparer<IGraphEdge> edgeEqualityComparer, PrecisionModel precisionModel, IReferenceSystem referenceSystem, IDictionary<String, Object> metadata) : base(precisionModel, referenceSystem, metadata) { _vertexEqualityComparer = vertexEqualityComparer ?? new VertexEqualityComparer(); _edgeEqualityComparer = edgeEqualityComparer ?? new EdgeEqualityComparer(); _version = 0; _vertexList = new List<IGraphVertex>(); _edgeList = null; _adjacencySource = new Dictionary<IGraphVertex, HashSet<IGraphEdge>>(_vertexEqualityComparer); _adjacencyTarget = new Dictionary<IGraphVertex, HashSet<IGraphEdge>>(_vertexEqualityComparer); } /// <summary> /// Initializes a new instance of the <see cref="GeometryGraph" /> class. /// </summary> /// <param name="factory">The geometry factory.</param> /// <param name="metadata">The metadata.</param> /// <exception cref="System.ArgumentNullException">The factory is null.</exception> /// <exception cref="System.ArgumentException">The specified factory is invalid.</exception> public GeometryGraph(IGeometryFactory factory, IDictionary<String, Object> metadata) : this(null, null, factory, metadata) { } /// <summary> /// Initializes a new instance of the <see cref="GeometryGraph" /> class. /// </summary> /// <param name="vertexEqualityComparer">The vertex equality comparer.</param> /// <param name="edgeEqualityComparer">The edge equality comparer.</param> /// <param name="factory">The geometry factory.</param> /// <param name="metadata">The metadata.</param> /// <exception cref="System.ArgumentNullException">The factory is null.</exception> /// <exception cref="System.ArgumentException">The specified factory is invalid.</exception> public GeometryGraph(IEqualityComparer<IGraphVertex> vertexEqualityComparer, IEqualityComparer<IGraphEdge> edgeEqualityComparer, IGeometryFactory factory, IDictionary<String, Object> metadata) : base(factory, metadata) { if (!factory.ContainsFactory<IGeometryGraphFactory>() || !(factory.GetFactory<IGeometryGraphFactory>() is GeometryGraphFactory)) throw new ArgumentException("The specified factory is invalid.", "factory"); _vertexEqualityComparer = vertexEqualityComparer ?? new VertexEqualityComparer(); _edgeEqualityComparer = edgeEqualityComparer ?? new EdgeEqualityComparer(); _version = 0; _vertexList = new List<IGraphVertex>(); _edgeList = null; _adjacencySource = new Dictionary<IGraphVertex, HashSet<IGraphEdge>>(_vertexEqualityComparer); _adjacencyTarget = new Dictionary<IGraphVertex, HashSet<IGraphEdge>>(_vertexEqualityComparer); } #endregion #region IGeometryGraph methods /// <summary> /// Returns the outgoing edges of a vertex. /// </summary> /// <param name="vertex">The vertex.</param> /// <returns>The read-only set containing edges with <paramref="vertex"> as source.</returns> public virtual ISet<IGraphEdge> OutEdges(IGraphVertex vertex) { return Contains(vertex) ? _adjacencySource[vertex].AsReadOnly() : EmptyEdgeSet.AsReadOnly(); } /// <summary> /// Returns the incoming edges of a vertex. /// </summary> /// <param name="vertex">The vertex.</param> /// <returns>The read-only set containing edges with <paramref="vertex"> as target.</returns> public virtual ISet<IGraphEdge> InEdges(IGraphVertex vertex) { return Contains(vertex) ? _adjacencyTarget[vertex].AsReadOnly() : EmptyEdgeSet.AsReadOnly(); } /// <summary> /// Adds a new vertex to a graph. /// </summary> /// <param name="coordinate">The coordinate of the vertex.</param> /// <returns>The vertex created at the <paramref name="coordinate" />.</returns> public virtual IGraphVertex AddVertex(Coordinate coordinate) { return AddVertex(PrecisionModel.MakePrecise(coordinate), null); } /// <summary> /// Adds a new vertex to a graph. /// </summary> /// <param name="coordinate">The coordinate of the vertex.</param> /// <param name="metadata">The metadata.</param> /// <returns>The vertex created at the <paramref name="coordinate" />.</returns> public virtual IGraphVertex AddVertex(Coordinate coordinate, IDictionary<String, Object> metadata) { GraphVertex vertex = new GraphVertex(this, PrecisionModel.MakePrecise(coordinate), metadata); if (_adjacencySource.ContainsKey(vertex)) return null; _vertexList.Add(vertex); _adjacencySource.Add(vertex, new HashSet<IGraphEdge>(_edgeEqualityComparer)); _adjacencyTarget.Add(vertex, new HashSet<IGraphEdge>(_edgeEqualityComparer)); _version++; OnGeometryChanged(); return vertex; } /// <summary> /// Returns a vertex at a specified coordinate. /// </summary> /// <param name="coordinate">The coordinate.</param> /// <returns>The vertex located at the <paramref name="coordinate" /> if any; otherwise, <c>null</c>.</returns> public virtual IGraphVertex GetVertex(Coordinate coordinate) { coordinate = PrecisionModel.MakePrecise(coordinate); return _vertexList.FirstOrDefault(t => t.Coordinate.Equals(coordinate)); } /// <summary> /// Returns all vertices located at a specified coordinate. /// </summary> /// <param name="coordinate">The coordinate.</param> /// <returns>The list of vertices located at the <paramref name="coordinate" />.</returns> public virtual IList<IGraphVertex> GetAllVertices(Coordinate coordinate) { coordinate = PrecisionModel.MakePrecise(coordinate); return _vertexList.Where(t => t.Coordinate.Equals(coordinate)).ToList<IGraphVertex>(); } /// <summary> /// Determines whether the graph contains the specified coordinate. /// </summary> /// <param name="vertex">The vertex.</param> /// <returns><c>true</c> if the graph contains the <paramref name="vertex" />; otherwise, <c>false</c>.</returns> /// <exception cref="System.ArgumentNullException">The vertex is null.</exception> public virtual Boolean Contains(IGraphVertex vertex) { if (vertex == null) throw new ArgumentNullException("vertex", "The vertex is null."); return (vertex is GraphVertex) && (vertex.Graph == this) && _adjacencySource.ContainsKey(vertex); } /// <summary> /// Adds a new edge to the graph. /// </summary> /// <param name="source">The source coordinate.</param> /// <param name="target">The target coordinate.</param> /// <returns>The edge created between <paramref name="source" /> and <paramref name="target" /> vertices.</returns> public virtual IGraphEdge AddEdge(Coordinate source, Coordinate target) { return AddEdge(source, target, null); } /// <summary> /// Adds a new edge to the graph. /// </summary> /// <param name="source">The source coordinate.</param> /// <param name="target">The target coordinate.</param> /// <param name="metadata">The metadata.</param> /// <returns>The edge created between <paramref name="source" /> and <paramref name="target" /> vertices.</returns> public virtual IGraphEdge AddEdge(Coordinate source, Coordinate target, IDictionary<String, Object> metadata) { source = PrecisionModel.MakePrecise(source); target = PrecisionModel.MakePrecise(target); IGraphVertex sourceVertex = GetVertex(source); IGraphVertex targetVertex = GetVertex(target); if (sourceVertex == null) sourceVertex = AddVertex(source); if (targetVertex == null) targetVertex = AddVertex(target); return AddEdge(sourceVertex, targetVertex, metadata); } /// <summary> /// Add a new edge to the graph. /// </summary> /// <param name="source">The source vertex.</param> /// <param name="target">The target vertex.</param> /// <returns>The edge created between <paramref name="source" /> and <paramref name="target" /> vertices.</returns> /// <exception cref="System.ArgumentNullException"> /// The source vertex is null. /// or /// The target vertex is null. /// </exception> /// <exception cref="System.ArgumentException"> /// The source vertex is not within the graph. /// or /// The target vertex is not within the graph. /// </exception> public virtual IGraphEdge AddEdge(IGraphVertex source, IGraphVertex target) { return AddEdge(source, target, null); } /// <summary> /// Add a new edge to the graph. /// </summary> /// <param name="source">The source vertex.</param> /// <param name="target">The target vertex.</param> /// <param name="metadata">The metadata.</param> /// <returns>The edge created between <paramref name="source" /> and <paramref name="target" /> vertices.</returns> /// <exception cref="System.ArgumentNullException"> /// The source vertex is null. /// or /// The target vertex is null. /// </exception> /// <exception cref="System.ArgumentException"> /// The source vertex is not within the graph. /// or /// The target vertex is not within the graph. /// </exception> public virtual IGraphEdge AddEdge(IGraphVertex source, IGraphVertex target, IDictionary<String, Object> metadata) { if (source == null) throw new ArgumentNullException("source", "The source vertex is null."); if (target == null) throw new ArgumentNullException("target", "The target vertex is null."); HashSet<IGraphEdge> sourceResult, targetResult; if (!(source is GraphVertex) || source.Graph != this || !_adjacencySource.TryGetValue(source, out sourceResult)) throw new ArgumentException("The source vertex is not within the graph.", "source"); if (!(target is GraphVertex) || target.Graph != this || !_adjacencyTarget.TryGetValue(target, out targetResult)) throw new ArgumentException("The target vertex is not within the graph.", "target"); GraphEdge edge = new GraphEdge(this, source as GraphVertex, target as GraphVertex, metadata); sourceResult.Add(edge); targetResult.Add(edge); OnGeometryChanged(); return edge; } /// <summary> /// Returns an edge between the specified coordinates. /// </summary> /// <param name="source">The source coordinate.</param> /// <param name="target">The target coordinate.</param> /// <returns>The first edge between <paramref name="source" /> and <paramref name="target" /> coordinates.</returns> public virtual IGraphEdge GetEdge(Coordinate source, Coordinate target) { source = PrecisionModel.MakePrecise(source); target = PrecisionModel.MakePrecise(target); foreach (GraphVertex vertex in _adjacencySource.Keys) { if (vertex.Coordinate.Equals(source)) { IGraphEdge selectedEdge = _adjacencySource[vertex].FirstOrDefault(edge => edge.Target.Coordinate.Equals(target)); if (selectedEdge != null) return selectedEdge; } } return null; } /// <summary> /// Returns an edge between the specified vertices. /// </summary> /// <param name="source">The source vertex.</param> /// <param name="target">The target vertex.</param> /// <returns>The edge between <paramref name="source" /> and <paramref name="target" /> vertices.</returns> /// <exception cref="System.ArgumentNullException"> /// The source vertex is null. /// or /// The target vertex is null. /// </exception> /// <exception cref="System.ArgumentException"> /// The source vertex is not within the graph. /// or /// The target vertex is not within the graph. /// </exception> public virtual IGraphEdge GetEdge(IGraphVertex source, IGraphVertex target) { if (source == null) throw new ArgumentNullException("source", "The source vertex is null."); if (target == null) throw new ArgumentNullException("target", "The target vertex is null."); HashSet<IGraphEdge> sourceResult; if (!(source is GraphVertex) || source.Graph != this || !_adjacencySource.TryGetValue(source, out sourceResult)) throw new ArgumentException("The source vertex is not within the graph.", "source"); if (!(target is GraphVertex) || target.Graph != this || !_adjacencyTarget.ContainsKey(target)) throw new ArgumentException("The target vertex is not within the graph.", "target"); return sourceResult.FirstOrDefault(edge => _vertexEqualityComparer.Equals(edge.Target, target)); } /// <summary> /// Returns all edges between the specified coordinates. /// </summary> /// <param name="source">The source coordinate.</param> /// <param name="target">The target coordinate.</param> /// <returns>The read-only list of edges between <paramref name="source" /> and <paramref name="target" /> coordinates.</returns> public virtual IList<IGraphEdge> GetAllEdges(Coordinate source, Coordinate target) { source = PrecisionModel.MakePrecise(source); target = PrecisionModel.MakePrecise(target); List<IGraphEdge> edges = new List<IGraphEdge>(); foreach (GraphVertex vertex in _adjacencySource.Keys) { if (vertex.Coordinate.Equals(source)) { edges.AddRange(_adjacencySource[vertex].Where(edge => edge.Target.Coordinate.Equals(target))); } } return edges; } /// <summary> /// Returns all edges between the specified vertices. /// </summary> /// <param name="source">The source vertex.</param> /// <param name="target">The target vertex.</param> /// <returns>The read-only list of edges between <paramref name="source" /> and <paramref name="target" /> vertices.</returns> /// <exception cref="System.ArgumentNullException"> /// The source vertex is null. /// or /// The target vertex is null. /// </exception> /// <exception cref="System.ArgumentException"> /// The source vertex is not within the graph. /// or /// The target vertex is not within the graph. /// </exception> public virtual IList<IGraphEdge> GetAllEdges(IGraphVertex source, IGraphVertex target) { if (source == null) throw new ArgumentNullException("source", "The source vertex is null."); if (target == null) throw new ArgumentNullException("target", "The target vertex is null."); HashSet<IGraphEdge> sourceResult; if (!(source is GraphVertex) || source.Graph != this || !_adjacencySource.TryGetValue(source, out sourceResult)) throw new ArgumentException("The source vertex is not within the graph.", "source"); if (!(target is GraphVertex) || target.Graph != this || !_adjacencyTarget.ContainsKey(target)) throw new ArgumentException("The target vertex is not within the graph.", "target"); return sourceResult.Where(edge => _vertexEqualityComparer.Equals(edge.Target, target)).ToList<IGraphEdge>(); } /// <summary> /// Returns the nearest vertex to a specified coordinate. /// </summary> /// <param name="coordinate">The coordinate.</param> /// <returns>The nearest vertex to <paramref name="coordinate" /> if the graph is not empty; otherwise, <c>null</c>.</returns> public IGraphVertex GetNearestVertex(Coordinate coordinate) { coordinate = PrecisionModel.MakePrecise(coordinate); GraphVertex minVertex = null; Double minDistance = Double.MaxValue; foreach (GraphVertex vertex in _vertexList) if (Coordinate.Distance(vertex.Coordinate, coordinate) < minDistance) { minVertex = vertex; minDistance = Coordinate.Distance(vertex.Coordinate, coordinate); } return minVertex; } /// <summary> /// Returns the nearest vertex to a specified coordinate. /// </summary> /// <param name="coordinate">The coordinate.</param> /// <param name="accuracy">The accuracy of the localization.</param> /// <returns>The first vertex within the specified <paramref name="accuracy" /> to <paramref name="coordinate" /> if any; otherwise, <c>null</c>.</returns> public IGraphVertex GetNearestVertex(Coordinate coordinate, Double accuracy) { coordinate = PrecisionModel.MakePrecise(coordinate); return _vertexList.FirstOrDefault(vertex => Coordinate.Distance(vertex.Coordinate, coordinate) <= accuracy); } /// <summary> /// Removes all vertices located at the specified vertex from the graph. /// </summary> /// <param name="coordinate">The coordinate.</param> /// <returns><c>true</c> if at least one vertex was located and removed from the <paramref name="coordinate" />; otherwise false.</returns> public virtual Boolean RemoveVertex(Coordinate coordinate) { coordinate = PrecisionModel.MakePrecise(coordinate); // get all vertices with the specified coordinate IGraphVertex[] vertices = _adjacencySource.Keys.Where(v => v.Coordinate.Equals(coordinate)).ToArray(); if (vertices.Length == 0) // if none, nothing to do return false; for (Int32 i = 0; i < vertices.Length; i++) // remove all vertices RemoveVertex(vertices[i]); return true; } /// <summary> /// Removes the specified vertex from the graph. /// </summary> /// <param name="vertex">The vertex.</param> /// <returns><c>true</c> if <paramref name="vertex" /> is within the graph and has been removed; otherwise false.</returns> /// <exception cref="System.ArgumentNullException">vertex;The vertex is null.</exception> public virtual Boolean RemoveVertex(IGraphVertex vertex) { if (vertex == null) throw new ArgumentNullException("vertex", "The vertex is null."); if (!(vertex is GraphVertex) || vertex.Graph != this) return false; if (!_adjacencySource.ContainsKey(vertex)) return false; _adjacencySource.Remove(vertex); foreach (GraphVertex v in _adjacencySource.Keys) { _adjacencySource[v].RemoveWhere(edge => _vertexEqualityComparer.Equals(edge.Target, vertex)); } _adjacencyTarget.Remove(vertex); foreach (GraphVertex v in _adjacencySource.Keys) { _adjacencyTarget[v].RemoveWhere(edge => _vertexEqualityComparer.Equals(edge.Source, vertex)); } _vertexList.Remove(vertex); _version++; OnGeometryChanged(); return true; } /// <summary> /// Removes the edge from the graph. /// </summary> /// <param name="edge">The edge.</param> /// <returns><c>true</c> if the edge was located and removed from the graph; otherwise, <c>false</c>.</returns> /// <exception cref="System.ArgumentNullException">The edge is null.</exception> public virtual Boolean RemoveEdge(IGraphEdge edge) { if (edge == null) throw new ArgumentNullException("edge", "The edge is null."); if (!(edge is GraphEdge) || edge.Graph != this) return false; Int32 removeCount = 0; foreach (GraphVertex v in _adjacencySource.Keys) { removeCount += _adjacencySource[v].RemoveWhere(e => _edgeEqualityComparer.Equals(e, edge)); } foreach (GraphVertex v in _adjacencyTarget.Keys) { removeCount += _adjacencyTarget[v].RemoveWhere(e => _edgeEqualityComparer.Equals(e, edge)); } if (removeCount > 0) { OnGeometryChanged(); return true; } return false; } /// <summary> /// Removes all edges between the source and target coordinates from the graph. /// </summary> /// <param name="source">The source coordinate.</param> /// <param name="target">The target coordinate.</param> /// <returns><c>true</c> if at least one edge was located and removed between <paramref name="source" /> and <paramref name="target" />; otherwise, <c>false</c>.</returns> public virtual Boolean RemoveEdge(Coordinate source, Coordinate target) { source = PrecisionModel.MakePrecise(source); target = PrecisionModel.MakePrecise(target); if (_vertexList.Count(vertex => vertex.Coordinate.Equals(source) || vertex.Coordinate.Equals(target)) == 0) return false; Int32 removeCount = 0; foreach (HashSet<IGraphEdge> edges in _adjacencySource.Where(item => item.Key.Coordinate.Equals(source)).Select(item => item.Value)) { removeCount += edges.RemoveWhere(edge => edge.Target.Coordinate.Equals(target)); } foreach (HashSet<IGraphEdge> edges in _adjacencyTarget.Where(item => item.Key.Coordinate.Equals(source)).Select(item => item.Value)) { removeCount += edges.RemoveWhere(edge => edge.Source.Coordinate.Equals(target)); } if (removeCount > 0) { OnGeometryChanged(); return true; } return false; } /// <summary> /// Removes all edges between the source and target vertices from the graph. /// </summary> /// <param name="source">The source vertex.</param> /// <param name="target">The target vertex.</param> /// <returns><c>true</c> if at least one edge was located and removed between <paramref name="source" /> and <paramref name="target" />; otherwise, <c>false</c>.</returns> /// <exception cref="System.ArgumentNullException"> /// The source vertex is null. /// or /// The target vertex is null. /// </exception> public virtual Boolean RemoveEdge(IGraphVertex source, IGraphVertex target) { if (source == null) throw new ArgumentNullException("source", "The source vertex is null."); if (target == null) throw new ArgumentNullException("target", "The target vertex is null."); HashSet<IGraphEdge> sourceEdges, targetEdges; if (!(source is GraphVertex) || source.Graph != this || !_adjacencySource.TryGetValue(source, out sourceEdges)) return false; if (!(target is GraphVertex) || target.Graph != this || !_adjacencyTarget.TryGetValue(source, out targetEdges)) return false; Int32 removeCount = 0; removeCount += sourceEdges.RemoveWhere(edge => _vertexEqualityComparer.Equals(edge.Target, target)); // remove all edges with the specified target removeCount += targetEdges.RemoveWhere(edge => _vertexEqualityComparer.Equals(edge.Source, source)); // remove all edges with the specified source if (removeCount > 0) { OnGeometryChanged(); return true; } return false; } /// <summary> /// Returns an enumerator that iterates through the graph. /// </summary> /// <param name="strategy">The strategy of the enumeration.</param> /// <returns>An <see cref="IEnumerator{IGraphVertex}" /> object that can be used to iterate through the graph.</returns> public IEnumerator<IGraphVertex> GetEnumerator(EnumerationStrategy strategy) { if (strategy == EnumerationStrategy.DepthFirst) return new DepthFirstEnumerator(this); else return new BreadthFirstEnumerator(this); } #endregion #region ICloneable methods /// <summary> /// Creates a clone of the <see cref="GeometryGraph" /> instance. /// </summary> /// <returns>The deep copy of the <see cref="GeometryGraph" /> instance.</returns> public override Object Clone() { GeometryGraph result = new GeometryGraph(_vertexEqualityComparer, _edgeEqualityComparer, Factory, Metadata); CloneToGraph(this, result); return result; } #endregion #region IEnumerable methods /// <summary> /// Returns an enumerator that iterates through a graph. /// </summary> /// <returns>An <see cref="IEnumerator{IGraphVertex}" /> object that can be used to iterate through the graph.</returns> public IEnumerator<IGraphVertex> GetEnumerator() { return new BreadthFirstEnumerator(this); } /// <summary> /// Returns an enumerator that iterates through a graph. /// </summary> /// <returns>An <see cref="IEnumerator" /> object that can be used to iterate through the graph.</returns> IEnumerator IEnumerable.GetEnumerator() { return new BreadthFirstEnumerator(this); } #endregion #region Object methods /// <summary> /// Returns the <see cref="System.String" /> equivalent of the instance. /// </summary> /// <returns>A <see cref="System.String" /> containing the coordinates in all dimensions.</returns> public override String ToString() { return Name + " [" + VertexCount + ", " + EdgeCount + "]"; } #endregion #region Protected methods /// <summary> /// Clones a specified source graph to a target graph. /// </summary> /// <param name="source">Source graph.</param> /// <param name="target">Target graph.</param> protected static void CloneToGraph(GeometryGraph source, GeometryGraph target) { Dictionary<IGraphVertex, IGraphVertex> sourceToTargetVertexMapper = new Dictionary<IGraphVertex, IGraphVertex>(); Dictionary<IGraphVertex, IGraphVertex> vertexToVertexMapper = new Dictionary<IGraphVertex, IGraphVertex>(target._vertexEqualityComparer); foreach (KeyValuePair<IGraphVertex, HashSet<IGraphEdge>> item in source._adjacencySource) { IGraphVertex n = target.AddVertex(item.Key.Coordinate, item.Key.Metadata), m; if (!vertexToVertexMapper.TryGetValue(n, out m)) { sourceToTargetVertexMapper.Add(item.Key, n); vertexToVertexMapper.Add(n, n); } else { sourceToTargetVertexMapper.Add(item.Key, vertexToVertexMapper[n]); } } foreach (KeyValuePair<IGraphVertex, HashSet<IGraphEdge>> item in source._adjacencySource) { IGraphVertex from = sourceToTargetVertexMapper[item.Key]; foreach (IGraphEdge edge in item.Value) { IGraphVertex to = sourceToTargetVertexMapper[edge.Target]; target.AddEdge(from, to, source.Factory.GetFactory<IMetadataFactory>().CreateCollection(edge.Metadata)); } } } /// <summary> /// Called when the geometry is changed. /// </summary> protected override void OnGeometryChanged() { _edgeList = null; _version++; base.OnGeometryChanged(); } /// <summary> /// Computes the minimal bounding envelope of the geometry. /// </summary> /// <returns>The minimum bounding box of the geometry.</returns> protected override Envelope ComputeEnvelope() { return Envelope.FromCoordinates(_vertexList.Select(vertex => vertex.Coordinate)); } /// <summary> /// Computes the boundary of the geometry. /// </summary> /// <returns>The closure of the combinatorial boundary of the geometry.</returns> protected override IGeometry ComputeBoundary() { // TODO: compute proper bundary for graph return null; } #endregion } }
41.09824
239
0.569071
[ "ECL-2.0" ]
AegisSpatial/aegis-origin
AEGIS.Core.Graphs/Geometry/GeometryGraph.cs
56,063
C#