content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class ET_AcceptAllCertificate_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(ET.AcceptAllCertificate); args = new Type[]{}; method = type.GetConstructor(flag, null, args, null); app.RegisterCLRMethodRedirection(method, Ctor_0); } static StackObject* Ctor_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* __ret = ILIntepreter.Minus(__esp, 0); var result_of_this_method = new ET.AcceptAllCertificate(); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } } }
30.12766
134
0.701977
[ "MIT" ]
306739889/guessGame
Unity/Assets/Mono/ILRuntime/Generate/ET_AcceptAllCertificate_Binding.cs
1,416
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/IContact.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.CLSID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="ContactManager" /> struct.</summary> public static unsafe partial class ContactManagerTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="ContactManager" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(ContactManager).GUID, Is.EqualTo(CLSID_ContactManager)); } /// <summary>Validates that the <see cref="ContactManager" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<ContactManager>(), Is.EqualTo(sizeof(ContactManager))); } /// <summary>Validates that the <see cref="ContactManager" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(ContactManager).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="ContactManager" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(ContactManager), Is.EqualTo(1)); } }
36.636364
145
0.708437
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/Windows/um/IContact/ContactManagerTests.cs
1,614
C#
/* * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers * for more information concerning the license and the contributors participating to this project. */ namespace AspNet.Security.OAuth.ServiceChannel; public static class ServiceChannelAuthenticationDefaults { /// <summary> /// Default value for <see cref="AuthenticationScheme.Name"/>. /// </summary> public const string AuthenticationScheme = "ServiceChannel"; /// <summary> /// Default value for <see cref="AuthenticationScheme.DisplayName"/>. /// </summary> public static readonly string DisplayName = "ServiceChannel"; /// <summary> /// Default value for <see cref="AuthenticationSchemeOptions.ClaimsIssuer"/>. /// </summary> public static readonly string Issuer = "ServiceChannel"; /// <summary> /// Default value for <see cref="RemoteAuthenticationOptions.CallbackPath"/>. /// </summary> public static readonly string CallbackPath = "/signin-servicechannel"; /// <summary> /// Default value for <see cref="OAuthOptions.AuthorizationEndpoint"/>. /// </summary> public static readonly string AuthorizationEndpoint = "https://login.servicechannel.com/oauth/authorize"; /// <summary> /// Default value for <see cref="OAuthOptions.TokenEndpoint"/>. /// </summary> public static readonly string TokenEndpoint = "https://login.servicechannel.com/oauth/token"; /// <summary> /// Default value for <see cref="OAuthOptions.UserInformationEndpoint"/>. /// </summary> public static readonly string UserInformationEndpoint = "https://api.servicechannel.com/v3/users/current/profile"; }
38.521739
118
0.704853
[ "Apache-2.0" ]
AnthonyYates/AspNet.Security.OAuth.Providers
src/AspNet.Security.OAuth.ServiceChannel/ServiceChannelAuthenticationDefaults.cs
1,774
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ColoursAPI.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; namespace ColoursAPI { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton<ColoursService>(new ColoursService(Configuration)); services.AddControllers(); services.AddCors(); services.AddAuthorization(); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.Authority = Configuration.GetValue<string>("Authentication:Issuer"); options.RequireHttpsMetadata = true; options.Audience = Configuration.GetValue<string>("Authentication:Audience"); options.TokenValidationParameters.ValidateAudience = false; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "ColoursAPI", Version = "v1", Description = "Grupo de operaciones de la aplicación ColoursApp. Aplicación con fines educativos de AprenderIT, que unifica y extiende las funcionalidades originalmente creadas por Mark Harrison (https://github.com/markharrison/ColourAPI/ y https://github.com/markharrison/ColoursWeb)", TermsOfService = new Uri("https://github.com/AprenderIT/ColoursApp"), Contact = new OpenApiContact { Name = "Pablo Di Loreto", Email = "pdiloreto@aprender.it", Url = new Uri("https://aprender.it"), }, License = new OpenApiLicense { Name = "Use under MIT License", Url = new Uri("https://github.com/AprenderIT/ColoursApp/blob/main/LICENSE"), } } ); var securityScheme = new OpenApiSecurityScheme { Name = "JWT Authentication", Description = "Enter JWT Bearer token **_only_**", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", // must be lower case BearerFormat = "JWT", Reference = new OpenApiReference { Id = JwtBearerDefaults.AuthenticationScheme, Type = ReferenceType.SecurityScheme } }; c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, securityScheme); c.AddSecurityRequirement(new OpenApiSecurityRequirement { {securityScheme, new string[] { }} }); c.EnableAnnotations(); string strURL = Configuration.GetValue<string>("ServerURL"); if (strURL != null && strURL != "") { c.AddServer(new OpenApiServer() { Url = strURL }); } }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod()); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "ColoursAPI v1"); }); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
36.364286
306
0.533883
[ "MIT" ]
AprenderIT/ColoursApp-AM101A
src/ColoursAPI/Startup.cs
5,093
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("LinqToAwait")] [assembly: AssemblyDescription("LINQ operators built to work with async/await, based on Rx")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Paul Betts")] [assembly: AssemblyProduct("LinqToAwait")] [assembly: AssemblyCopyright("Copyright © Paul Betts 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.0.0")] [assembly: AssemblyFileVersion("0.9.0.0")]
37.517241
93
0.746324
[ "MIT" ]
anaisbetts/LinqToAwait
LinqToAwait/Properties/AssemblyInfo.cs
1,091
C#
using ControlzEx.Theming; using MahApps.Metro.Controls; using Microsoft.Win32; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Windows; using System.Windows.Navigation; using WPFLocalizeExtension.Engine; namespace NotEnoughAV1Encodes.Views { public partial class ProgramSettings : MetroWindow { public Settings settingsDBTemp = new(); public ProgramSettings(Settings settingsDB) { InitializeComponent(); ToggleSwitchOverrideWorkerCount.IsOn = settingsDB.OverrideWorkerCount; ToggleSwitchDeleteTempFiles.IsOn = settingsDB.DeleteTempFiles; ToggleSwitchAutoPauseResume.IsOn = settingsDB.AutoResumePause; ToggleSwitchInputSeeking.IsOn = settingsDB.UseInputSeeking; ToggleSwitchShutdown.IsOn = settingsDB.ShutdownAfterEncode; ToggleSwitchLogging.IsOn = settingsDB.Logging; ComboBoxAccentTheme.SelectedIndex = settingsDB.AccentTheme; ComboBoxBaseTheme.SelectedIndex = settingsDB.BaseTheme; TextBoxTempPath.Text = settingsDB.TempPath; settingsDBTemp.BGImage = settingsDB.BGImage; ComboBoxProcessPriority.SelectedIndex = settingsDB.PriorityNormal ? 0 : 1; string AssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); LabelVersion1.Content = AssemblyVersion.Remove(AssemblyVersion.Length - 2); try { ThemeManager.Current.ChangeTheme(this, settingsDB.Theme); } catch { } ComboBoxLanguage.SelectedIndex = settingsDB.CultureInfo.Name switch { "en" => 0, "de" => 1, "zh-CN" => 2, "ru-RU" => 3, "ja-JP" => 4, "it-IT" => 5, _ => 0, }; } private void ButtonSelectBGImage_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new() { Filter = "Image Files|*.jpg;*.jpeg;*.png;*.bmp" }; if (openFileDialog.ShowDialog() == true) { settingsDBTemp.BGImage = openFileDialog.FileName; } } private void ButtonSelectTempPath_Click(object sender, RoutedEventArgs e) { using var dialog = new System.Windows.Forms.FolderBrowserDialog(); dialog.SelectedPath = TextBoxTempPath.Text; System.Windows.Forms.DialogResult result = dialog.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { TextBoxTempPath.Text = dialog.SelectedPath + "\\"; } } private void ButtonSelectTempPathReset_Click(object sender, RoutedEventArgs e) { TextBoxTempPath.Text = Path.GetTempPath(); } private void ButtonUpdater_Click(object sender, RoutedEventArgs e) { Updater updater = new(ComboBoxBaseTheme.Text, ComboBoxAccentTheme.Text); updater.ShowDialog(); } private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) { settingsDBTemp.OverrideWorkerCount = ToggleSwitchOverrideWorkerCount.IsOn; settingsDBTemp.DeleteTempFiles = ToggleSwitchDeleteTempFiles.IsOn; settingsDBTemp.AutoResumePause = ToggleSwitchAutoPauseResume.IsOn; settingsDBTemp.UseInputSeeking = ToggleSwitchInputSeeking.IsOn; settingsDBTemp.ShutdownAfterEncode = ToggleSwitchShutdown.IsOn; settingsDBTemp.Logging = ToggleSwitchLogging.IsOn; settingsDBTemp.BaseTheme = ComboBoxBaseTheme.SelectedIndex; settingsDBTemp.AccentTheme = ComboBoxAccentTheme.SelectedIndex; settingsDBTemp.Theme = ComboBoxBaseTheme.Text + "." + ComboBoxAccentTheme.Text; settingsDBTemp.TempPath = TextBoxTempPath.Text; settingsDBTemp.PriorityNormal = ComboBoxProcessPriority.SelectedIndex == 0; } private void ButtonResetBGImage_Click(object sender, RoutedEventArgs e) { settingsDBTemp.BGImage = null; } private void ComboBoxLanguage_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { if (ComboBoxLanguage == null) return; settingsDBTemp.CultureInfo = ComboBoxLanguage.SelectedIndex switch { 0 => new CultureInfo("en"), 1 => new CultureInfo("de"), 2 => new CultureInfo("zh-CN"), 3 => new CultureInfo("ru-RU"), 4 => new CultureInfo("ja-JP"), 5 => new CultureInfo("it-IT"), _ => new CultureInfo("en"), }; LocalizeDictionary.Instance.Culture = settingsDBTemp.CultureInfo; } private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) { ProcessStartInfo psi = new() { FileName = "cmd", WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false, CreateNoWindow = true, Arguments = $"/c start {e.Uri}" }; Process.Start(psi); } private void ButtonExit_Click(object sender, RoutedEventArgs e) { Close(); } } }
39.077465
122
0.611101
[ "MIT" ]
dramspro/NotEnoughAV1Encodes
NotEnoughAV1Encodes/Views/ProgramSettings.xaml.cs
5,551
C#
namespace ProductShop.Import { using System; using System.Collections.Generic; using System.IO; using AutoMapper; using Data; using Models; using Newtonsoft.Json; public class StartUp { public static void Main(string[] args) { var config = new MapperConfiguration(cfg => { cfg.AddProfile<ProductShopProfile>(); }); var mapper = config.CreateMapper(); var context = new ProductShopContext(); context.Database.EnsureDeleted(); context.Database.EnsureCreated(); ImportUsersRecords(context); ImportProductsRecords(context); ImportCategoriesRecords(context); ImportCategoryProductsRecords(context); } private static void ImportCategoryProductsRecords(ProductShopContext context) { List<CategoryProduct> categoryProducts = new List<CategoryProduct>(); Random random = new Random(); for (int productId = 1; productId <= 200; productId++) { var categoryProduct = new CategoryProduct { CategoryId = random.Next(1, 12), ProductId = productId }; categoryProducts.Add(categoryProduct); } context.CategoryProducts.AddRange(categoryProducts); context.SaveChanges(); } private static void ImportCategoriesRecords(ProductShopContext context) { string jsonString = File.ReadAllText("../../../Json/categories.json"); var categories = JsonConvert.DeserializeObject<List<Category>>(jsonString); context.Categories.AddRange(categories); context.SaveChanges(); } private static void ImportProductsRecords(ProductShopContext context) { string jsonString = File.ReadAllText("../../../Json/products.json"); var products = JsonConvert.DeserializeObject<List<Product>>(jsonString); Random random = new Random(); foreach (var product in products) { product.SellerId = random.Next(1, 57); bool isBuyerExist = random.Next(1, 5) == 4; if (isBuyerExist) { product.BuyerId = random.Next(1, 57); } } context.Products.AddRange(products); context.SaveChanges(); } private static void ImportUsersRecords(ProductShopContext context) { string jsonString = File.ReadAllText("../../../Json/users.json"); var users = JsonConvert.DeserializeObject<List<User>>(jsonString); context.Users.AddRange(users); context.SaveChanges(); } } }
29.313131
87
0.564094
[ "MIT" ]
RosenBobchev/CSharp-DB-Fundamentals
Database Advanced/JSON Processing - Exercise/ProductShop.ImportData/StartUp.cs
2,904
C#
#if !NETSTANDARD13 /* * 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 ce-2017-10-25.normal.json service model. */ using Amazon.Runtime; namespace Amazon.CostExplorer.Model { /// <summary> /// Paginator for the ListCostCategoryDefinitions operation ///</summary> public interface IListCostCategoryDefinitionsPaginator { /// <summary> /// Enumerable containing all full responses for the operation /// </summary> IPaginatedEnumerable<ListCostCategoryDefinitionsResponse> Responses { get; } } } #endif
33.057143
100
0.713051
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/CostExplorer/Generated/Model/_bcl45+netstandard/IListCostCategoryDefinitionsPaginator.cs
1,157
C#
// Copyright 2021 Yubico AB // // 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 System; using Xunit; using Yubico.Core.Iso7816; namespace Yubico.YubiKey.U2f.Commands { public class VerifyPinCommandTests { private const int offsetCla = 0; private const int offsetIns = 1; private const int offsetP1 = 2; private const int offsetP2 = 3; private const int lengthHeader = 4; // APDU header is 4 bytes (Cla, Ins, P1, P2) private const int offsetLc = 4; private const int lengthLc = 3; private const int offsetData = offsetLc + lengthLc; private readonly byte[] Pin = new byte[] { 1, 2, 3, 4, 5, 6 }; [Fact] public void CreateCommandApdu_GetClaProperty_ReturnsZero() { var command = new VerifyPinCommand(Pin); Assert.Equal(0, command.CreateCommandApdu().Cla); } [Fact] public void CreateCommandApdu_GetInsProperty_Returns0x03() { var command = new VerifyPinCommand(Pin); Assert.Equal(0x03, command.CreateCommandApdu().Ins); } [Fact] public void CreateCommandApdu_GetP1Property_ReturnsZero() { var command = new VerifyPinCommand(Pin); Assert.Equal(0, command.CreateCommandApdu().P1); } [Fact] public void CreateCommandApdu_GetP2Property_ReturnsZero() { var command = new VerifyPinCommand(Pin); Assert.Equal(0, command.CreateCommandApdu().P2); } [Fact] public void CreateCommandApdu_GetNcProperty_ReturnsCorrectLength() { byte[] expectedInnerLc = new byte[] { 0x00, 0x00, (byte)Pin.Length }; int expectedCommandLength = lengthHeader + expectedInnerLc.Length + Pin.Length; var command = new VerifyPinCommand(Pin); CommandApdu commandApdu = command.CreateCommandApdu(); Assert.Equal(commandApdu.Nc, expectedCommandLength); } [Fact] public void CreateCommandApdu_InnerCommandGetClaProperty_ReturnsZero() { var command = new VerifyPinCommand(Pin); CommandApdu commandApdu = command.CreateCommandApdu(); ReadOnlyMemory<byte> actualInnerCommandApdu = commandApdu.Data; byte actualInnerCommandCla = actualInnerCommandApdu.Span[offsetCla]; Assert.Equal(0, actualInnerCommandCla); } [Fact] public void CreateCommandApdu_InnerCommandGetInsProperty_Returns0x43() { var command = new VerifyPinCommand(Pin); CommandApdu commandApdu = command.CreateCommandApdu(); ReadOnlyMemory<byte> actualInnerCommandApdu = commandApdu.Data; byte actualInnerCommandIns = actualInnerCommandApdu.Span[offsetIns]; Assert.Equal(0x43, actualInnerCommandIns); } [Fact] public void CreateCommandApdu_InnerCommandGetP1Property_ReturnsZero() { var command = new VerifyPinCommand(Pin); CommandApdu commandApdu = command.CreateCommandApdu(); ReadOnlyMemory<byte> actualInnerCommandApdu = commandApdu.Data; byte actualInnerCommandP1 = actualInnerCommandApdu.Span[offsetP1]; Assert.Equal(0, actualInnerCommandP1); } [Fact] public void CreateCommandApdu_InnerCommandGetP2Property_ReturnsZero() { var command = new VerifyPinCommand(Pin); CommandApdu commandApdu = command.CreateCommandApdu(); ReadOnlyMemory<byte> actualInnerCommandApdu = commandApdu.Data; byte actualInnerCommandP2 = actualInnerCommandApdu.Span[offsetP2]; Assert.Equal(0, actualInnerCommandP2); } [Fact] public void CreateCommandApdu_InnerCommandGetNcProperty_ReturnsCorrectLength() { byte[] expectedInnerLc = new byte[] { 0x00, 0x00, (byte)Pin.Length }; var command = new VerifyPinCommand(Pin); CommandApdu commandApdu = command.CreateCommandApdu(); ReadOnlyMemory<byte> actualInnerCommandApdu = commandApdu.Data; ReadOnlySpan<byte> actualInnerCommandLc = actualInnerCommandApdu.Slice(offsetLc, lengthLc).Span; Assert.True(actualInnerCommandLc.SequenceEqual(expectedInnerLc)); } [Fact] public void CreateCommandApdu_InnerCommandGetData_ReturnsCorrectData() { var command = new VerifyPinCommand(Pin); CommandApdu commandApdu = command.CreateCommandApdu(); ReadOnlyMemory<byte> actualInnerCommandApdu = commandApdu.Data; ReadOnlySpan<byte> actualInnerCommandData = actualInnerCommandApdu.Slice(offsetData, Pin.Length).Span; Assert.True(actualInnerCommandData.SequenceEqual(Pin)); } [Fact] public void CreateCommandApdu_PinIsEmpty_ThrowsArgumentException() { _ = Assert.Throws<ArgumentException>(() => new VerifyPinCommand(Array.Empty<byte>())); } [Fact] public void CreateCommandApdu_PinIsNull_ThrowsArgumentException() { _ = Assert.Throws<ArgumentException>(() => new VerifyPinCommand(null)); } [Fact] public void CreateCommandApdu_PinLengthLessThan6_ThrowsArgumentException() { var pin = new byte[] { 1, 2, 3, 4 }; _ = Assert.Throws<ArgumentException>(() => new VerifyPinCommand(pin)); } [Fact] public void CreateCommandApdu_PinLengthMoreThan32_ThrowsArgumentException() { var pin = new byte[33]; _ = Assert.Throws<ArgumentException>(() => new VerifyPinCommand(pin)); } [Fact] public void CreateResponseApdu_ReturnsCorrectType() { var responseApdu = new ResponseApdu(new byte[] { 0x90, 0x00 }); var command = new VerifyPinCommand(Pin); var response = command.CreateResponseForApdu(responseApdu); _ = Assert.IsType<U2fResponse>(response); } } }
34.692708
114
0.645549
[ "Apache-2.0" ]
Yubico/Yubico.NET.SDK
Yubico.YubiKey/tests/unit/Yubico/YubiKey/U2f/Commands/VerifyPinCommandTests.cs
6,663
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("ConsoleApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApp")] [assembly: AssemblyCopyright("Copyright © 2019")] [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("6a591df6-046a-4116-81b2-60682429801d")] // 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.513514
84
0.747118
[ "MIT" ]
ClairG/ChatApp
ClairG.ChatApp/ConsoleApp/Properties/AssemblyInfo.cs
1,391
C#
using System; using System.Threading.Tasks; using Convey.CQRS.Commands; using CourseLibrary.Application.Exceptions; using CourseLibrary.Application.Services; using CourseLibrary.Core.Repositories; namespace CourseLibrary.Application.Commands.Student.Handlers { public class CreateStudentHandler : ICommandHandler<CreateStudent> { private readonly IStudentsRepository _studentsRepository; private readonly IUsersService _usersService; public CreateStudentHandler(IStudentsRepository studentsRepository, IUsersService usersService) => (_studentsRepository, _usersService) = (studentsRepository, usersService); public async Task HandleAsync(CreateStudent command) { var user = await _usersService.GetAsync(command.UserId); if(!(user is null)) { throw new UserAlreadyExistsException(command.UserId); } var student = await _studentsRepository.GetAsync(command.UserId); if(!(student is null)) { throw new StudentAlreadyExistsException(command.UserId); } student = new Core.Aggregates.Student(user.Id, user.FirstName, user.LastName, DateTime.UtcNow, null); await _studentsRepository.AddAsync(student); } } }
33.925
113
0.676492
[ "MIT" ]
ktutak1337/CourseLibrary
src/CourseLibrary.Application/Commands/Student/Handlers/CreateStudentHandler.cs
1,357
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 cognito-idp-2016-04-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.CognitoIdentityProvider.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CognitoIdentityProvider.Model.Internal.MarshallTransformations { /// <summary> /// AdminLinkProviderForUser Request Marshaller /// </summary> public class AdminLinkProviderForUserRequestMarshaller : IMarshaller<IRequest, AdminLinkProviderForUserRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((AdminLinkProviderForUserRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(AdminLinkProviderForUserRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.CognitoIdentityProvider"); string target = "AWSCognitoIdentityProviderService.AdminLinkProviderForUser"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-04-18"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetDestinationUser()) { context.Writer.WritePropertyName("DestinationUser"); context.Writer.WriteObjectStart(); var marshaller = ProviderUserIdentifierTypeMarshaller.Instance; marshaller.Marshall(publicRequest.DestinationUser, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetSourceUser()) { context.Writer.WritePropertyName("SourceUser"); context.Writer.WriteObjectStart(); var marshaller = ProviderUserIdentifierTypeMarshaller.Instance; marshaller.Marshall(publicRequest.SourceUser, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetUserPoolId()) { context.Writer.WritePropertyName("UserPoolId"); context.Writer.Write(publicRequest.UserPoolId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static AdminLinkProviderForUserRequestMarshaller _instance = new AdminLinkProviderForUserRequestMarshaller(); internal static AdminLinkProviderForUserRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static AdminLinkProviderForUserRequestMarshaller Instance { get { return _instance; } } } }
37.15748
163
0.62704
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/CognitoIdentityProvider/Generated/Model/Internal/MarshallTransformations/AdminLinkProviderForUserRequestMarshaller.cs
4,719
C#
using MTSC.Common.WebSockets.RoutingModules; namespace MTSC.UnitTests { public class EchoWebsocketModule2 : WebsocketRouteBase<byte[], byte[]> { public override void ConnectionClosed() { } public override void ConnectionInitialized() { } public override void HandleReceivedMessage(byte[] message) { this.SendMessage(message); } public override void Tick() { } } }
19.56
74
0.582822
[ "MIT" ]
AlexMacocian/MTSC
MTSC.UnitTests/EchoWebsocketModule2.cs
491
C#
using System; using System.Collections.Generic; namespace EnternetMagazine { class Program { public static void Main(string[] args) { var productName = new List<string>(); var productPrice = new List<double>(); var productWeight = new List<double>(); var shoppingCartUser = new List<string>(); var shopCart = new ShoppingCart(); var disc = new Discount(); var product = new Product(); product.ProductName = productName; product.ProductPrice = productPrice; product.ProductWeight = productWeight; Console.WriteLine("Привет, если что-то хочешь добавить в магазин, то нажми 'S'"); string userInput = Console.ReadLine().ToLower(); if (userInput == "s") { // TODO: rename method product.SomeMethod(productName, productPrice, productWeight); } shopCart.ShoppingMethod(shoppingCartUser); disc.ShoppingMethod(shoppingCartUser); } } }
29.105263
93
0.570524
[ "MIT" ]
Egor-kl/TMS-DotNet
src/EnternetStore/Program.cs
1,152
C#
using System; using System.Security.Claims; using System.Threading.Tasks; using Lern.Core.Models.Users.Settings; using Lern.Infrastructure.Database.Interfaces; using MediatR; using Microsoft.AspNetCore.Mvc; namespace Lern.Api.Controllers.Users.Settings { [ApiController] [Route("user/options/[controller]")] public class ChangeUsernameController : ControllerBase { private readonly IMediator _mediator; private readonly IUnitOfWork _unitOfWork; public ChangeUsernameController(IMediator mediator, IUnitOfWork unitOfWork) { _mediator = mediator; _unitOfWork = unitOfWork; } [HttpPut] public async Task<IActionResult> ChangeUsername([FromBody] ChangeUsernameModel changeUsernameModel) { await _mediator.Send(new ChangeUsernameMediatorModel { Id = Guid.Parse(User.FindFirst(ClaimTypes.PrimarySid)?.Value!), NewUsername = changeUsernameModel.NewUsername }); await _unitOfWork.CompleteAsync(); return Ok(); } } }
29.473684
107
0.666964
[ "MIT" ]
MRmlik12/lern
backend/src/Lern.Api/Controllers/Users/Settings/ChangeUsernameController.cs
1,120
C#
namespace MyApp.Infrastructure; public class Power { public int Id { get; set; } [StringLength(50)] public string Name { get; set; } public ICollection<Character> Characters { get; set; } = new HashSet<Character>(); public Power(string name) { Name = name; } }
17.705882
86
0.621262
[ "MIT" ]
antonPalmFolkmann/BDSA2021
MyApp.Infrastructure/Power.cs
301
C#
using System.Collections.Generic; using System.Runtime.Serialization; using Umbraco.Cms.Core.Models.ContentEditing; namespace Umbraco.Cms.Core.Models { [DataContract(Name = "contentTypeImportModel")] public class ContentTypeImportModel : INotificationModel { [DataMember(Name = "alias")] public string? Alias { get; set; } [DataMember(Name = "name")] public string? Name { get; set; } [DataMember(Name = "notifications")] public List<BackOfficeNotification> Notifications { get; } = new List<BackOfficeNotification>(); [DataMember(Name = "tempFileName")] public string? TempFileName { get; set; } } }
29.826087
104
0.669096
[ "MIT" ]
Lantzify/Umbraco-CMS
src/Umbraco.Core/Models/ContentTypeImportModel.cs
688
C#
using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using Xamarin.Forms.TestingLibrary.FormsProxies; namespace Xamarin.Forms.TestingLibrary.Extensions { internal static class BindableObjectExtensions { private static IEnumerable<LocalValueEntry> GetLocalValueEntries(this BindableObject bindableObject) { var localValueEnumerator = bindableObject.GetType().GetMethod("GetLocalValueEnumerator", BindingFlags.Instance | BindingFlags.NonPublic)?.Invoke(bindableObject, new object[0]) as IEnumerator; while (localValueEnumerator?.MoveNext() == true) { var localValue = localValueEnumerator.Current; var localValueType = localValue!.GetType(); yield return new LocalValueEntry( localValueType.GetProperty("Property")?.GetValue(localValue) as BindableProperty, localValueType.GetProperty("Value")?.GetValue(localValue), (BindableContextAttributes)(localValueType.GetProperty("Attributes")?.GetValue(localValue) ?? BindableContextAttributes.None)); } } internal static string? GetTextContentValue(this BindableObject bindableObject) { var localValueEntries = bindableObject.GetLocalValueEntries().ToArray(); return localValueEntries.FirstOrDefault(x => x.Property.PropertyName == "Text")?.Value?.ToString() ?? localValueEntries.FirstOrDefault(x => x.Property.PropertyName == "FormattedText")?.Value?.ToString(); } internal static bool HasTextValueWith(this BindableObject bindableObject, string text) => bindableObject.GetLocalValueEntries() .Any(x => x.Property.PropertyName == "Text" && (string)x.Value == text); internal static bool HasAutomationIdValueWith(this BindableObject bindableObject, string automationId) => bindableObject.GetLocalValueEntries() .Any(x => x.Property.PropertyName == "AutomationId" && (string)x.Value == automationId); } }
47.804348
120
0.664848
[ "MIT" ]
rodrigoramos/Xamarin.Forms.TestingLibrary
src/Xamarin.Forms.TestingLibrary/Extensions/BindableObjectExtensions.cs
2,199
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Npgsql; namespace Discount.Grpc.Extensions { public static class HostExtensions { public static IHost MigrateDatabase<IContext>(this IHost host, int? retry = 0) { int retryForAvailability = retry.Value; using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var configuration = services.GetRequiredService<IConfiguration>(); var logger = services.GetRequiredService<ILogger<IContext>>(); try { logger.LogInformation("Migrating postgresql database."); using var connection = new NpgsqlConnection (configuration.GetValue<string>("DatabaseSettings:ConnectionString")); connection.Open(); using var command = new NpgsqlCommand { Connection = connection }; command.CommandText = "DROP TABLE IF EXISTS Coupon"; command.ExecuteNonQuery(); command.CommandText = @"CREATE TABLE Coupon(Id SERIAL PRIMARY KEY, ProductName VARCHAR(24) NOT NULL, Description TEXT, Amount INT)"; command.ExecuteNonQuery(); command.CommandText = "INSERT INTO Coupon(ProductName, Description, Amount) VALUES('IPhone X', 'IPhone Discount', 150);"; command.ExecuteNonQuery(); command.CommandText = "INSERT INTO Coupon(ProductName, Description, Amount) VALUES('Samsung 10', 'Samsung Discount', 100);"; command.ExecuteNonQuery(); logger.LogInformation("Migrated postgresql database."); } catch (NpgsqlException ex) { logger.LogError(ex, "An error occurred while migrating the postresql database"); if (retryForAvailability < 50) { retryForAvailability++; System.Threading.Thread.Sleep(2000); MigrateDatabase<IContext>(host, retryForAvailability); } } } return host; } } }
39.426471
144
0.513987
[ "MIT" ]
edmilsonamancio/AspnetMicroservices
src/Services/Discount/Discount.Grpc/Extensions/HostExtensions.cs
2,683
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.Numerics; using System.Runtime.CompilerServices; namespace System.Buffers.Binary { /// <summary> /// Reads bytes as primitives with specific endianness /// </summary> /// <remarks> /// For native formats, MemoryExtensions.Read{T}; should be used. /// Use these helpers when you need to read specific endinanness. /// </remarks> public static partial class BinaryPrimitives { /// <summary> /// This is a no-op and added only for consistency. /// This allows the caller to read a struct of numeric primitives and reverse each field /// rather than having to skip sbyte fields. /// </summary> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static sbyte ReverseEndianness(sbyte value) { return value; } /// <summary> /// Reverses a primitive value - performs an endianness swap /// </summary> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short ReverseEndianness(short value) => (short)ReverseEndianness((ushort)value); /// <summary> /// Reverses a primitive value - performs an endianness swap /// </summary> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ReverseEndianness(int value) => (int)ReverseEndianness((uint)value); /// <summary> /// Reverses a primitive value - performs an endianness swap /// </summary> [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long ReverseEndianness(long value) => (long)ReverseEndianness((ulong)value); /// <summary> /// This is a no-op and added only for consistency. /// This allows the caller to read a struct of numeric primitives and reverse each field /// rather than having to skip byte fields. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte ReverseEndianness(byte value) { return value; } /// <summary> /// Reverses a primitive value - performs an endianness swap /// </summary> [CLSCompliant(false)] [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ushort ReverseEndianness(ushort value) { // Don't need to AND with 0xFF00 or 0x00FF since the final // cast back to ushort will clear out all bits above [ 15 .. 00 ]. // This is normally implemented via "movzx eax, ax" on the return. // Alternatively, the compiler could elide the movzx instruction // entirely if it knows the caller is only going to access "ax" // instead of "eax" / "rax" when the function returns. return (ushort)((value >> 8) + (value << 8)); } /// <summary> /// Reverses a primitive value - performs an endianness swap /// </summary> [CLSCompliant(false)] [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint ReverseEndianness(uint value) { // This takes advantage of the fact that the JIT can detect // ROL32 / ROR32 patterns and output the correct intrinsic. // // Input: value = [ ww xx yy zz ] // // First line generates : [ ww xx yy zz ] // & [ 00 FF 00 FF ] // = [ 00 xx 00 zz ] // ROR32(8) = [ zz 00 xx 00 ] // // Second line generates: [ ww xx yy zz ] // & [ FF 00 FF 00 ] // = [ ww 00 yy 00 ] // ROL32(8) = [ 00 yy 00 ww ] // // (sum) = [ zz yy xx ww ] // // Testing shows that throughput increases if the AND // is performed before the ROL / ROR. return BitOperations.RotateRight(value & 0x00FF00FFu, 8) // xx zz + BitOperations.RotateLeft(value & 0xFF00FF00u, 8); // ww yy } /// <summary> /// Reverses a primitive value - performs an endianness swap /// </summary> [CLSCompliant(false)] [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ReverseEndianness(ulong value) { // Operations on 32-bit values have higher throughput than // operations on 64-bit values, so decompose. return ((ulong)ReverseEndianness((uint)value) << 32) + ReverseEndianness((uint)(value >> 32)); } } }
39.410853
102
0.571794
[ "MIT" ]
3F/coreclr
src/System.Private.CoreLib/shared/System/Buffers/Binary/Reader.cs
5,084
C#
using Orchard.AuditTrail.Services; using Orchard.AuditTrail.Services.Models; using Orchard.Environment.Extensions; namespace Orchard.AuditTrail.Providers.Users { [OrchardFeature("Orchard.AuditTrail.Users")] public class UserAuditTrailEventProvider : AuditTrailEventProviderBase { public const string LoggedIn = "LoggedIn"; public const string LoggedOut = "LoggedOut"; public const string LogInFailed = "LogInFailed"; public const string PasswordChanged = "PasswordChanged"; public override void Describe(DescribeContext context) { context.For("User", T("Users")) .Event(this, LoggedIn, T("Logged in"), T("A user was successfully logged in."), enableByDefault: true) .Event(this, LoggedOut, T("Logged out"), T("A user actively logged out."), enableByDefault: true) .Event(this, LogInFailed, T("Login failed"), T("An attempt to login failed due to incorrect credentials."), enableByDefault: true) .Event(this, PasswordChanged, T("Password changed"), T("A user's password was changed."), enableByDefault: true); } } }
55.857143
147
0.672634
[ "BSD-3-Clause" ]
Lombiq/Associativy
src/Orchard.Web/Modules/Orchard.AuditTrail/Providers/Users/UserAuditTrailEventProvider.cs
1,175
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.CloudFormation; using Amazon.ElasticBeanstalk; using Amazon.ElasticBeanstalk.Model; using AWS.Deploy.Common; using AWS.Deploy.Common.IO; using AWS.Deploy.Common.Recipes; using AWS.Deploy.Orchestration.Data; using AWS.Deploy.Orchestration.LocalUserSettings; using AWS.Deploy.Recipes.CDK.Common; namespace AWS.Deploy.Orchestration.Utilities { public interface IDeployedApplicationQueryer { /// <summary> /// Get the list of existing deployed <see cref="CloudApplication"/> based on the deploymentTypes filter. /// </summary> Task<List<CloudApplication>> GetExistingDeployedApplications(List<DeploymentTypes> deploymentTypes); /// <summary> /// Get the list of compatible applications by matching elements of the CloudApplication RecipeId and the recommendation RecipeId. /// </summary> Task<List<CloudApplication>> GetCompatibleApplications(List<Recommendation> recommendations, List<CloudApplication>? allDeployedApplications = null, OrchestratorSession? session = null); /// <summary> /// Checks if the given recommendation can be used for a redeployment to an existing cloudformation stack. /// </summary> bool IsCompatible(CloudApplication application, Recommendation recommendation); /// <summary> /// Gets the current option settings associated with the cloud application. This method is only used for non-CloudFormation based cloud applications. /// </summary> Task<IDictionary<string, object>> GetPreviousSettings(CloudApplication application); } public class DeployedApplicationQueryer : IDeployedApplicationQueryer { private readonly IAWSResourceQueryer _awsResourceQueryer; private readonly ILocalUserSettingsEngine _localUserSettingsEngine; private readonly IOrchestratorInteractiveService _orchestratorInteractiveService; public DeployedApplicationQueryer( IAWSResourceQueryer awsResourceQueryer, ILocalUserSettingsEngine localUserSettingsEngine, IOrchestratorInteractiveService orchestratorInteractiveService) { _awsResourceQueryer = awsResourceQueryer; _localUserSettingsEngine = localUserSettingsEngine; _orchestratorInteractiveService = orchestratorInteractiveService; } public async Task<List<CloudApplication>> GetExistingDeployedApplications(List<DeploymentTypes> deploymentTypes) { var existingApplications = new List<CloudApplication>(); if (deploymentTypes.Contains(DeploymentTypes.CdkProject)) existingApplications.AddRange(await GetExistingCloudFormationStacks()); if (deploymentTypes.Contains(DeploymentTypes.BeanstalkEnvironment)) existingApplications.AddRange(await GetExistingBeanstalkEnvironments()); return existingApplications; } /// <summary> /// Filters the applications that can be re-deployed using the current set of available recommendations. /// </summary> /// <returns>A list of <see cref="CloudApplication"/> that are compatible for a re-deployment</returns> public async Task<List<CloudApplication>> GetCompatibleApplications(List<Recommendation> recommendations, List<CloudApplication>? allDeployedApplications = null, OrchestratorSession? session = null) { var compatibleApplications = new List<CloudApplication>(); if (allDeployedApplications == null) allDeployedApplications = await GetExistingDeployedApplications(recommendations.Select(x => x.Recipe.DeploymentType).ToList()); foreach (var application in allDeployedApplications) { if (recommendations.Any(rec => IsCompatible(application, rec))) { compatibleApplications.Add(application); } } if (session != null) { try { await _localUserSettingsEngine.CleanOrphanStacks(allDeployedApplications.Select(x => x.Name).ToList(), session.ProjectDefinition.ProjectName, session.AWSAccountId, session.AWSRegion); var deploymentManifest = await _localUserSettingsEngine.GetLocalUserSettings(); var lastDeployedStack = deploymentManifest?.LastDeployedStacks? .FirstOrDefault(x => x.Exists(session.AWSAccountId, session.AWSRegion, session.ProjectDefinition.ProjectName)); return compatibleApplications .Select(x => { x.UpdatedByCurrentUser = lastDeployedStack?.Stacks?.Contains(x.Name) ?? false; return x; }) .OrderByDescending(x => x.UpdatedByCurrentUser) .ThenByDescending(x => x.LastUpdatedTime) .ToList(); } catch (FailedToUpdateLocalUserSettingsFileException ex) { _orchestratorInteractiveService.LogErrorMessage(ex.Message); _orchestratorInteractiveService.LogDebugMessage(ex.PrettyPrint()); } catch (InvalidLocalUserSettingsFileException ex) { _orchestratorInteractiveService.LogErrorMessage(ex.Message); _orchestratorInteractiveService.LogDebugMessage(ex.PrettyPrint()); } } return compatibleApplications .OrderByDescending(x => x.LastUpdatedTime) .ToList(); } /// <summary> /// Checks if the given recommendation can be used for a redeployment to an existing cloudformation stack. /// </summary> public bool IsCompatible(CloudApplication application, Recommendation recommendation) { // For persisted projects check both the recipe id and the base recipe id for compatibility. The base recipe id check is for stacks that // were first created by a system recipe and then later moved to a persisted deployment project. if (recommendation.Recipe.PersistedDeploymentProject) { return string.Equals(recommendation.Recipe.Id, application.RecipeId, StringComparison.Ordinal) || string.Equals(recommendation.Recipe.BaseRecipeId, application.RecipeId, StringComparison.Ordinal); } return string.Equals(recommendation.Recipe.Id, application.RecipeId, StringComparison.Ordinal); } /// <summary> /// Gets the current option settings associated with the cloud application.This method is only used for non-CloudFormation based cloud applications. /// </summary> public async Task<IDictionary<string, object>> GetPreviousSettings(CloudApplication application) { IDictionary<string, object> previousSettings; switch (application.ResourceType) { case CloudApplicationResourceType.BeanstalkEnvironment: previousSettings = await GetBeanstalkEnvironmentConfigurationSettings(application.Name); break; default: throw new InvalidOperationException($"Cannot fetch existing option settings for the following {nameof(CloudApplicationResourceType)}: {application.ResourceType}"); } return previousSettings; } /// <summary> /// Fetches existing CloudFormation stacks created by the AWS .NET deployment tool /// </summary> /// <returns>A list of <see cref="CloudApplication"/></returns> private async Task<List<CloudApplication>> GetExistingCloudFormationStacks() { var stacks = await _awsResourceQueryer.GetCloudFormationStacks(); var apps = new List<CloudApplication>(); foreach (var stack in stacks) { // Check to see if stack has AWS .NET deployment tool tag and the stack is not deleted or in the process of being deleted. var deployTag = stack.Tags.FirstOrDefault(tags => string.Equals(tags.Key, Constants.CloudFormationIdentifier.STACK_TAG)); // Skip stacks that don't have AWS .NET deployment tool tag if (deployTag == null || // Skip stacks does not have AWS .NET deployment tool description prefix. (This is filter out stacks that have the tag propagated to it like the Beanstalk stack) (stack.Description == null || !stack.Description.StartsWith(Constants.CloudFormationIdentifier.STACK_DESCRIPTION_PREFIX)) || // Skip tags that are deleted or in the process of being deleted stack.StackStatus.ToString().StartsWith("DELETE")) { continue; } // ROLLBACK_COMPLETE occurs when a stack creation fails and successfully rollbacks with cleaning partially created resources. // In this state, only a delete operation can be performed. (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html) // We don't want to include ROLLBACK_COMPLETE because it never succeeded to deploy. // However, a customer can give name of new application same as ROLLBACK_COMPLETE stack, which will trigger the re-deployment flow on the ROLLBACK_COMPLETE stack. if (stack.StackStatus == StackStatus.ROLLBACK_COMPLETE) { continue; } // If a list of compatible recommendations was given then skip existing applications that were used with a // recipe that is not compatible. var recipeId = deployTag.Value; apps.Add(new CloudApplication(stack.StackName, stack.StackId, CloudApplicationResourceType.CloudFormationStack, recipeId, stack.LastUpdatedTime)); } return apps; } /// <summary> /// Fetches existing Elastic Beanstalk environments that can serve as a deployment target. /// These environments must have a valid dotnet specific platform arn. /// Any environment that was created via the AWS .NET deployment tool as part of a CloudFormation stack is not included. /// </summary> /// <returns>A list of <see cref="CloudApplication"/></returns> private async Task<List<CloudApplication>> GetExistingBeanstalkEnvironments() { var validEnvironments = new List<CloudApplication>(); var environments = await _awsResourceQueryer.ListOfElasticBeanstalkEnvironments(); if (!environments.Any()) return validEnvironments; var dotnetPlatformArns = (await _awsResourceQueryer.GetElasticBeanstalkPlatformArns()).Select(x => x.PlatformArn).ToList(); // only select environments that have a dotnet specific platform ARN. environments = environments.Where(x => x.Status == EnvironmentStatus.Ready && dotnetPlatformArns.Contains(x.PlatformArn)).ToList(); foreach (var env in environments) { var tags = await _awsResourceQueryer.ListElasticBeanstalkResourceTags(env.EnvironmentArn); // skips all environments that were created via the deploy tool. if (tags.Any(x => string.Equals(x.Key, Constants.CloudFormationIdentifier.STACK_TAG))) continue; validEnvironments.Add(new CloudApplication(env.EnvironmentName, env.EnvironmentId, CloudApplicationResourceType.BeanstalkEnvironment, Constants.RecipeIdentifier.EXISTING_BEANSTALK_ENVIRONMENT_RECIPE_ID, env.DateUpdated)); } return validEnvironments; } private async Task<IDictionary<string, object>> GetBeanstalkEnvironmentConfigurationSettings(string environmentName) { IDictionary<string, object> optionSettings = new Dictionary<string, object>(); var configurationSettings = await _awsResourceQueryer.GetBeanstalkEnvironmentConfigurationSettings(environmentName); foreach (var tuple in Constants.ElasticBeanstalk.OptionSettingQueryList) { var configurationSetting = GetBeanstalkEnvironmentConfigurationSetting(configurationSettings, tuple.OptionSettingNameSpace, tuple.OptionSettingName); if (string.IsNullOrEmpty(configurationSetting?.Value)) continue; optionSettings[tuple.OptionSettingId] = configurationSetting.Value; } return optionSettings; } private ConfigurationOptionSetting GetBeanstalkEnvironmentConfigurationSetting(List<ConfigurationOptionSetting> configurationSettings, string optionNameSpace, string optionName) { var configurationSetting = configurationSettings .FirstOrDefault(x => string.Equals(optionNameSpace, x.Namespace) && string.Equals(optionName, x.OptionName)); return configurationSetting; } } }
51.885057
237
0.665707
[ "MIT" ]
96malhar/aws-dotnet-deploy
src/AWS.Deploy.Orchestration/Utilities/DeployedApplicationQueryer.cs
13,542
C#
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace OpenShift.DotNet.Service.Models { using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Rest; using Microsoft.Rest.Serialization; /// <summary> /// Affinity is a group of affinity scheduling rules. /// </summary> public partial class Iok8sapicorev1Affinity { /// <summary> /// Initializes a new instance of the Iok8sapicorev1Affinity class. /// </summary> public Iok8sapicorev1Affinity() { } /// <summary> /// Initializes a new instance of the Iok8sapicorev1Affinity class. /// </summary> public Iok8sapicorev1Affinity(Iok8sapicorev1NodeAffinity nodeAffinity = default(Iok8sapicorev1NodeAffinity), Iok8sapicorev1PodAffinity podAffinity = default(Iok8sapicorev1PodAffinity), Iok8sapicorev1PodAntiAffinity podAntiAffinity = default(Iok8sapicorev1PodAntiAffinity)) { NodeAffinity = nodeAffinity; PodAffinity = podAffinity; PodAntiAffinity = podAntiAffinity; } /// <summary> /// Describes node affinity scheduling rules for the pod. /// </summary> [JsonProperty(PropertyName = "nodeAffinity")] public Iok8sapicorev1NodeAffinity NodeAffinity { get; set; } /// <summary> /// Describes pod affinity scheduling rules (e.g. co-locate this pod /// in the same node, zone, etc. as some other pod(s)). /// </summary> [JsonProperty(PropertyName = "podAffinity")] public Iok8sapicorev1PodAffinity PodAffinity { get; set; } /// <summary> /// Describes pod anti-affinity scheduling rules (e.g. avoid putting /// this pod in the same node, zone, etc. as some other pod(s)). /// </summary> [JsonProperty(PropertyName = "podAntiAffinity")] public Iok8sapicorev1PodAntiAffinity PodAntiAffinity { get; set; } /// <summary> /// Validate the object. Throws ValidationException if validation fails. /// </summary> public virtual void Validate() { if (this.NodeAffinity != null) { this.NodeAffinity.Validate(); } } } }
36.666667
280
0.63595
[ "MIT" ]
gbraad/OpenShift.Vsix
OpenShift.DotNet.Service.Netfx/OpenShift API (with Kubernetes)/Models/Iok8sapicorev1Affinity.cs
2,422
C#
namespace Neovolve.Toolkit.Communication { /// <summary> /// The Neovolve.Toolkit.Communication namespace contains classes that provide communication related functionality. /// The communication support includes local, distributed and debugging implementations. /// </summary> internal static class NamespaceDoc { } }
34.8
119
0.732759
[ "MIT" ]
roryprimrose/Neovolve.Toolkit
Neovolve.Toolkit/Communication/NamespaceDoc.cs
350
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; namespace Microsoft.NetCore.Analyzers.InteropServices { /// <summary> /// CA1414: Mark boolean PInvoke arguments with MarshalAs /// </summary> public abstract class MarkBooleanPInvokeArgumentsWithMarshalAsFixer : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(MarkBooleanPInvokeArgumentsWithMarshalAsAnalyzer.RuleId); public sealed override FixAllProvider GetFixAllProvider() { // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers return WellKnownFixAllProviders.BatchFixer; } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { // Fixer not yet implemented. return Task.CompletedTask; } } }
39.758621
160
0.731136
[ "Apache-2.0" ]
LingxiaChen/roslyn-analyzers
src/Microsoft.NetCore.Analyzers/Core/InteropServices/MarkBooleanPInvokeArgumentsWithMarshalAs.Fixer.cs
1,153
C#
#nullable disable namespace PasPasPas.Parsing.SyntaxTree.Standard { /// <summary> /// current class declaration mode /// </summary> public enum ClassDeclarationMode { /// <summary> /// undefined mode /// </summary> Undefined = 0, /// <summary> /// declaring fields /// </summary> Fields = 1, /// <summary> /// declaring class fields /// </summary> ClassFields = 2, /// <summary> /// declaring other things (methods, properties, constants, etc.) /// </summary> Other = 3, } }
21.3125
78
0.464809
[ "Apache-2.0" ]
prjm/paspaspas
PasPasPas.Parsing/src/SyntaxTree/Standard/ClassDeclarationMode.cs
684
C#
using System; using System.Collections.Concurrent; namespace KitchenSink { public static partial class Operators { /// <summary> /// Forward function composition. /// </summary> public static Func<A, C> Compose<A, B, C>( Func<A, B> f, Func<B, C> g) => x => g(f(x)); /// <summary> /// Forward function composition. /// </summary> public static Func<A, D> Compose<A, B, C, D>( Func<A, B> f, Func<B, C> g, Func<C, D> h) => x => h(g(f(x))); /// <summary> /// Forward function composition. /// </summary> public static Func<A, E> Compose<A, B, C, D, E>( Func<A, B> f, Func<B, C> g, Func<C, D> h, Func<D, E> i) => x => i(h(g(f(x)))); /// <summary> /// Forward function composition. /// </summary> public static Func<A, F> Compose<A, B, C, D, E, F>( Func<A, B> f, Func<B, C> g, Func<C, D> h, Func<D, E> i, Func<E, F> j) => x => j(i(h(g(f(x))))); /// <summary> /// Function currying. /// </summary> public static Func<A, Func<B, C>> Curry<A, B, C>( Func<A, B, C> f) => x => y => f(x, y); /// <summary> /// Function currying. /// </summary> public static Func<A, Func<B, Func<C, D>>> Curry<A, B, C, D>( Func<A, B, C, D> f) => x => y => z => f(x, y, z); /// <summary> /// Function currying. /// </summary> public static Func<A, Func<B, Func<C, Func<D, E>>>> Curry<A, B, C, D, E>( Func<A, B, C, D, E> f) => x => y => z => w => f(x, y, z, w); /// <summary> /// Function un-currying. /// </summary> public static Func<A, B, C> Uncurry<A, B, C>( Func<A, Func<B, C>> f) => (x, y) => f(x)(y); /// <summary> /// Function un-currying. /// </summary> public static Func<A, B, C, D> Uncurry<A, B, C, D>( Func<A, Func<B, Func<C, D>>> f) => (x, y, z) => f(x)(y)(z); /// <summary> /// Function un-currying. /// </summary> public static Func<A, B, C, D, E> Uncurry<A, B, C, D, E>( Func<A, Func<B, Func<C, Func<D, E>>>> f) => (x, y, z, w) => f(x)(y)(z)(w); /// <summary> /// Join parameters into tuple. /// </summary> public static Func<(A, B), Z> Tuplize<A, B, Z>(Func<A, B, Z> f) => t => f(t.Item1, t.Item2); /// <summary> /// Join parameters into tuple. /// </summary> public static Func<(A, B, C), Z> Tuplize<A, B, C, Z>(Func<A, B, C, Z> f) => t => f(t.Item1, t.Item2, t.Item3); /// <summary> /// Join parameters into tuple. /// </summary> public static Func<(A, B, C, D), Z> Tuplize<A, B, C, D, Z>(Func<A, B, C, D, Z> f) => t => f(t.Item1, t.Item2, t.Item3, t.Item4); /// <summary> /// Join parameters into tuple. /// </summary> public static Action<(A, B)> Tuplize<A, B>(Action<A, B> f) => t => f(t.Item1, t.Item2); /// <summary> /// Join parameters into tuple. /// </summary> public static Action<(A, B, C)> Tuplize<A, B, C>(Action<A, B, C> f) => t => f(t.Item1, t.Item2, t.Item3); /// <summary> /// Join parameters into tuple. /// </summary> public static Action<(A, B, C, D)> Tuplize<A, B, C, D>(Action<A, B, C, D> f) => t => f(t.Item1, t.Item2, t.Item3, t.Item4); /// <summary> /// Split parameters from tuple. /// </summary> public static Func<A, B, Z> Detuplize<A, B, Z>(Func<(A, B), Z> f) => (a, b) => f((a, b)); /// <summary> /// Split parameters from tuple. /// </summary> public static Func<A, B, C, Z> Detuplize<A, B, C, Z>(Func<(A, B, C), Z> f) => (a, b, c) => f((a, b, c)); /// <summary> /// Split parameters from tuple. /// </summary> public static Func<A, B, C, D, Z> Detuplize<A, B, C, D, Z>(Func<(A, B, C, D), Z> f) => (a, b, c, d) => f((a, b, c, d)); /// <summary> /// Split parameters from tuple. /// </summary> public static Action<A, B> Detuplize<A, B>(Action<(A, B)> f) => (a, b) => f((a, b)); /// <summary> /// Split parameters from tuple. /// </summary> public static Action<A, B, C> Detuplize<A, B, C>(Action<(A, B, C)> f) => (a, b, c) => f((a, b, c)); /// <summary> /// Split parameters from tuple. /// </summary> public static Action<A, B, C, D> Detuplize<A, B, C, D>(Action<(A, B, C, D)> f) => (a, b, c, d) => f((a, b, c, d)); /// <summary> /// Wrap function with one that takes placeholder Unit. /// </summary> public static Func<Unit, Z> TakeUnit<Z>(Func<Z> f) => _ => f(); /// <summary> /// Wrap function with one that takes placeholder Unit. /// </summary> public static Action<Unit> TakeUnit(Action f) => _ => f(); /// <summary> /// Wrap function with one that gives placeholder Unit. /// </summary> public static Func<Z> GiveUnit<Z>(Func<Unit, Z> f) => () => f(Unit.It); /// <summary> /// Wrap function with one that gives placeholder Unit. /// </summary> public static Action GiveUnit(Action<Unit> f) => () => f(Unit.It); /// <summary> /// Partially apply function. /// </summary> public static Func<B, Z> Apply<A, B, Z>(Func<A, B, Z> f, A a) => b => f(a, b); /// <summary> /// Partially apply function. /// </summary> public static Func<B, C, Z> Apply<A, B, C, Z>(Func<A, B, C, Z> f, A a) => (b, c) => f(a, b, c); /// <summary> /// Partially apply function. /// </summary> public static Func<C, Z> Apply<A, B, C, Z>(Func<A, B, C, Z> f, A a, B b) => c => f(a, b, c); /// <summary> /// Partially apply function. /// </summary> public static Func<B, C, D, Z> Apply<A, B, C, D, Z>(Func<A, B, C, D, Z> f, A a) => (b, c, d) => f(a, b, c, d); /// <summary> /// Partially apply function. /// </summary> public static Func<C, D, Z> Apply<A, B, C, D, Z>(Func<A, B, C, D, Z> f, A a, B b) => (c, d) => f(a, b, c, d); /// <summary> /// Partially apply function. /// </summary> public static Func<D, Z> Apply<A, B, C, D, Z>(Func<A, B, C, D, Z> f, A a, B b, C c) => d => f(a, b, c, d); /// <summary> /// Flip function arguments. /// </summary> public static Func<B, A, Z> Flip<A, B, Z>(Func<A, B, Z> f) => (b, a) => f(a, b); /// <summary> /// Rotate function arguments forward. /// </summary> public static Func<C, A, B, Z> Rotate<A, B, C, Z>(Func<A, B, C, Z> f) => (c, a, b) => f(a, b, c); /// <summary> /// Rotate function arguments backward. /// </summary> public static Func<B, C, A, Z> RotateBack<A, B, C, Z>(Func<A, B, C, Z> f) => (b, c, a) => f(a, b, c); /// <summary> /// Wrap function with memoizing cache. /// </summary> public static Func<Z> Memo<Z>(Func<Z> f) { var cache = new Lazy<Z>(f); return () => cache.Value; } /// <summary> /// Wrap function with memoizing cache. /// </summary> public static Func<A, Z> Memo<A, Z>(Func<A, Z> f) { var cache = new ConcurrentDictionary<A, Z>(); return a => cache.GetOrAdd(a, f); } /// <summary> /// Wrap function with memoizing cache. /// </summary> public static Func<A, B, Z> Memo<A, B, Z>(Func<A, B, Z> f) => Detuplize(Memo(Tuplize(f))); /// <summary> /// Wrap function with memoizing cache. /// </summary> public static Func<A, B, C, Z> Memo<A, B, C, Z>(Func<A, B, C, Z> f) => Detuplize(Memo(Tuplize(f))); /// <summary> /// Wrap function with memoizing cache. /// </summary> public static Func<A, B, C, D, Z> Memo<A, B, C, D, Z>(Func<A, B, C, D, Z> f) => Detuplize(Memo(Tuplize(f))); /// <summary> /// Wrap function with memoizing cache with an expiration timeout. /// </summary> public static Func<Z> Memo<Z>(TimeSpan timeout, Func<Z> f) => GiveUnit(Memo(timeout, TakeUnit(f))); /// <summary> /// Wrap function with memoizing cache with an expiration timeout. /// </summary> public static Func<A, Z> Memo<A, Z>(TimeSpan timeout, Func<A, Z> f) { var cache = new ConcurrentDictionary<A, (DateTime, Z)>(); return a => cache.AddOrUpdate( a, _ => (DateTime.UtcNow, f(a)), (_, current) => DateTime.UtcNow - current.Item1 > timeout ? (DateTime.UtcNow, f(a)) : current).Item2; } /// <summary> /// Wrap function with memoizing cache with an expiration timeout. /// </summary> public static Func<A, B, Z> Memo<A, B, Z>(TimeSpan timeout, Func<A, B, Z> f) => Detuplize(Memo(timeout, Tuplize(f))); /// <summary> /// Wrap function with memoizing cache with an expiration timeout. /// </summary> public static Func<A, B, C, Z> Memo<A, B, C, Z>(TimeSpan timeout, Func<A, B, C, Z> f) => Detuplize(Memo(timeout, Tuplize(f))); /// <summary> /// Wrap function with memoizing cache with an expiration timeout. /// </summary> public static Func<A, B, C, D, Z> Memo<A, B, C, D, Z>(TimeSpan timeout, Func<A, B, C, D, Z> f) => Detuplize(Memo(timeout, Tuplize(f))); /// <summary> /// Wraps action so it won't be called more frequently than given timeout. /// </summary> public static Action Debounce(TimeSpan timeout, Action f) => GiveUnit(Debounce(timeout, TakeUnit(f))); /// <summary> /// Wraps action so it won't be called more frequently than given timeout. /// </summary> public static Action<A> Debounce<A>(TimeSpan timeout, Action<A> f) { var atom = Atom.Of(DateTime.MinValue); return a => { atom.Update(prev => { if (DateTime.UtcNow - prev > timeout) { f(a); return DateTime.UtcNow; } return prev; }); }; } /// <summary> /// Wraps action so it won't be called more frequently than given timeout. /// </summary> public static Action<A, B> Debounce<A, B>(TimeSpan timeout, Action<A, B> f) => Detuplize(Debounce(timeout, Tuplize(f))); /// <summary> /// Wraps action so it won't be called more frequently than given timeout. /// </summary> public static Action<A, B, C> Debounce<A, B, C>(TimeSpan timeout, Action<A, B, C> f) => Detuplize(Debounce(timeout, Tuplize(f))); /// <summary> /// Wraps action so it won't be called more frequently than given timeout. /// </summary> public static Action<A, B, C, D> Debounce<A, B, C, D>(TimeSpan timeout, Action<A, B, C, D> f) => Detuplize(Debounce(timeout, Tuplize(f))); /// <summary> /// Returns an IDisposable that, when <c>Dispose</c>d, calls the given function. /// </summary> public static IDisposable Disposable(Action f) => new DisposableAction(f); internal class DisposableAction : IDisposable { private readonly Action f; internal DisposableAction(Action f) => this.f = f; public void Dispose() => f(); } } }
34.100543
105
0.458762
[ "MIT" ]
rkoeninger/KitchenSink
src/KitchenSink/Operators.Functions.cs
12,551
C#
using AoE2Lib; using AoE2Lib.Bots; using AoE2Lib.Bots.GameElements; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using static Unary.Managers.MilitaryManager; namespace Unary.UnitControllers { class ScoutController : UnitController { public Position AttractorPosition { get; set; } = Position.Zero; public double AttractorRadius { get; set; } = 0; public double ExploredFraction { get; set; } = 0.7; public ScoutingState State { get; private set; } = null; private TimeSpan LastDistanceChangeGameTime { get; set; } = TimeSpan.MinValue; private double LastDistance { get; set; } = 0; public ScoutController(Unit scout, Unary unary) : base(scout, unary) { } protected override void Tick() { if (State == null) { FindState(); } if (State != null) { ExploreState(); } } private void FindState() { var los = 4; ScoutingState best = null; var best_cost = double.MaxValue; var my_pos = Unit.Position; foreach (var state in Unary.MilitaryManager.GetScoutingStatesForLos(los)) { if (state.LastAttemptGameTime > TimeSpan.Zero) { continue; } var total = 0d; var explored = 0d; foreach (var tile in Unary.GameState.Map.GetTilesInRange(state.Tile.X, state.Tile.Y, los)) { total++; if (tile.Explored) { explored++; } } explored /= Math.Max(1, total); if (explored < ExploredFraction) { var cost = state.Tile.Position.DistanceTo(my_pos) + Math.Abs(AttractorRadius - state.Tile.Position.DistanceTo(AttractorPosition)); if (best == null || cost < best_cost) { best = state; best_cost = cost; } } } if (best != null) { State = best; Unary.Log.Info($"Scouting {best.Tile.Position}"); } } private void ExploreState() { State.LastAttemptGameTime = Unary.GameState.GameTime; var target_pos = State.Tile.Center; var distance = target_pos.DistanceTo(Unit.Position); if (Math.Abs(distance - LastDistance) > 1) { LastDistanceChangeGameTime = Unary.GameState.GameTime; LastDistance = distance; } var time = Unary.GameState.GameTime - LastDistanceChangeGameTime; if (target_pos.DistanceTo(Unit.Position) > 1 && time < TimeSpan.FromSeconds(3)) { Unit.Target(target_pos, UnitAction.MOVE); } else { State = null; } } } }
28.854701
106
0.482524
[ "MIT" ]
01010100b/AoE2Lib
Unary/UnitControllers/ScoutController.cs
3,378
C#
 using UnityEngine; using DG.Tweening; using System.Collections.Generic; namespace UChart.HeatMap { public enum HeatMapMode { RefreshEachFrame, RefreshByInterval } public class HeatMapComponent : MonoBehaviour { // TODO: set point properties for shader properties. // TODO: get mesh.material private Material m_material = null; public Material material { get { if( null == m_material ) { var render = this.GetComponent<Renderer>(); if( null == render) throw new UChartNotFoundException("Can not found Renderer component on HeatMapComponent"); m_material = render.material; } return m_material; } } public HeatMapMode heatMapMode = HeatMapMode.RefreshEachFrame; // 热力图刷新间隔 TODO: 支持设置为每帧刷新 public float interval = 0.02f; private float m_timer = 0.0f; public bool mimic = false; private float m_mimicInterval = 1.0f; private float m_mimicTiemr = 0.0f; public List<HeatMapFactor> impactFactors = new List<HeatMapFactor>(); private void Update() { if (mimic) { m_mimicTiemr += Time.deltaTime; if (m_mimicTiemr > m_mimicInterval) { foreach (var factor in impactFactors) { float lerp = factor.temperatureFactor; DOTween.To(() => lerp, x => lerp = x, Random.Range(0.1f, 3.0f), m_mimicInterval).OnUpdate(() => { factor.temperatureFactor = lerp; }); } m_mimicTiemr = 0.0f; } } if( heatMapMode == HeatMapMode.RefreshEachFrame ) { RefreshHeatmap(); return; } m_timer += Time.deltaTime; if( m_timer > interval ) { RefreshHeatmap(); m_timer -= interval; } } private void RefreshHeatmap() { // set impact factor count material.SetInt("_FactorCount",impactFactors.Count); // set impact factors var ifPosition = new Vector4[impactFactors.Count]; for( int i = 0 ; i < impactFactors.Count;i++ ) ifPosition[i] = impactFactors[i].transform.position; material.SetVectorArray("_Factors",ifPosition); // set factor properties var properties = new Vector4[impactFactors.Count]; for (int i = 0; i < impactFactors.Count; i++) { var factor = impactFactors[i]; properties[i] = new Vector4(factor.influenceRadius, factor.intensity,factor.temperatureFactor,0.0f); } material.SetVectorArray("_FactorsProperties",properties); // TODO: 将温度本身数值作为一个影响因子累乘 // set factor values //var values = new float[impactFactors.Count]; //for( int i = 0 ; i < impactFactors.Count;i++ ) // values[i] = Random.Range(0,5); //material.SetFloatArray("_FactorsValues",values); } } }
32.214953
119
0.507398
[ "MIT" ]
ll4080333/UChart
UChart/Assets/UChart/Scripts/Solutions/HeatMap/3D/HeatMapComponent.cs
3,515
C#
using System; using System.IO; using Microsoft.Xna.Framework; namespace Nez { public static class EffectResource { // sprite effects internal static byte[] spriteBlinkEffectBytes { get { return getFileResourceBytes( "Content/nez/effects/SpriteBlinkEffect.mgfxo" ); } } internal static byte[] spriteLinesEffectBytes { get { return getFileResourceBytes( "Content/nez/effects/SpriteLines.mgfxo" ); } } internal static byte[] spriteAlphaTestBytes { get { return getFileResourceBytes( "Content/nez/effects/SpriteAlphaTest.mgfxo" ); } } internal static byte[] crosshatchBytes { get { return getFileResourceBytes( "Content/nez/effects/Crosshatch.mgfxo" ); } } internal static byte[] noiseBytes { get { return getFileResourceBytes( "Content/nez/effects/Noise.mgfxo" ); } } internal static byte[] twistBytes { get { return getFileResourceBytes( "Content/nez/effects/Twist.mgfxo" ); } } internal static byte[] dotsBytes { get { return getFileResourceBytes( "Content/nez/effects/Dots.mgfxo" ); } } internal static byte[] dissolveBytes { get { return getFileResourceBytes( "Content/nez/effects/Dissolve.mgfxo" ); } } // post processor effects internal static byte[] bloomCombineBytes { get { return getFileResourceBytes( "Content/nez/effects/BloomCombine.mgfxo" ); } } internal static byte[] bloomExtractBytes { get { return getFileResourceBytes( "Content/nez/effects/BloomExtract.mgfxo" ); } } internal static byte[] gaussianBlurBytes { get { return getFileResourceBytes( "Content/nez/effects/GaussianBlur.mgfxo" ); } } internal static byte[] vignetteBytes { get { return getFileResourceBytes( "Content/nez/effects/Vignette.mgfxo" ); } } internal static byte[] letterboxBytes { get { return getFileResourceBytes( "Content/nez/effects/Letterbox.mgfxo" ); } } internal static byte[] heatDistortionBytes { get { return getFileResourceBytes( "Content/nez/effects/HeatDistortion.mgfxo" ); } } internal static byte[] spriteLightMultiplyBytes { get { return getFileResourceBytes( "Content/nez/effects/SpriteLightMultiply.mgfxo" ); } } internal static byte[] pixelGlitchBytes { get { return getFileResourceBytes( "Content/nez/effects/PixelGlitch.mgfxo" ); } } // deferred lighting internal static byte[] deferredSpriteBytes { get { return getFileResourceBytes( "Content/nez/effects/DeferredSprite.mgfxo" ); } } internal static byte[] deferredLightBytes { get { return getFileResourceBytes( "Content/nez/effects/DeferredLighting.mgfxo" ); } } // forward lighting internal static byte[] forwardLightingBytes { get { return getFileResourceBytes( "Content/nez/effects/ForwardLighting.mgfxo" ); } } internal static byte[] polygonLightBytes { get { return getFileResourceBytes( "Content/nez/effects/PolygonLight.mgfxo" ); } } // scene transitions internal static byte[] squaresTransitionBytes { get { return getFileResourceBytes( "Content/nez/effects/transitions/Squares.mgfxo" ); } } // sprite or post processor effects internal static byte[] spriteEffectBytes { get { return getMonoGameEmbeddedResourceBytes( "Microsoft.Xna.Framework.Graphics.Effect.Resources.SpriteEffect.ogl.mgfxo" ); } } internal static byte[] multiTextureOverlayBytes { get { return getFileResourceBytes( "Content/nez/effects/MultiTextureOverlay.mgfxo" ); } } internal static byte[] scanlinesBytes { get { return getFileResourceBytes( "Content/nez/effects/Scanlines.mgfxo" ); } } internal static byte[] reflectionBytes { get { return getFileResourceBytes( "Content/nez/effects/Reflection.mgfxo" ); } } internal static byte[] grayscaleBytes { get { return getFileResourceBytes( "Content/nez/effects/Grayscale.mgfxo" ); } } internal static byte[] sepiaBytes { get { return getFileResourceBytes( "Content/nez/effects/Sepia.mgfxo" ); } } internal static byte[] paletteCyclerBytes { get { return getFileResourceBytes( "Content/nez/effects/PaletteCycler.mgfxo" ); } } /// <summary> /// gets the raw byte[] from an EmbeddedResource /// </summary> /// <returns>The embedded resource bytes.</returns> /// <param name="name">Name.</param> static byte[] getEmbeddedResourceBytes( string name ) { var assembly = ReflectionUtils.getAssembly( typeof( EffectResource ) ); using( var stream = assembly.GetManifestResourceStream( name ) ) { using( var ms = new MemoryStream() ) { stream.CopyTo( ms ); return ms.ToArray(); } } } internal static byte[] getMonoGameEmbeddedResourceBytes( string name ) { #if FNA name = name.Replace( ".ogl.mgfxo", ".fxb" ); #endif var assembly = ReflectionUtils.getAssembly( typeof( MathHelper ) ); using( var stream = assembly.GetManifestResourceStream( name ) ) { using( var ms = new MemoryStream() ) { stream.CopyTo( ms ); return ms.ToArray(); } } } /// <summary> /// fetches the raw byte data of a file from the Content folder. Used to keep the Effect subclass code simple and clean due to the Effect /// constructor requiring the byte[]. /// </summary> /// <returns>The file resource bytes.</returns> /// <param name="path">Path.</param> public static byte[] getFileResourceBytes( string path ) { #if FNA path = path.Replace( ".mgfxo", ".fxb" ); #endif byte[] bytes; try { using( var stream = TitleContainer.OpenStream( path ) ) { bytes = new byte[stream.Length]; stream.Read( bytes, 0, bytes.Length ); } } catch( Exception e ) { var txt = string.Format( "OpenStream failed to find file at path: {0}. Did you add it to the Content folder?", path ); throw new Exception( txt, e ); } return bytes; } } }
46.975
173
0.719177
[ "MIT" ]
jkstrawn/gangsters
Nez/Nez.Portable/Graphics/Effects/EffectResource.cs
5,639
C#
using System; namespace Boolean6 { class Boolean6 { static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.UTF8; Console.WriteLine("Введите число A"); var a = int.Parse(Console.ReadLine()); Console.WriteLine("Введите число B"); var b = int.Parse(Console.ReadLine()); Console.WriteLine("Введите число C"); var c = int.Parse(Console.ReadLine()); bool isInequalityTrue = ((a < b) && (b < c)); Console.WriteLine($"Справедливо двойное неравенство A<B<C? - {isInequalityTrue}"); Console.ReadLine(); } } }
27.4
94
0.553285
[ "MIT" ]
levkovich-polina/CSharpStudy
src/Boolean6/Boolean6.cs
752
C#
using System.Collections.Generic; using WooshiiAttributes; using UnityEngine; using Director.Component; namespace Director { [System.Serializable] public class CameraSettings { public float fov = 60; // Clipping Planes public float clipNear = 0.1f; public float clipFar = 5000f; public Rect viewportRect = new Rect (0, 0, 1, 1); public void UpdateCamera(Camera cam) { cam.fieldOfView = fov; cam.nearClipPlane = clipNear; cam.farClipPlane = clipFar; cam.rect = viewportRect; } } //TODO: Create custom editor for references public class DirectorCamera : DirectorCore { //Drop downs for director states would be nice, future changes [HeaderLine ("Settings")] public DirectorState currentState = DirectorStatePresets.CinematicDistant; protected DirectorState previousState = DirectorStatePresets.ShoulderView; [HideInInspector] public Vector3 offset; [HideInInspector] public float radius = 7; [HideInInspector] public float fovVelocity; public CameraSettings settings = new CameraSettings(); [Range (0, 10)] public float moveDamp; [Range (0, 60)] public float rotationDamp; [HeaderLine ("Targets")] public bool canRotate = true; public bool canMove = true; public Transform follow; public Transform lookAt; [HideInInspector] public Vector3 displacement; [HideInInspector] public Vector3 transposeVelocity; [HeaderLine ("Components")] [HideInInspector] public DirectorComponent[] components; // -- Privates -- private Vector3 offsetVel; // --- Properties --- public Camera cam { get; private set; } public Transform CameraTransform => cam.transform; public Vector3 transposePosition { get; protected set; } public Quaternion transposeRotation { get; protected set; } public Vector3 localOffset => transform.rotation * currentState.originOffset; public Vector3 TargetOffset => transposeRotation * new Vector3 (localOffset.x, localOffset.y, localOffset.z - currentState.radius); protected virtual void Awake() { Initialize (); } protected virtual void Update() { UpdateStateData (); ComponentUpdate (); //Update camera data cam.fieldOfView = settings.fov; } protected virtual void FixedUpdate() { ComponentFixedUpdate (); } protected virtual void LateUpdate() { } protected void Initialize() { if (currentState == null) currentState = DirectorStatePresets.ThirdPersonView; radius = currentState.radius; settings.fov = currentState.targetFOV; offset = currentState.originOffset; cam = Camera.main; if (cam != null) cam.fieldOfView = settings.fov; InitalizeComponents (); } #region Setup Components protected void InitalizeComponents() { components = GetComponents<DirectorComponent> (); if (components.Length > 0) { foreach (var component in components) { component.Initialize (); component.directorCam = this; } } } protected void ComponentUpdate() { if (components != null) { foreach (var component in components) component.Execute (); } } protected void ComponentFixedUpdate() { if (components != null) { foreach (var component in components) component.FixedExecute (); } } #endregion private void UpdateStateData() { radius = currentState.radius; settings.fov = DirectorSmoothing.SmoothDamp (settings.fov, currentState.targetFOV, ref fovVelocity, currentState.fovDamp, Time.deltaTime); offset = DirectorSmoothing.SmoothDamp (offset, currentState.originOffset, ref offsetVel, Time.fixedDeltaTime, Time.deltaTime); if (Mathf.Abs (settings.fov - currentState.targetFOV) <= 0.001f) settings.fov = currentState.targetFOV; if (Mathf.Abs (radius - currentState.radius) <= 0.001f) radius = currentState.radius; } public void ChangeState(DirectorState newState) { previousState = currentState; currentState = newState; } public void ChangeState(string stateName) { if (DirectorStatePresets.GlobalStates.TryGetValue (stateName, out DirectorState state)) { previousState = currentState; currentState = state; } else { currentState = previousState; } } } }
29.71978
150
0.555556
[ "MIT" ]
WooshiiDev/The-Last-Day
The-Last-Day/Assets/Scripts/Wooshii/CameraDirector/Scripts/Core/CameraBase.cs
5,411
C#
namespace IDisposableAnalyzers { using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using Gu.Roslyn.AnalyzerExtensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; internal class RecursiveValues : IEnumerator<ExpressionSyntax> { private static readonly ConcurrentQueue<RecursiveValues> Cache = new ConcurrentQueue<RecursiveValues>(); private readonly List<ExpressionSyntax> values = new List<ExpressionSyntax>(); private readonly HashSet<SyntaxNode> checkedLocations = new HashSet<SyntaxNode>(); private int rawIndex = -1; private int recursiveIndex = -1; private IReadOnlyList<ExpressionSyntax> rawValues = null!; private SemanticModel semanticModel = null!; private CancellationToken cancellationToken; private RecursiveValues() { } object IEnumerator.Current => this.Current; public ExpressionSyntax Current => this.values[this.recursiveIndex]; internal bool IsEmpty => this.rawValues.Count == 0; public bool MoveNext() { if (this.recursiveIndex < this.values.Count - 1) { this.recursiveIndex++; return true; } if (this.rawIndex < this.rawValues.Count - 1) { this.rawIndex++; if (!this.AddRecursiveValues(this.rawValues[this.rawIndex])) { return this.MoveNext(); } this.recursiveIndex++; return true; } return false; } public void Reset() { this.recursiveIndex = -1; } public void Dispose() { this.values.Clear(); this.checkedLocations.Clear(); this.rawValues = null!; this.rawIndex = -1; this.recursiveIndex = -1; this.semanticModel = null!; this.cancellationToken = CancellationToken.None; Cache.Enqueue(this); } internal static RecursiveValues Borrow(IReadOnlyList<ExpressionSyntax> rawValues, SemanticModel semanticModel, CancellationToken cancellationToken) { var item = Cache.GetOrCreate(() => new RecursiveValues()); item.rawValues = rawValues; item.semanticModel = semanticModel; item.cancellationToken = cancellationToken; return item; } private bool AddRecursiveValues(ExpressionSyntax assignedValue) { if (assignedValue is null || assignedValue.IsMissing || !this.checkedLocations.Add(assignedValue)) { return false; } if (assignedValue.Parent is ArgumentSyntax argument && argument.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword)) { if (assignedValue.TryFirstAncestor(out InvocationExpressionSyntax? invocation) && this.semanticModel.TryGetSymbol(invocation, this.cancellationToken, out var target) && target.TrySingleMethodDeclaration(this.cancellationToken, out var targetDeclaration)) { if (targetDeclaration.TryFindParameter(argument, out var parameter) && this.semanticModel.TryGetSymbol(parameter, this.cancellationToken, out var parameterSymbol)) { using var assignedValues = AssignedValueWalker.Borrow(parameterSymbol, this.semanticModel, this.cancellationToken); assignedValues.HandleInvoke(target, invocation.ArgumentList); return this.AddManyRecursively(assignedValues); } return false; } this.values.Add(assignedValue); return true; } switch (assignedValue) { case ArrayCreationExpressionSyntax _: case DefaultExpressionSyntax _: case ElementAccessExpressionSyntax _: case ImplicitArrayCreationExpressionSyntax _: case InitializerExpressionSyntax _: case LiteralExpressionSyntax _: case ObjectCreationExpressionSyntax _: case TypeOfExpressionSyntax _: this.values.Add(assignedValue); return true; case BinaryExpressionSyntax { Left: { }, OperatorToken: { ValueText: "as" } } binary: return this.AddRecursiveValues(binary.Left); case BinaryExpressionSyntax { Left: { }, OperatorToken: { ValueText: "??" }, Right: { } } binary: var left = this.AddRecursiveValues(binary.Left); var right = this.AddRecursiveValues(binary.Right); return left || right; case CastExpressionSyntax cast: return this.AddRecursiveValues(cast.Expression); case ConditionalExpressionSyntax { WhenTrue: { }, WhenFalse: { } } conditional: var whenTrue = this.AddRecursiveValues(conditional.WhenTrue); var whenFalse = this.AddRecursiveValues(conditional.WhenFalse); return whenTrue || whenFalse; case SwitchExpressionSyntax { Arms: { } arms }: var added = false; foreach (var arm in arms) { added |= this.AddRecursiveValues(arm.Expression); } return added; case AwaitExpressionSyntax awaitExpression: using (var walker = ReturnValueWalker.Borrow(awaitExpression, ReturnValueSearch.RecursiveInside, this.semanticModel, this.cancellationToken)) { return this.AddManyRecursively(walker.ReturnValues); } case ConditionalAccessExpressionSyntax { WhenNotNull: { } whenNotNull }: return this.AddRecursiveValues(whenNotNull); } if (this.semanticModel.TryGetSymbol(assignedValue, this.cancellationToken, out var symbol)) { switch (symbol) { case ILocalSymbol _: using (var assignedValues = AssignedValueWalker.Borrow(assignedValue, this.semanticModel, this.cancellationToken)) { return this.AddManyRecursively(assignedValues); } case IParameterSymbol _: this.values.Add(assignedValue); using (var assignedValues = AssignedValueWalker.Borrow(assignedValue, this.semanticModel, this.cancellationToken)) { return this.AddManyRecursively(assignedValues); } case IFieldSymbol _: this.values.Add(assignedValue); return true; case IPropertySymbol _: case IMethodSymbol _: if (symbol.DeclaringSyntaxReferences.Length == 0) { this.values.Add(assignedValue); return true; } using (var walker = ReturnValueWalker.Borrow(assignedValue, ReturnValueSearch.RecursiveInside, this.semanticModel, this.cancellationToken)) { return this.AddManyRecursively(walker.ReturnValues); } } } return false; } private bool AddManyRecursively(IReadOnlyList<ExpressionSyntax> newValues) { var addedAny = false; foreach (var value in newValues) { addedAny |= this.AddRecursiveValues(value); } return addedAny; } } }
40.495146
163
0.552865
[ "MIT" ]
hackf5/IDisposableAnalyzers
IDisposableAnalyzers/Helpers/Pooled/RecursiveValues.cs
8,344
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Text; using Xunit; namespace System.Text.EncodingTests { public class TestEncoder : Encoder { public override int GetByteCount(char[] chars, int index, int count, bool flush) { throw new Exception("The method or operation is not implemented."); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { throw new Exception("The method or operation is not implemented."); } } public class EncoderCtor { #region Positive Test Cases // PosTest1: Call ctor to construct a new instance [Fact] public void PosTest1() { Encoder encoder = new TestEncoder(); Assert.NotNull(encoder); } #endregion } }
28.055556
121
0.627723
[ "MIT" ]
bpschoch/corefx
src/System.Text.Encoding/tests/Encoder/EncoderCtor.cs
1,010
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using System.Reflection; using Xunit; namespace System.Composition.Convention.Tests { public class ConventionBuilderTests { private interface IFoo { } private class FooImpl : IFoo { public string P1 { get; set; } public string P2 { get; set; } public IEnumerable<IFoo> P3 { get; set; } } private class FooImplWithConstructors : IFoo { public FooImplWithConstructors() { } public FooImplWithConstructors(IEnumerable<IFoo> ids) { } public FooImplWithConstructors(int id, string name) { } } [Fact] public void MapType_ShouldReturnProjectedAttributesForType() { var builder = new ConventionBuilder(); builder. ForTypesDerivedFrom<IFoo>(). Export<IFoo>(); Attribute[] fooImplAttributes = builder.GetDeclaredAttributes(typeof(FooImpl), typeof(FooImpl).GetTypeInfo()); Attribute[] fooImplWithConstructorsAttributes = builder.GetDeclaredAttributes(typeof(FooImplWithConstructors), typeof(FooImplWithConstructors).GetTypeInfo()); var exports = new List<object>(); exports.AddRange(fooImplAttributes); exports.AddRange(fooImplWithConstructorsAttributes); Assert.Equal(2, exports.Count); foreach (var exportAttribute in exports) { Assert.Equal(typeof(IFoo), ((ExportAttribute)exportAttribute).ContractType); Assert.Null(((ExportAttribute)exportAttribute).ContractName); } } [Fact] public void MapType_ConventionSelectedConstructor() { var builder = new ConventionBuilder(); builder. ForTypesDerivedFrom<IFoo>(). Export<IFoo>(); TypeInfo fooImplWithConstructorsTypeInfo = typeof(FooImplWithConstructors).GetTypeInfo(); // necessary as BuildConventionConstructorAttributes is only called for type level query for attributes ConstructorInfo constructor1 = fooImplWithConstructorsTypeInfo.DeclaredConstructors.Where(c => c.GetParameters().Length == 0).Single(); ConstructorInfo constructor2 = fooImplWithConstructorsTypeInfo.DeclaredConstructors.Where(c => c.GetParameters().Length == 1).Single(); ConstructorInfo constructor3 = fooImplWithConstructorsTypeInfo.DeclaredConstructors.Where(c => c.GetParameters().Length == 2).Single(); Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor1).Count()); Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor2).Count()); ConstructorInfo ci = constructor3; IEnumerable<Attribute> attrs = builder.GetCustomAttributes(typeof(FooImplWithConstructors), ci); Assert.Equal(1, attrs.Count()); Assert.Equal(typeof(ImportingConstructorAttribute), attrs.FirstOrDefault().GetType()); } [Fact] public void MapType_OverridingSelectionOfConventionSelectedConstructor() { var builder = new ConventionBuilder(); builder. ForTypesDerivedFrom<IFoo>(). Export<IFoo>(); builder.ForType<FooImplWithConstructors>() .SelectConstructor(cis => cis.Single(c => c.GetParameters().Length == 1)); TypeInfo fooImplWithConstructors = typeof(FooImplWithConstructors).GetTypeInfo(); ConstructorInfo constructor1 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 0).Single(); ConstructorInfo constructor2 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 1).Single(); ConstructorInfo constructor3 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 2).Single(); // necessary as BuildConventionConstructorAttributes is only called for type level query for attributes Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor1).Count()); Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor3).Count()); ConstructorInfo ci = constructor2; IEnumerable<Attribute> attrs = builder.GetCustomAttributes(typeof(FooImplWithConstructors), ci); Assert.Equal(1, attrs.Count()); Assert.Equal(typeof(ImportingConstructorAttribute), attrs.FirstOrDefault().GetType()); } [Fact] public void MapType_OverridingSelectionOfConventionSelectedConstructor_WithPartBuilderOfT() { var builder = new ConventionBuilder(); builder. ForTypesDerivedFrom<IFoo>(). Export<IFoo>(); builder.ForType<FooImplWithConstructors>(). SelectConstructor(param => new FooImplWithConstructors(param.Import<IEnumerable<IFoo>>())); TypeInfo fooImplWithConstructors = typeof(FooImplWithConstructors).GetTypeInfo(); ConstructorInfo constructor1 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 0).Single(); ConstructorInfo constructor2 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 1).Single(); ConstructorInfo constructor3 = fooImplWithConstructors.DeclaredConstructors.Where(c => c.GetParameters().Length == 2).Single(); // necessary as BuildConventionConstructorAttributes is only called for type level query for attributes Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor1).Count()); Assert.Equal(0, builder.GetCustomAttributes(typeof(FooImplWithConstructors), constructor3).Count()); ConstructorInfo ci = constructor2; IEnumerable<Attribute> attrs = builder.GetCustomAttributes(typeof(FooImplWithConstructors), ci); Assert.Equal(1, attrs.Count()); Assert.Equal(typeof(ImportingConstructorAttribute), attrs.FirstOrDefault().GetType()); } } }
48.156716
170
0.672865
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Composition.Convention/tests/ConventionBuilderTests.cs
6,453
C#
using Newtonsoft.Json; namespace Kasp.Identity.Entities.UserEntities.XEntities { public class TokenRequest { public string Username { get; set; } public string Password { get; set; } [JsonProperty("grant_type")] public GrandType GrandType { get; set; } [JsonProperty("refresh_token")] public string RefreshToken { get; set; } } public enum GrandType { Password = 0, RefreshToken = 1 } }
21.578947
57
0.712195
[ "MIT" ]
fossabot/Kasp
src/Kasp.Identity/Entities/UserEntities/XEntities/TokenRequest.cs
410
C#
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- /// Game $Game::CompanyName = "GarageGames LLC"; $Game::ProductName = "Torque 2D"; /// iOS $pref::iOS::ScreenOrientation = $iOS::constant::Landscape; $pref::iOS::ScreenDepth = 32; $pref::iOS::UseGameKit = 0; $pref::iOS::UseMusic = 0; $pref::iOS::UseMoviePlayer = 0; $pref::iOS::UseAutoRotate = 1; $pref::iOS::EnableOrientationRotation = 1; $pref::iOS::EnableOtherOrientationRotation = 1; $pref::iOS::StatusBarType = 0; /// Audio $pref::Audio::driver = "OpenAL"; $pref::Audio::forceMaxDistanceUpdate = 0; $pref::Audio::environmentEnabled = 0; $pref::Audio::masterVolume = 1.0; $pref::Audio::channelVolume1 = 1.0; $pref::Audio::channelVolume2 = 1.0; $pref::Audio::channelVolume3 = 1.0; $pref::Audio::sfxVolume = 1.0; $pref::Audio::musicVolume = 1.0; /// T2D $pref::T2D::ParticlePlayerEmissionRateScale = 1.0; $pref::T2D::ParticlePlayerSizeScale = 1.0; $pref::T2D::ParticlePlayerForceScale = 1.0; $pref::T2D::ParticlePlayerTimeScale = 1.0; $pref::T2D::warnFileDeprecated = 1; $pref::T2D::warnSceneOccupancy = 1; $pref::T2D::imageAssetGlobalFilterMode = Bilinear; $pref::T2D::TAMLSchema=""; $pref::T2D::JSONStrict = 1; /// Video $pref::Video::appliedPref = 0; $pref::Video::disableVerticalSync = 1; $pref::Video::displayDevice = "OpenGL"; $pref::Video::preferOpenGL = 1; $pref::Video::fullScreen = 0; $pref::Video::defaultResolution = "1024 768"; $pref::Video::windowedRes = "1024 768 32"; $pref::OpenGL::gammaCorrection = 0.5; /// Fonts. $Gui::fontCacheDirectory = expandPath( "^AppCore/fonts" ); // Gui $pref::Gui::noClampTorqueCursorToWindow = 1; $pref::Gui::hideCursorWhenTouchEventDetected = 1;
38.802632
79
0.671414
[ "MIT" ]
JLA02/Torque2D
toybox/AppCore/1/scripts/defaultPreferences.cs
2,949
C#
using System; using System.Diagnostics.CodeAnalysis; using ILLink.Shared; using Mono.Cecil; namespace Mono.Linker { /// Tracks dependencies created via DynamicDependencyAttribute in the linker. /// This is almost identical to DynamicDependencyAttribute, but it holds a /// TypeReference instead of a Type, and it has a reference to the original /// CustomAttribute for dependency tracing. It is also a place for helper /// methods related to the attribute. [System.AttributeUsage (System.AttributeTargets.Constructor | System.AttributeTargets.Field | System.AttributeTargets.Method, AllowMultiple = true, Inherited = false)] internal class DynamicDependency : Attribute { public CustomAttribute? OriginalAttribute { get; private set; } public DynamicDependency (string memberSignature) { MemberSignature = memberSignature; } public DynamicDependency (string memberSignature, TypeReference type) { MemberSignature = memberSignature; Type = type; } public DynamicDependency (string memberSignature, string typeName, string assemblyName) { MemberSignature = memberSignature; TypeName = typeName; AssemblyName = assemblyName; } public DynamicDependency (DynamicallyAccessedMemberTypes memberTypes, TypeReference type) { MemberTypes = memberTypes; Type = type; } public DynamicDependency (DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName) { MemberTypes = memberTypes; TypeName = typeName; AssemblyName = assemblyName; } public string? MemberSignature { get; } public DynamicallyAccessedMemberTypes MemberTypes { get; } public TypeReference? Type { get; } public string? TypeName { get; } public string? AssemblyName { get; } public string? Condition { get; set; } public static DynamicDependency? ProcessAttribute (LinkContext context, ICustomAttributeProvider provider, CustomAttribute customAttribute) { if (!(provider is IMemberDefinition member)) return null; if (!(member is MethodDefinition || member is FieldDefinition)) return null; // Don't honor the Condition until we have figured out the behavior for DynamicDependencyAttribute: // https://github.com/dotnet/linker/issues/1231 // if (!ShouldProcess (context, customAttribute)) // return null; var dynamicDependency = GetDynamicDependency (customAttribute); if (dynamicDependency != null) return dynamicDependency; context.LogWarning (member, DiagnosticId.DynamicDependencyAttributeCouldNotBeAnalyzed); return null; } static DynamicDependency? GetDynamicDependency (CustomAttribute ca) { var args = ca.ConstructorArguments; if (args.Count < 1 || args.Count > 3) return null; DynamicDependency? result = args[0].Value switch { string stringMemberSignature => args.Count switch { 1 => new DynamicDependency (stringMemberSignature), 2 when args[1].Value is TypeReference type => new DynamicDependency (stringMemberSignature, type), 3 when args[1].Value is string typeName && args[2].Value is string assemblyName => new DynamicDependency (stringMemberSignature, typeName, assemblyName), _ => null, }, int memberTypes => args.Count switch { 2 when args[1].Value is TypeReference type => new DynamicDependency ((DynamicallyAccessedMemberTypes) memberTypes, type), 3 when args[1].Value is string typeName && args[2].Value is string assemblyName => new DynamicDependency ((DynamicallyAccessedMemberTypes) memberTypes, typeName, assemblyName), _ => null, }, _ => null, }; if (result != null) result.OriginalAttribute = ca; return result; } public static bool ShouldProcess (LinkContext context, CustomAttribute ca) { if (ca.HasProperties && ca.Properties[0].Name == "Condition") { var condition = ca.Properties[0].Argument.Value as string; switch (condition) { case "": case null: return true; case "DEBUG": if (!context.KeepMembersForDebugger) return false; break; default: // Don't have yet a way to match the general condition so everything is excluded return false; } } return true; } } }
32.472868
181
0.731439
[ "MIT" ]
Mu-L/linker
src/linker/Linker/DynamicDependency.cs
4,189
C#
// <copyright file="SeleniumOperaDriver.cs"> // Copyright © 2018 Rami Abughazaleh. All rights reserved. // </copyright> namespace SpecBind.Selenium.Drivers { using System; using Configuration; using OpenQA.Selenium; using OpenQA.Selenium.Opera; using TechTalk.SpecFlow; /// <summary> /// Selenium Opera Driver. /// </summary> /// <seealso cref="SpecBind.Selenium.Drivers.SeleniumDriverBase" /> internal class SeleniumOperaDriver : SeleniumDriverBase { /// <summary> /// Creates the web driver from the specified browser factory configuration. /// </summary> /// <param name="browserFactoryConfiguration">The browser factory configuration.</param> /// <param name="scenarioContext">The scenario context.</param> /// <returns> /// The configured web driver. /// </returns> protected override IWebDriverEx CreateLocalDriver( BrowserFactoryConfiguration browserFactoryConfiguration, ScenarioContext scenarioContext) { throw new NotImplementedException(); } /// <summary> /// Downloads the driver to the specified path. /// </summary> /// <param name="driverPath">The driver path.</param> protected override void Download(string driverPath) { throw new NotImplementedException(); } /// <summary> /// Creates the driver options. /// </summary> /// <param name="browserFactoryConfiguration">The browser factory configuration.</param> /// <returns>The driver options.</returns> protected override DriverOptions CreateRemoteDriverOptions(BrowserFactoryConfiguration browserFactoryConfiguration) { return new OperaOptions(); } } }
34.811321
123
0.634146
[ "MIT" ]
icnocop/specbind
src/SpecBind.Selenium/Drivers/SeleniumOperaDriver.cs
1,848
C#
#region File Description //----------------------------------------------------------------------------- // GameScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input.Touch; using System.IO; #endregion namespace GameStateManagement { /// <summary> /// Enum describes the screen transition state. /// </summary> public enum ScreenState { TransitionOn, Active, TransitionOff, Hidden, } /// <summary> /// A screen is a single layer that has update and draw logic, and which /// can be combined with other layers to build up a complex menu system. /// For instance the main menu, the options menu, the "are you sure you /// want to quit" message box, and the main game itself are all implemented /// as screens. /// </summary> public abstract class GameScreen { #region Properties /// <summary> /// Normally when one screen is brought up over the top of another, /// the first screen will transition off to make room for the new /// one. This property indicates whether the screen is only a small /// popup, in which case screens underneath it do not need to bother /// transitioning off. /// </summary> public bool IsPopup { get { return isPopup; } protected set { isPopup = value; } } bool isPopup = false; /// <summary> /// Indicates how long the screen takes to /// transition on when it is activated. /// </summary> public TimeSpan TransitionOnTime { get { return transitionOnTime; } protected set { transitionOnTime = value; } } TimeSpan transitionOnTime = TimeSpan.Zero; /// <summary> /// Indicates how long the screen takes to /// transition off when it is deactivated. /// </summary> public TimeSpan TransitionOffTime { get { return transitionOffTime; } protected set { transitionOffTime = value; } } TimeSpan transitionOffTime = TimeSpan.Zero; /// <summary> /// Gets the current position of the screen transition, ranging /// from zero (fully active, no transition) to one (transitioned /// fully off to nothing). /// </summary> public float TransitionPosition { get { return transitionPosition; } protected set { transitionPosition = value; } } float transitionPosition = 1; /// <summary> /// Gets the current alpha of the screen transition, ranging /// from 1 (fully active, no transition) to 0 (transitioned /// fully off to nothing). /// </summary> public float TransitionAlpha { get { return 1f - TransitionPosition; } } /// <summary> /// Gets the current screen transition state. /// </summary> public ScreenState ScreenState { get { return screenState; } protected set { screenState = value; } } ScreenState screenState = ScreenState.TransitionOn; /// <summary> /// There are two possible reasons why a screen might be transitioning /// off. It could be temporarily going away to make room for another /// screen that is on top of it, or it could be going away for good. /// This property indicates whether the screen is exiting for real: /// if set, the screen will automatically remove itself as soon as the /// transition finishes. /// </summary> public bool IsExiting { get { return isExiting; } protected internal set { isExiting = value; } } bool isExiting = false; /// <summary> /// Checks whether this screen is active and can respond to user input. /// </summary> public bool IsActive { get { return !otherScreenHasFocus && (screenState == ScreenState.TransitionOn || screenState == ScreenState.Active); } } bool otherScreenHasFocus; /// <summary> /// Gets the manager that this screen belongs to. /// </summary> public ScreenManager ScreenManager { get { return screenManager; } internal set { screenManager = value; } } ScreenManager screenManager; /// <summary> /// Gets the index of the player who is currently controlling this screen, /// or null if it is accepting input from any player. This is used to lock /// the game to a specific player profile. The main menu responds to input /// from any connected gamepad, but whichever player makes a selection from /// this menu is given control over all subsequent screens, so other gamepads /// are inactive until the controlling player returns to the main menu. /// </summary> public PlayerIndex? ControllingPlayer { get { return controllingPlayer; } internal set { controllingPlayer = value; } } PlayerIndex? controllingPlayer; /// <summary> /// Gets the gestures the screen is interested in. Screens should be as specific /// as possible with gestures to increase the accuracy of the gesture engine. /// For example, most menus only need Tap or perhaps Tap and VerticalDrag to operate. /// These gestures are handled by the ScreenManager when screens change and /// all gestures are placed in the InputState passed to the HandleInput method. /// </summary> public GestureType EnabledGestures { get { return enabledGestures; } protected set { enabledGestures = value; // the screen manager handles this during screen changes, but // if this screen is active and the gesture types are changing, // we have to update the TouchPanel ourself. if (ScreenState == ScreenState.Active) { TouchPanel.EnabledGestures = value; } } } GestureType enabledGestures = GestureType.None; /// <summary> /// Gets whether or not this screen is serializable. If this is true, /// the screen will be recorded into the screen manager's state and /// its Serialize and Deserialize methods will be called as appropriate. /// If this is false, the screen will be ignored during serialization. /// By default, all screens are assumed to be serializable. /// </summary> public bool IsSerializable { get { return isSerializable; } protected set { isSerializable = value; } } bool isSerializable = true; #endregion #region Initialization /// <summary> /// Load graphics content for the screen. /// </summary> public virtual void LoadContent() { } /// <summary> /// Unload content for the screen. /// </summary> public virtual void UnloadContent() { } #endregion #region Update and Draw /// <summary> /// Allows the screen to run logic, such as updating the transition position. /// Unlike HandleInput, this method is called regardless of whether the screen /// is active, hidden, or in the middle of a transition. /// </summary> public virtual void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { this.otherScreenHasFocus = otherScreenHasFocus; if (isExiting) { // If the screen is going away to die, it should transition off. screenState = ScreenState.TransitionOff; if (!UpdateTransition(gameTime, transitionOffTime, 1)) { // When the transition finishes, remove the screen. ScreenManager.RemoveScreen(this); } } else if (coveredByOtherScreen) { // If the screen is covered by another, it should transition off. if (UpdateTransition(gameTime, transitionOffTime, 1)) { // Still busy transitioning. screenState = ScreenState.TransitionOff; } else { // Transition finished! screenState = ScreenState.Hidden; } } else { // Otherwise the screen should transition on and become active. if (UpdateTransition(gameTime, transitionOnTime, -1)) { // Still busy transitioning. screenState = ScreenState.TransitionOn; } else { // Transition finished! screenState = ScreenState.Active; } } } /// <summary> /// Helper for updating the screen transition position. /// </summary> bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction) { // How much should we move by? float transitionDelta; if (time == TimeSpan.Zero) transitionDelta = 1; else transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds / time.TotalMilliseconds); // Update the transition position. transitionPosition += transitionDelta * direction; // Did we reach the end of the transition? if (((direction < 0) && (transitionPosition <= 0)) || ((direction > 0) && (transitionPosition >= 1))) { transitionPosition = MathHelper.Clamp(transitionPosition, 0, 1); return false; } // Otherwise we are still busy transitioning. return true; } /// <summary> /// Allows the screen to handle user input. Unlike Update, this method /// is only called when the screen is active, and not when some other /// screen has taken the focus. /// </summary> public virtual void HandleInput(InputState input) { } /// <summary> /// This is called when the screen should draw itself. /// </summary> public virtual void Draw(GameTime gameTime) { } #endregion #region Public Methods /// <summary> /// Tells the screen to serialize its state into the given stream. /// </summary> public virtual void Serialize(Stream stream) { } /// <summary> /// Tells the screen to deserialize its state from the given stream. /// </summary> public virtual void Deserialize(Stream stream) { } /// <summary> /// Tells the screen to go away. Unlike ScreenManager.RemoveScreen, which /// instantly kills the screen, this method respects the transition timings /// and will give the screen a chance to gradually transition off. /// </summary> public void ExitScreen() { if (TransitionOffTime == TimeSpan.Zero) { // If the screen has a zero transition time, remove it immediately. ScreenManager.RemoveScreen(this); } else { // Otherwise flag that it should transition off and then exit. isExiting = true; } } #endregion } }
32.503937
93
0.549903
[ "MIT" ]
SimonDarksideJ/XNAGameStudio
Samples/GSMSample_4_0_PHONE/GameStateManagementSample/ScreenManager/GameScreen.cs
12,384
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using AutoMapper; using ClosedXML.Excel; using Lottery.Data; using Lottery.Helpers; using Lottery.Models.Attendee; using Lottery.Repositories.Interfaces; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace Lottery.Controllers { [ApiController] [Authorize] [Route("api/items/{itemId}/winners")] public class WinnersForItemIdController : ControllerBase { private readonly IMapper _mapper; private readonly IWinnerRepository _winnerRepository; private readonly IItemRepository _itemRepository; private readonly IAttendeeRepository _attendeeRepository; public WinnersForItemIdController( IMapper mapper, IWinnerRepository winnerRepository, IItemRepository itemRepository, IAttendeeRepository attendeeRepository) { _mapper = mapper; _winnerRepository = winnerRepository; _itemRepository = itemRepository; _attendeeRepository = attendeeRepository; } [HttpGet("length", Name = nameof(GetAllWinnersLengthForItemId))] public async Task<ActionResult<int>> GetAllWinnersLengthForItemId(string itemId) { if (!await _itemRepository.ExistItemByIdAsync(itemId)) { return NotFound(); } var model = await _winnerRepository.GetAllWinnersLengthForItemIdAsync(itemId); return Ok(model); } [HttpGet(Name = nameof(GetWinnersForItemId))] public async Task<ActionResult<IEnumerable<AttendeeViewModel>>> GetWinnersForItemId(string itemId, [FromQuery] WinnerResourceParameters parameters) { if (!await _itemRepository.ExistItemByIdAsync(itemId)) { return NotFound(); } var skipNumber = parameters.PageSize * (parameters.PageNumber - 1); var takeNumber = parameters.PageSize; var entities = await _winnerRepository.GetWinnersForItemIdAsync(itemId, skipNumber, takeNumber); var models = _mapper.Map<IEnumerable<AttendeeViewModel>>(entities); return Ok(models); } [HttpGet("file/xlsx", Name = nameof(GetWinnersXlsxForItemId))] public async Task<IActionResult> GetWinnersXlsxForItemId(string itemId) { var item = await _itemRepository.GetItemByIdAsync(itemId); if (item == null) { return NotFound(); } var entity = await _winnerRepository.GetAllWinnersForItemIdAsync(itemId); var models = _mapper.Map<List<AttendeeFileViewModel>>(entity); var fileName = $"{item.ItemName}.xlsx"; try { using (var workbook = new XLWorkbook()) { IXLWorksheet worksheet = workbook.Worksheets.Add($"{item.ItemName}列表"); worksheet.Cell(1, 1).Value = "學號"; worksheet.Cell(1, 2).Value = "姓名"; worksheet.Cell(1, 3).Value = "系所"; for (int i = 1; i <= models.Count; i++) { worksheet.Cell(i + 1, 1).Value = models[i - 1].NID; worksheet.Cell(i + 1, 2).Value = models[i - 1].Name; worksheet.Cell(i + 1, 3).Value = models[i - 1].Department; } using (var stream = new MemoryStream()) { workbook.SaveAs(stream); var content = stream.ToArray(); return File(content, ContentType.Xlsx, fileName); } } } catch (Exception e) { return BadRequest(); } } [HttpGet("file/csv", Name = nameof(GetWinnersCsvForItemId))] public async Task<IActionResult> GetWinnersCsvForItemId(string itemId) { var item = await _itemRepository.GetItemByIdAsync(itemId); if (item == null) { return NotFound(); } var entity = await _winnerRepository.GetAllWinnersForItemIdAsync(itemId); var models = _mapper.Map<List<AttendeeFileViewModel>>(entity); var fileName = $"{item.ItemName}.csv"; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("學號, 姓名, 系所"); foreach (var m in models) { stringBuilder.AppendLine($"{m.NID}, {m.Name}, {m.Department}"); } var content = Encoding.UTF8.GetBytes(stringBuilder.ToString()); return File(content, ContentType.Csv, fileName); } [HttpGet("file/json", Name = nameof(GetWinnersJsonForItemId))] public async Task<IActionResult> GetWinnersJsonForItemId(string itemId) { var item = await _itemRepository.GetItemByIdAsync(itemId); if (item == null) { return NotFound(); } var entity = await _winnerRepository.GetAllWinnersForItemIdAsync(itemId); // 移除 IsAwarded var models = _mapper.Map<List<AttendeeFileViewModel>>(entity) .Select(e => new {e.NID, e.Name, e.Department}) .ToList(); var fileName = $"{item.ItemName}.json"; var content = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(models)); return File(content, ContentType.Json, fileName); } } }
35.871951
155
0.572157
[ "MIT" ]
D0683497/Lottery
Controllers/WinnersForItemIdController.cs
5,917
C#
using System; namespace Task1_7_Numbers_to_Words { class Numbers_to_Words { static void Main() { int n = int.Parse(Console.ReadLine()); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = int.Parse(Console.ReadLine()); } foreach (int number in arr) { if (number < -999) { Console.WriteLine("too small"); } else if (number > 999) { Console.WriteLine("too large"); } else if (number > -100 && number < 100) { } else { Console.WriteLine(Letterize(number)); } } } static string Letterize(int number) { string minus = number < 0 ? "minus " : ""; string hundreds = string.Empty; int hund = Math.Abs(number / 100); switch (hund) { case 1: hundreds = "one-hundred"; break; case 2: hundreds = "two-hundred"; break; case 3: hundreds = "three-hundred"; break; case 4: hundreds = "four-hundred"; break; case 5: hundreds = "five-hundred"; break; case 6: hundreds = "six-hundred"; break; case 7: hundreds = "seven-hundred"; break; case 8: hundreds = "eight-hundred"; break; case 9: hundreds = "nine-hundred"; break; default: break; } if (number % 100 == 0) { return minus + hundreds; } number = Math.Abs(number % 100); int d1, d2; string word1 = string.Empty; string word2 = string.Empty; string name = string.Empty; d1 = number / 10; d2 = number % 10; if (d1 == 1) { switch (d2) { case 1: name = minus + hundreds + " and " + "eleven"; break; case 2: name = minus + hundreds + " and " + "twelve"; break; case 3: name = minus + hundreds + " and " + "thirteen"; break; case 4: name = minus + hundreds + " and " + "fourteen"; break; case 5: name = minus + hundreds + " and " + "fifteen"; break; case 6: name = minus + hundreds + " and " + "sixteen"; break; case 7: name = minus + hundreds + " and " + "seventeen"; break; case 8: name = minus + hundreds + " and " + "eighteen"; break; case 9: name = minus + hundreds + " and " + "nineteen"; break; default: name = minus + hundreds + " and " + "ten"; break; } } else if (d1 == 0) { switch (d2) { case 1: name = minus + hundreds + " and " + "one"; break; case 2: name = minus + hundreds + " and " + "two"; break; case 3: name = minus + hundreds + " and " + "three"; break; case 4: name = minus + hundreds + " and " + "four"; break; case 5: name = minus + hundreds + " and " + "five"; break; case 6: name = minus + hundreds + " and " + "six"; break; case 7: name = minus + hundreds + " and " + "seven"; break; case 8: name = minus + hundreds + " and " + "eight"; break; case 9: name = minus + hundreds + " and " + "nine"; break; default: break; } } else { switch (d1) { case 2: word1 = "twenty"; break; case 3: word1 = "thirty"; break; case 4: word1 = "forty"; break; case 5: word1 = "fifty"; break; case 6: word1 = "sixty"; break; case 7: word1 = "seventy"; break; case 8: word1 = "eighty"; break; case 9: word1 = "ninety"; break; default: word1 = ""; break; } switch (d2) { case 1: word2 = "one"; break; case 2: word2 = "two"; break; case 3: word2 = "three"; break; case 4: word2 = "four"; break; case 5: word2 = "five"; break; case 6: word2 = "six"; break; case 7: word2 = "seven"; break; case 8: word2 = "eight"; break; case 9: word2 = "nine"; break; default: word2 = ""; break; } if (word1 == "") { name = minus + hundreds + " and " + word2; } else if (word2 == "") { name = minus + hundreds + " and " + word1; } else { name = minus + hundreds + " and " + word1 + " " + word2; } } return name; } } }
35.590909
83
0.376391
[ "MIT" ]
naydenhristov/Numbers_to_Words
Numbers_to_Words.cs
5,483
C#
using System; using System.Web; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using Owin; using FrontEndASPNETTest.Models; namespace FrontEndASPNETTest.Account { public partial class RegisterExternalLogin : System.Web.UI.Page { protected string ProviderName { get { return (string)ViewState["ProviderName"] ?? String.Empty; } private set { ViewState["ProviderName"] = value; } } protected string ProviderAccountKey { get { return (string)ViewState["ProviderAccountKey"] ?? String.Empty; } private set { ViewState["ProviderAccountKey"] = value; } } private void RedirectOnFail() { Response.Redirect((User.Identity.IsAuthenticated) ? "~/Account/Manage" : "~/Account/Login"); } protected void Page_Load() { // Process the result from an auth provider in the request ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { RedirectOnFail(); return; } if (!IsPostBack) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { RedirectOnFail(); return; } var user = manager.Find(loginInfo.Login); if (user != null) { signInManager.SignIn(user, isPersistent: false, rememberBrowser: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Apply Xsrf check when linking var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { RedirectOnFail(); return; } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { email.Text = loginInfo.Email; } } } protected void LogIn_Click(object sender, EventArgs e) { CreateAndLoginUser(); } private void CreateAndLoginUser() { if (!IsValid) { return; } var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>(); var user = new ApplicationUser() { UserName = email.Text, Email = email.Text }; IdentityResult result = manager.Create(user); if (result.Succeeded) { var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { RedirectOnFail(); return; } result = manager.AddLogin(user.Id, loginInfo.Login); if (result.Succeeded) { signInManager.SignIn(user, isPersistent: false, rememberBrowser: false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // var code = manager.GenerateEmailConfirmationToken(user.Id); // Send this link via email: IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id) IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); return; } } AddErrors(result); } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } } }
37.869231
159
0.525696
[ "Apache-2.0" ]
atombryan/ThaiResortFull
ServiceStackHub/Thai Resort/FrontEndASPNETTest/Account/RegisterExternalLogin.aspx.cs
4,925
C#
using UnityEngine; using System.Collections.Generic; namespace Lean.Transition.Method { /// <summary>This component allows you to delay for a specified duration.</summary> [HelpURL(LeanTransition.HelpUrlPrefix + "LeanDelay")] [AddComponentMenu(LeanTransition.MethodsMenuPrefix + "Delay" + LeanTransition.MethodsMenuSuffix + "(LeanDelay)")] public class LeanDelay : LeanMethodWithState { public override void Register() { PreviousState = Register(Data.Duration); } public static LeanState Register(float duration) { var state = LeanTransition.Spawn(State.Pool); return LeanTransition.Register(state, duration); } [System.Serializable] public class State : LeanState { public override void Begin() { // No state to begin from } public override void Update(float progress) { // No state to update } public static Stack<State> Pool = new Stack<State>(); public override void Despawn() { Pool.Push(this); } } public State Data; } } namespace Lean.Transition { public static partial class LeanExtensions { /// <summary>This will pause the animation for the specified amount of seconds.</summary> public static T DelayTransition<T>(this T target, float duration) where T : Component { Method.LeanDelay.Register(duration); return target; } /// <summary>This will pause the animation for the specified amount of seconds.</summary> public static GameObject DelayTransition(this GameObject target, float duration) { Method.LeanDelay.Register(duration); return target; } } }
26.1
114
0.727969
[ "MIT" ]
AbhishekPardhi/GameDev-Project-1
Monkey KickOff/Assets/Lean/Transition/Methods/LeanDelay.cs
1,568
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("Examples.Filler")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Examples.Filler")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7865a4b8-b41e-434c-92e5-685b6ed0a54c")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.861111
84
0.748349
[ "MIT" ]
wurdum/examples.filler
Src/Examples.Filler/Properties/AssemblyInfo.cs
1,366
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 ICSharpCode.WixBinding; using NUnit.Framework; using System; namespace WixBinding.Tests.Document { /// <summary> /// Tests the WixFileElement GetFiles method and its FileName property. /// </summary> [TestFixture] public class ChildFilesTestFixture { WixDocument doc; WixFileElement[] files; [SetUp] public void SetUpFixture() { doc = new WixDocument(); doc.FileName = @"C:\Projects\Setup\Setup.wxs"; doc.LoadXml(GetWixXml()); WixDirectoryElement rootDirectory = doc.GetRootDirectory(); WixDirectoryElement[] rootChildDirectories = rootDirectory.GetDirectories(); WixDirectoryElement programFilesDirectory = rootChildDirectories[0]; WixDirectoryElement[] programFilesChildDirectories = programFilesDirectory.GetDirectories(); WixDirectoryElement myAppDirectory = programFilesChildDirectories[0]; WixComponentElement[] childComponents = myAppDirectory.GetComponents(); WixComponentElement coreComponent = childComponents[0]; files = coreComponent.GetFiles(); } [Test] public void TwoFiles() { Assert.AreEqual(2, files.Length); } /// <summary> /// The filename should not include the ".." part. /// </summary> [Test] public void FirstFileElementFileName() { Assert.AreEqual(@"C:\Projects\doc\license.rtf", files[0].GetSourceFullPath()); } [Test] public void SecondFileElementFileName() { Assert.AreEqual(@"C:\Projects\Setup\bin\myapp.exe", files[1].GetSourceFullPath()); } /// <summary> /// Tests that the WixFileElement.FileName property returns the /// relative filename if no filename is given to the WixDocument. /// </summary> [Test] public void RelativeFileNameUsed() { doc.FileName = String.Empty; Assert.AreEqual(@"..\doc\license.rtf", files[0].GetSourceFullPath()); Assert.AreEqual(@"bin\myapp.exe", files[1].GetSourceFullPath()); } [Test] public void SourceAttributeUsed() { Assert.AreEqual(@"..\doc\license.rtf", files[0].Source); Assert.AreEqual(@"bin\myapp.exe", files[1].Source); } [Test] public void NameAttributeUsed() { Assert.AreEqual(@"License.rtf", files[0].FileName); Assert.AreEqual(@"MyApp.exe", files[1].FileName); } string GetWixXml() { return "<Wix xmlns=\"http://schemas.microsoft.com/wix/2006/wi\">\r\n" + "\t<Product Name=\"MySetup\" \r\n" + "\t Manufacturer=\"\" \r\n" + "\t Id=\"F4A71A3A-C271-4BE8-B72C-F47CC956B3AA\" \r\n" + "\t Language=\"1033\" \r\n" + "\t Version=\"1.0.0.0\">\r\n" + "\t\t<Package Id=\"6B8BE64F-3768-49CA-8BC2-86A76424DFE9\"/>\r\n" + "\t\t<Directory Id=\"TARGETDIR\" SourceName=\"SourceDir\">\r\n" + "\t\t\t<Directory Id=\"ProgramFilesFolder\" Name=\"PFiles\">\r\n" + "\t\t\t\t<Directory Id=\"INSTALLDIR\" Name=\"MyApp\">\r\n" + "\t\t\t\t\t<Component Id=\"CoreComponents\">\r\n" + "\t\t\t\t\t\t<File Id=\"LicenseFile\" Name=\"License.rtf\" Source=\"..\\doc\\license.rtf\" />\r\n" + "\t\t\t\t\t\t<File Id=\"ExeFile\" Name=\"MyApp.exe\" Source=\"bin\\myapp.exe\" />\r\n" + "\t\t\t\t\t</Component>\r\n" + "\t\t\t\t</Directory>\r\n" + "\t\t\t</Directory>\r\n" + "\t\t</Directory>\r\n" + "\t</Product>\r\n" + "</Wix>"; } } }
36.31405
104
0.680246
[ "MIT" ]
TetradogOther/SharpDevelop
src/AddIns/BackendBindings/WixBinding/Test/Document/ChildFilesTestFixture.cs
4,396
C#
namespace WebApi.Modules { using Application.Boundaries.GetAccount; using Application.UseCases; using Domain.Accounts; using Microsoft.Extensions.DependencyInjection; using UseCases.V2.GetAccount; /// <summary> /// The User Interface V2 Extensions. /// </summary> public static class UserInterfaceV2Extensions { /// <summary> /// Inject All V2 Presenters dependencies; /// </summary> public static IServiceCollection AddPresentersV2(this IServiceCollection services) { services.AddScoped<GetAccountDetailsPresenterV2, GetAccountDetailsPresenterV2>(); services.AddScoped<IGetAccountUseCaseV2>( ctx => new GetAccountUseCase( ctx.GetRequiredService<GetAccountDetailsPresenterV2>(), ctx.GetRequiredService<IAccountRepository>())); return services; } } }
33.517241
94
0.627572
[ "Apache-2.0" ]
IYoni/imangatest
src/WebApi/Modules/UserInterfaceV2Extensions.cs
972
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.EventHub.Latest.Outputs { [OutputType] public sealed class SkuResponse { /// <summary> /// The Event Hubs throughput units, value should be 0 to 20 throughput units. /// </summary> public readonly int? Capacity; /// <summary> /// Name of this SKU. /// </summary> public readonly string Name; /// <summary> /// The billing tier of this particular SKU. /// </summary> public readonly string? Tier; [OutputConstructor] private SkuResponse( int? capacity, string name, string? tier) { Capacity = capacity; Name = name; Tier = tier; } } }
25.186047
86
0.581717
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/EventHub/Latest/Outputs/SkuResponse.cs
1,083
C#
using System.Collections.Generic; namespace UnityMdDocGenerator { public class MdNode { public string Name { get; private set; } public DocNode Content { get; private set; } public List<MdNode> Childs { get; private set; } public MdNodeType Type { get; set; } public MdNode(string name, DocNode content) { Name = name; Content = content; Childs = new List<MdNode>(); } } }
22.105263
51
0.652381
[ "MIT" ]
KonH/UnityMdDocGenerator
Editor/Sctructure/MdNode.cs
422
C#
using RevolutionaryStuff.Core; using System; using System.IO; namespace RevolutionaryStuff.TheLoader { public enum FileFormats { Auto, CSV, Pipe, CustomText, FixedWidthText, FoxPro, Excel, MySqlDump, SqlServerDump, Json, OData4, Html, ELF, //https://en.wikipedia.org/wiki/Extended_Log_Format } public static class FileFormatHelpers { public static FileFormats GetImpliedFormat(string filePath, Uri source) { var ext = Path.GetExtension(source?.AbsolutePath ?? filePath).ToLower(); switch (ext) { case ".htm": case ".html": return FileFormats.Html; case ".dbf": return FileFormats.FoxPro; case ".csv": return FileFormats.CSV; case ".pipe": return FileFormats.Pipe; case ".log": return FileFormats.ELF; case ".xls": case ".xlsx": return FileFormats.Excel; case ".mdmp": return FileFormats.MySqlDump; case ".json": return FileFormats.Json; default: throw new UnexpectedSwitchValueException(ext); } } } }
26.545455
84
0.473973
[ "MIT" ]
jbt00000/RevolutionaryStuff
src/RevolutionaryStuff.TheLoader/FileFormats.cs
1,462
C#
using SharpSweeper.Enum; using SharpSweeper.Struct; namespace SharpSweeper { internal class Flag { private Matrix flagMap; private int countOfClosedBoxes; internal int GetCountOfClosedBoxes() => countOfClosedBoxes; internal void Start() { flagMap = new Matrix(Box.CLOSED); countOfClosedBoxes = Ranges.Size.x * Ranges.Size.y; } internal Box this[Coord coord] => flagMap[coord]; internal void SetOpenedToBox(Coord coord) { flagMap[coord] = Box.OPENED; countOfClosedBoxes--; } #region [Flags] internal void ToggleFlaggedBox(Coord coord) { switch (flagMap[coord]) { case Box.FLAGED: SetClosedToBox(coord); break; case Box.CLOSED: SetFlaggedToBox(coord); break; } } private void SetFlaggedToBox(Coord coord) => flagMap[coord] = Box.FLAGED; private void SetClosedToBox(Coord coord) => flagMap[coord] = Box.CLOSED; #endregion internal void SetBombedToBox(Coord coord) => flagMap[coord] = Box.BOMBED; internal void SetOpenedToClosedBombBox(Coord coord) { if (flagMap[coord] == Box.CLOSED) flagMap[coord] = Box.OPENED; } internal void SetNobombToFlagedSafeBox(Coord coord) { if (flagMap[coord] == Box.FLAGED) flagMap[coord] = Box.NOBOMB; } internal int GetCountOfFlaggedBoxesAround(Coord coord) { int count = 0; foreach (var around in Ranges.GetCoordsAround(coord)) if (flagMap[around] == Box.FLAGED) count++; return count; } } }
28.4375
81
0.558791
[ "MIT" ]
bazuka5801/SharpSweeper
SharpSweeper/SharpSweeper/Flag.cs
1,822
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/wincrypt.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="CRYPT_ASYNC_RETRIEVAL_COMPLETION" /> struct.</summary> public static unsafe partial class CRYPT_ASYNC_RETRIEVAL_COMPLETIONTests { /// <summary>Validates that the <see cref="CRYPT_ASYNC_RETRIEVAL_COMPLETION" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<CRYPT_ASYNC_RETRIEVAL_COMPLETION>(), Is.EqualTo(sizeof(CRYPT_ASYNC_RETRIEVAL_COMPLETION))); } /// <summary>Validates that the <see cref="CRYPT_ASYNC_RETRIEVAL_COMPLETION" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(CRYPT_ASYNC_RETRIEVAL_COMPLETION).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="CRYPT_ASYNC_RETRIEVAL_COMPLETION" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(CRYPT_ASYNC_RETRIEVAL_COMPLETION), Is.EqualTo(16)); } else { Assert.That(sizeof(CRYPT_ASYNC_RETRIEVAL_COMPLETION), Is.EqualTo(8)); } } }
38.232558
145
0.718978
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/Windows/um/wincrypt/CRYPT_ASYNC_RETRIEVAL_COMPLETIONTests.cs
1,646
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace JS_Ecommerce.Models { public class CompletedOrder { public string TransactionId { get; set; } public SubmittedOrder SubmittedOrder { get; set; } public string Status { get; set; } public string Message { get; set; } } }
23.3125
58
0.675603
[ "MIT" ]
ecaoile/JS-ecommerce
JS_Ecommerce/JS_Ecommerce/Models/CompletedOrder.cs
375
C#
using System; using MongoDB.Bson.Serialization.Attributes; namespace ETModel { // 分享日志 public class Log_Share : EntityDB { public long Uid { set; get; } } }
16.272727
44
0.653631
[ "MIT" ]
zhangfengqwer/NjmjNew
Server/Model/Njmj/Entity/Db/Log_Share.cs
189
C#
using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition; using System.Linq; namespace GitHub.VisualStudio.Menus { [Export(typeof(IMenuProvider))] [PartCreationPolicy(CreationPolicy.Shared)] public class MenuProvider : IMenuProvider { public IReadOnlyCollection<IMenuHandler> Menus { get; private set; } public IReadOnlyCollection<IDynamicMenuHandler> DynamicMenus { get; private set; } [ImportingConstructor] public MenuProvider([ImportMany] IEnumerable<IMenuHandler> menus, [ImportMany] IEnumerable<IDynamicMenuHandler> dynamicMenus) { Menus = new ReadOnlyCollection<IMenuHandler>(menus.ToList()); DynamicMenus = new ReadOnlyCollection<IDynamicMenuHandler>(dynamicMenus.ToList()); } } }
35
133
0.732143
[ "MIT" ]
uQr/VisualStudio
src/GitHub.VisualStudio/Menus/MenuProvider.cs
842
C#
using UnityEngine; [CreateAssetMenu(menuName = "ScriptableEvents/Conditions/String")] public class StringCondition : Condition<string> { protected override void CheckType() { if (!(VarToCompare is StringVar)) { Debug.Log("You must assign a StringVar."); VarToCompare = null; } } }
20.235294
66
0.622093
[ "MIT" ]
celojevic/ScriptableEventSystem
Assets/Scripts/ScriptableEvents/Conditions/StringCondition.cs
344
C#
// AccountPopupContentAnchors using ClubPenguin; using UnityEngine; [ExecuteInEditMode] public class AccountPopupContentAnchors : MonoBehaviour { public enum VerticalAlignment { Top, Middle, Bottom } public enum HorizontalAlignment { Left, Center, Right } public VerticalAlignment VerticalAlign = VerticalAlignment.Middle; private VerticalAlignment lastVAlign; public HorizontalAlignment HorizontalAlign = HorizontalAlignment.Center; private HorizontalAlignment lastHAlign; private RectTransform rectTransform; private Vector2 startAnchorMin; private Vector2 startAnchorMax; private void Start() { rectTransform = GetComponent<RectTransform>(); startAnchorMin = rectTransform.anchorMin; startAnchorMax = rectTransform.anchorMax; lastVAlign = VerticalAlign; lastHAlign = HorizontalAlign; } private void OnGUI() { if (VerticalAlign != lastVAlign) { switch (VerticalAlign) { case VerticalAlignment.Top: rectTransform.anchorMin = new Vector2(rectTransform.anchorMin.x, 1f); rectTransform.anchorMax = new Vector2(rectTransform.anchorMax.x, 1f); break; case VerticalAlignment.Middle: rectTransform.anchorMin = new Vector2(rectTransform.anchorMin.x, 0.5f); rectTransform.anchorMax = new Vector2(rectTransform.anchorMax.x, 0.5f); break; case VerticalAlignment.Bottom: rectTransform.anchorMin = new Vector2(rectTransform.anchorMin.x, 0f); rectTransform.anchorMax = new Vector2(rectTransform.anchorMax.x, 0f); break; } lastVAlign = VerticalAlign; } if (HorizontalAlign != lastHAlign) { switch (HorizontalAlign) { case HorizontalAlignment.Left: rectTransform.anchorMin = new Vector2(0f, rectTransform.anchorMin.y); rectTransform.anchorMax = new Vector2(0f, rectTransform.anchorMax.y); break; case HorizontalAlignment.Center: rectTransform.anchorMin = new Vector2(0.5f, rectTransform.anchorMin.y); rectTransform.anchorMax = new Vector2(0.5f, rectTransform.anchorMax.y); break; case HorizontalAlignment.Right: rectTransform.anchorMin = new Vector2(1f, rectTransform.anchorMin.y); rectTransform.anchorMax = new Vector2(1f, rectTransform.anchorMax.y); break; } lastHAlign = HorizontalAlign; } } public void Reset() { rectTransform.anchorMin = startAnchorMin; rectTransform.anchorMax = startAnchorMax; } }
25.548387
75
0.753788
[ "MIT" ]
smdx24/CPI-Source-Code
ClubPenguin/AccountPopupContentAnchors.cs
2,376
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyFormData.Models { using System.Linq; public partial class Error { /// <summary> /// Initializes a new instance of the Error class. /// </summary> public Error() { } /// <summary> /// Initializes a new instance of the Error class. /// </summary> public Error(int? status = default(int?), string message = default(string)) { Status = status; Message = message; } /// <summary> /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "status")] public int? Status { get; set; } /// <summary> /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "message")] public string Message { get; set; } } }
27.926829
83
0.59738
[ "MIT" ]
fhoering/autorest
src/generator/AutoRest.CSharp.Tests/Expected/AcceptanceTests/BodyFormData/Models/Error.cs
1,145
C#
using LoESoft.Dungeon.utils; using RotMG.Common.Rasterizer; namespace LoESoft.Dungeon.templates.Difficult_1.Pirate_Cave { internal class Corridor : MapCorridor { public override void Rasterize(Room src, Room dst, Point srcPos, Point dstPos) { Default(srcPos, dstPos, new DungeonTile { TileType = PirateCaveTemplate.BrownLines }); } } }
26.5625
86
0.630588
[ "MIT" ]
Devwarlt/LOE-V6-SERVER
dungeon/Templates/Difficult 1/Pirate Cave/Corridor.cs
427
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/MsHTML.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="SVGStopElement" /> struct.</summary> public static unsafe partial class SVGStopElementTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="SVGStopElement" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(SVGStopElement).GUID, Is.EqualTo(IID_SVGStopElement)); } /// <summary>Validates that the <see cref="SVGStopElement" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<SVGStopElement>(), Is.EqualTo(sizeof(SVGStopElement))); } /// <summary>Validates that the <see cref="SVGStopElement" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(SVGStopElement).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="SVGStopElement" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(SVGStopElement), Is.EqualTo(1)); } }
36.5
145
0.707347
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/Windows/um/MsHTML/SVGStopElementTests.cs
1,608
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 gamelift-2015-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.GameLift.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.GameLift.Model.Internal.MarshallTransformations { /// <summary> /// StopFleetActions Request Marshaller /// </summary> public class StopFleetActionsRequestMarshaller : IMarshaller<IRequest, StopFleetActionsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((StopFleetActionsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(StopFleetActionsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.GameLift"); string target = "GameLift.StopFleetActions"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-10-01"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetActions()) { context.Writer.WritePropertyName("Actions"); context.Writer.WriteArrayStart(); foreach(var publicRequestActionsListValue in publicRequest.Actions) { context.Writer.Write(publicRequestActionsListValue); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetFleetId()) { context.Writer.WritePropertyName("FleetId"); context.Writer.Write(publicRequest.FleetId); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static StopFleetActionsRequestMarshaller _instance = new StopFleetActionsRequestMarshaller(); internal static StopFleetActionsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static StopFleetActionsRequestMarshaller Instance { get { return _instance; } } } }
35.844828
147
0.612554
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/GameLift/Generated/Model/Internal/MarshallTransformations/StopFleetActionsRequestMarshaller.cs
4,158
C#
using Nethereum.Hex.HexTypes; using Nethereum.Util; using Newtonsoft.Json.Linq; using System.Runtime.Serialization; namespace Nethereum.RPC.Eth.DTOs { [DataContract] public class TransactionReceipt { /// <summary> /// DATA, 32 Bytes - hash of the transaction. /// </summary> [DataMember(Name = "transactionHash")] public string TransactionHash { get; set; } /// <summary> /// QUANTITY - integer of the transactions index position in the block. /// </summary> [DataMember(Name = "transactionIndex")] public HexBigInteger TransactionIndex { get; set; } /// <summary> /// DATA, 32 Bytes - hash of the block where this transaction was in. /// </summary> [DataMember(Name = "blockHash")] public string BlockHash { get; set; } /// <summary> /// QUANTITY - block number where this transaction was in. /// </summary> [DataMember(Name = "blockNumber")] public HexBigInteger BlockNumber { get; set; } /// <summary> /// QUANTITY - The total amount of gas used when this transaction was executed in the block. /// </summary> [DataMember(Name = "cumulativeGasUsed")] public HexBigInteger CumulativeGasUsed { get; set; } /// <summary> /// QUANTITY - The amount of gas used by this specific transaction alone. /// </summary> [DataMember(Name = "gasUsed")] public HexBigInteger GasUsed { get; set; } /// <summary> /// The actual value per gas deducted from the senders account. Before EIP-1559, this is equal to the transaction's gas price. After, it is equal to baseFeePerGas + min(maxFeePerGas - baseFeePerGas, maxPriorityFeePerGas). Legacy transactions and EIP-2930 transactions are coerced into the EIP-1559 format by setting both maxFeePerGas and maxPriorityFeePerGas as the transaction's gas price. /// </summary> [DataMember(Name = "effectiveGasPrice")] public HexBigInteger EffectiveGasPrice { get; set; } /// <summary> /// DATA, 20 Bytes - The contract address created, if the transaction was a contract creation, otherwise null. /// </summary> [DataMember(Name = "contractAddress")] public string ContractAddress { get; set; } /// <summary> /// QUANTITY / BOOLEAN Transaction Success 1, Transaction Failed 0 /// </summary> [DataMember(Name = "status")] public HexBigInteger Status { get; set; } /// <summary> /// logs: Array - Array of log objects, which this transaction generated. /// </summary> [DataMember(Name = "logs")] public JArray Logs { get; set; } /// <summary> /// QUANTITY - The transaction type. /// </summary> [DataMember(Name = "type")] public HexBigInteger Type { get; set; } /// <summary> /// DATA, 256 Bytes - Bloom filter for light clients to quickly retrieve related logs /// </summary> [DataMember(Name = "logsBloom")] public string LogsBloom { get; set; } public bool? HasErrors() { if (Status?.HexValue == null) return null; return Status.Value == 0; } public override bool Equals(object obj) { if (obj is TransactionReceipt val) { return TransactionHash == val.TransactionHash && TransactionIndex == val.TransactionIndex && BlockHash == val.BlockHash && BlockNumber == val.BlockNumber && CumulativeGasUsed == val.CumulativeGasUsed && GasUsed == val.GasUsed && ContractAddress.IsTheSameAddress(val.ContractAddress) && Status == val.Status && Type == val.Type && LogsBloom == val.LogsBloom; } return false; } } }
38.761468
399
0.55503
[ "MIT" ]
rahul0tripathi/MetaNox
Assets/MoralisWeb3ApiSdk/Nethereum/Nethereum.RPC/Eth/DTOs/TransactionReceipt.cs
4,225
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.Its.Recipes; using NUnit.Framework; using Sample.Domain.Ordering; namespace Microsoft.Its.Domain.Sql.Tests { [TestFixture] public class StorableEventTests : EventStoreDbTest { [Test] public void UtcTime_getter_accurately_converts_values_set_via_TimeStamp_setter() { var now = DateTime.UtcNow; var e = new StorableEvent { Timestamp = now }; e.UtcTime.Should().Be(now); } [Test] public void UtcTime_setter_accurately_converts_values_forwarded_to_TimeStamp_setter() { var now = DateTime.UtcNow; var e = new StorableEvent { UtcTime = now }; e.Timestamp.Should().Be(now); } [Test] public void Event_Actor_is_populated_from_Event_Metadata() { var actor = Any.Email(); var sourceEvent = new Order.ItemAdded { Metadata = { Actor = actor } }; var storableEvent = sourceEvent.ToStorableEvent(); storableEvent.Actor.Should().Be(actor); } [Test] public void When_Metadata_Actor_is_not_set_then_Event_Actor_will_be_null() { var sourceEvent = new Order.ItemAdded(); var storableEvent = sourceEvent.ToStorableEvent(); storableEvent.Actor.Should().BeNull(); } [Test] public void Properties_on_the_base_Event_type_are_not_serialized() { var serialized = new TestEvent { AggregateId = Guid.NewGuid(), SequenceNumber = 1, Timestamp = DateTimeOffset.Now, Id = 7, Data = "abc" }.ToStorableEvent().Body; serialized.Should().Be("{\"Id\":7,\"Data\":\"abc\"}"); } [Test] public void Timestamp_round_trips_correctly_between_Event_and_StorableEvent() { var e1 = new TestEvent { Timestamp = DateTimeOffset.Now, }; var e2 = e1.ToStorableEvent().ToDomainEvent(); e2.Timestamp.Should().Be(e1.Timestamp); } [Test] public void Timestamp_round_trips_correctly_to_database() { var id = Guid.NewGuid(); var now = Clock.Now(); using (var db = new EventStoreDbContext()) { db.Events.Add(new TestEvent { AggregateId = id, Timestamp = now }.ToStorableEvent()); db.SaveChanges(); } using (var db = new EventStoreDbContext()) { var @event = db.Events.Single(e => e.AggregateId == id).ToDomainEvent(); // the database is not saving the offset, but the two dates should be equivalent UTC times @event.Timestamp .UtcDateTime .Should() .BeCloseTo(now.UtcDateTime, // there's a slight loss of precision saving to the db, but we should be within 3ms precision: 3 ); } } public class TestEvent : Event<TestAggregate> { public int Id; public string Data; public override void Update(TestAggregate aggregate) { } } public class TestAggregate : EventSourcedAggregate<TestAggregate> { /// <summary> /// Initializes a new instance of the <see cref="EventSourcedAggregate{T}"/> class. /// </summary> /// <param name="id">The aggregate's unique id.</param> /// <param name="eventHistory">The event history.</param> public TestAggregate(Guid id, IEnumerable<IEvent> eventHistory) : base(id, eventHistory) { } /// <summary> /// Initializes a new instance of the <see cref="EventSourcedAggregate{T}"/> class. /// </summary> /// <param name="id">The aggregate's unique id.</param> public TestAggregate(Guid? id = null) : base(id) { } } } }
29.360248
116
0.517453
[ "MIT" ]
gitter-badger/Its.Cqrs
Domain.Sql.Tests/StorableEventTests.cs
4,727
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Silk.NET.Core.Attributes; #pragma warning disable 1591 namespace Silk.NET.OpenGLES { [NativeName("Name", "FogCoordinatePointerType")] public enum FogCoordinatePointerType : int { [NativeName("Name", "GL_FLOAT")] Float = 0x1406, [NativeName("Name", "GL_DOUBLE")] Double = 0x140A, } }
23.428571
71
0.676829
[ "MIT" ]
Ar37-rs/Silk.NET
src/OpenGL/Silk.NET.OpenGLES/Enums/FogCoordinatePointerType.gen.cs
492
C#
using System.Linq; using System.Windows.Media; namespace TsNode.Preset.Models { /// <summary> /// ノード操作用のAPI /// </summary> public class NodeService { private readonly PresetNode _model; private readonly Network _network; public NodeService(PresetNode node , Network network) { _model = node; _network = network; } /// <summary> /// 座標を指定します。 /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public NodeService SetPos(double x, double y) { _model.X = x; _model.Y = y; return this; } /// <summary> /// ヘッダー色を変更します。 /// </summary> /// <param name="header"></param> /// <returns></returns> public NodeService SetColor(Color header) { _model.HeaderColor = header; return this; } /// <summary> /// ヘッダー色、背景色、前景色をまとめて変更します。 /// </summary> /// <param name="header"></param> /// <param name="backGround"></param> /// <param name="headerText"></param> /// <returns></returns> public NodeService SetColors(Color header, Color backGround, Color headerText) { _model.HeaderColor = header; _model.BackGroundColor = backGround; _model.HeaderTextColor = headerText; return this; } /// <summary> /// 任意の入力プラグTを追加します。 /// </summary> /// <param name="plugName"></param> /// <param name="defaultValue"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public NodeService AddInputPlug<T>(string plugName , T defaultValue) { var plug = new PresetPlug(new Property<T>() { Name = plugName, Value = defaultValue, }); _model.InputPlugs.Add(plug); return this; } /// <summary> /// 任意の出力プラグTを追加します。 /// </summary> /// <param name="plugName"></param> /// <param name="defaultValue"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public NodeService AddOutputPlug<T>(string plugName , T defaultValue) { var plug = new PresetPlug(new Property<T>() { Name = plugName, Value = defaultValue, }); _model.OutputPlugs.Add(plug); return this; } /// <summary> /// ノードを削除します。関連するコネクション等も削除されます。 /// </summary> public void Remove() { var plugs = _model.InputPlugs.Concat(_model.OutputPlugs).ToArray(); foreach (var connection in _network.Connections.ToArray()) { if (plugs.Any(x => connection.SourcePlug == x || connection.DestPlug == x)) { _network.Connections.Remove(connection); } } _network.Nodes.Remove(_model); } public string Handle => _model.Name; } }
29.123894
91
0.488605
[ "MIT" ]
p4j4dyxcry/Node
TsNode/Preset/Models/NodeService.cs
3,515
C#
using System; using System.Linq; using Hl7.Fhir.Model; namespace GaTech.Chai.Cbs.CaseNotificationPanelProfile { /// <summary> /// CBS Date Of First Report To Public Health Department Observation Profile /// http://cbsig.chai.gatech.edu/StructureDefinition/cbs-date-reported-to-phd /// </summary> public class CbsDateOfFirstReportToPublicHealthDept : CbsCaseNotificationPanel { internal CbsDateOfFirstReportToPublicHealthDept(Observation observation) : base(observation) { this.ProfileUrl = "http://cbsig.chai.gatech.edu/StructureDefinition/cbs-date-reported-to-phd"; } /// <summary> /// Factory for CBS Date Of First Report To Public Health Department Observation Profile /// http://cbsig.chai.gatech.edu/StructureDefinition/cbs-date-reported-to-phd /// </summary> public static new Observation Create() { var observation = new Observation(); observation.CbsCaseNotificationPanel().AddProfile(); observation.CbsDateOfFirstReportToPublicHealthDept().AddProfile(); observation.Code = new CodeableConcept("http://loinc.org", "77995-9", "Date of first report to public health department", null); return observation; } public FhirDateTime Value { get => this.observation.Value as FhirDateTime; set => this.observation.Value = value; } } }
38.578947
140
0.663711
[ "Apache-2.0" ]
mmg-fhir-ig/cbs-ig-dotnet
src/GaTech.Chai.Cbs/CbsCaseNotificationPanelProfile/CbsDateOfFirstReportToPublicHealthDept.cs
1,468
C#
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * 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; namespace Microsoft.DirectX.Direct3D { public enum DrawStringFormat { WordBreak = 16, VerticalCenter = 4, SingleLine = 32, RightToLeftReading = 131072, NoClip = 256, ExpandTabs = 64, Center = 1, None = 0, Top = 0, Right = 2, Left = 0, Bottom = 8 } }
32.133333
83
0.735131
[ "MIT" ]
alesliehughes/monoDX
Microsoft.DirectX.Direct3D/Microsoft.DirectX.Direct3D/DrawStringFormat.cs
1,446
C#
using System; using System.Threading.Tasks; using Fluid; using Fluid.Values; using OrchardCore.Liquid; namespace OrchardCore.Media.Filters { public class MediaUrlFilter : ILiquidFilter { private readonly IMediaFileStore _mediaFileStore; public MediaUrlFilter(IMediaFileStore mediaFileStore) { _mediaFileStore = mediaFileStore; } public Task<FluidValue> ProcessAsync(FluidValue input, FilterArguments arguments, TemplateContext ctx) { var url = input.ToStringValue(); var imageUrl = _mediaFileStore.MapPathToPublicUrl(url); return Task.FromResult<FluidValue>(new StringValue(imageUrl ?? url)); } } public class ImageTagFilter : ILiquidFilter { public Task<FluidValue> ProcessAsync(FluidValue input, FilterArguments arguments, TemplateContext ctx) { var url = input.ToStringValue(); var imgTag = $"<img src=\"{url}\""; foreach (var name in arguments.Names) { imgTag += $" {name.Replace("_", "-")}=\"{arguments[name].ToStringValue()}\""; } imgTag += " />"; return Task.FromResult<FluidValue>(new StringValue(imgTag) { Encode = false }); } } public class ResizeUrlFilter : ILiquidFilter { public Task<FluidValue> ProcessAsync(FluidValue input, FilterArguments arguments, TemplateContext ctx) { var url = input.ToStringValue(); if (!url.Contains("?")) { url += "?"; } var width = arguments["width"].Or(arguments.At(0)); var height = arguments["height"].Or(arguments.At(1)); var mode = arguments["mode"]; if (!width.IsNil()) { url += "&width=" + width.ToStringValue(); } if (!height.IsNil()) { url += "&height=" + height.ToStringValue(); } if (!mode.IsNil()) { url += "&rmode=" + mode.ToStringValue(); } return Task.FromResult<FluidValue>(new StringValue(url)); } } }
27.925
110
0.548791
[ "BSD-3-Clause" ]
AlexGuedes1986/FutbolCubano
src/OrchardCore.Modules/OrchardCore.Media/Filters/MediaFilters.cs
2,234
C#
using System; #if ! AZURE_MOBILE_SERVICES namespace Xamarin.Auth #else namespace Xamarin.Auth._MobileServices #endif { public static class FileHelper { public static string GetLocalStoragePath() { throw new NotImplementedException("Portable"); #pragma warning disable 0162 return string.Empty; } } }
18.684211
58
0.68169
[ "Apache-2.0" ]
Acidburn0zzz/Xamarin.Auth
source/Xamarin.Auth.Portable/PlatformSpecific/FileHelper.cs
355
C#
using System; using System.ComponentModel; using System.Windows.Forms; namespace HolidayLabelsAndLists { /// <summary> /// A popup window to be used by the background worker /// to display summary of progress. /// /// </summary> public partial class frmProgress : Form { public BackgroundWorker Worker { get; set; } private bool _done; /// <summary> /// When the Done property is changed, /// set this form's controls as appropriate /// to the new state. /// </summary> public bool Done { get { return _done; } set { _done = value; SetControls(); } } public frmProgress() { InitializeComponent(); Done = false; } /// <summary> /// Reset progress display /// </summary> public void Clear() { txtDisplay.Clear(); } /// <summary> /// Cancel buton enabled until we're done; /// then Close button enabled. /// </summary> /// <param name="isDone"></param> private void SetControls() { btnCancel.Enabled = !Done; btnClose.Enabled = Done; } /// <summary> /// Append a string to the end of the display /// </summary> /// <param name="msg"></param> public void AddMessage(string msg) { txtDisplay.AppendText(msg + Environment.NewLine); } /// <summary> /// If user clicks Cancel button, send word to BackgroundWorker /// to stop. Make appropriate changes to our display. /// </summary> public void Cancel() { if (Worker != null) Worker.CancelAsync(); Done = true; } private void btnCancel_Click(object sender, EventArgs e) { Cancel(); } private void btnClose_Click(object sender, EventArgs e) { this.Close(); } private void frmProgress_FormClosing(object sender, FormClosingEventArgs e) { if ((!Done) && (!Worker.CancellationPending)) e.Cancel = true; else e.Cancel = false; } } }
24.59596
83
0.482957
[ "MIT" ]
tonyrein/HolidayLabelsAndLists_Public
HolidayLabelsAndLists/frmProgress.cs
2,437
C#
using System; namespace BonusCalcListener.Boundary { public class EntityEventSns { public Guid Id { get; set; } public string EventType { get; set; } public string SourceDomain { get; set; } public string SourceSystem { get; set; } public string Version { get; set; } public Guid CorrelationId { get; set; } public DateTime DateTime { get; set; } public User User { get; set; } public Guid EntityId { get; set; } public WorkOrderOperativeSmvData EventData { get; set; } } }
20.571429
64
0.602431
[ "MIT" ]
LBHackney-IT/bonuscalc-listener
BonusCalcListener/Boundary/EntityEventSns.cs
576
C#
using System.Reflection; 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("Sautom.Domain")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sautom.Domain")] [assembly: AssemblyCopyright("Copyright © 2012")] [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("85db69f6-fc77-4cc4-a93a-3a05bd1be5d1")] // 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.777778
84
0.740441
[ "MIT" ]
nikaburu/sautom-wpf
src/Sautom.Domain/Properties/AssemblyInfo.cs
1,363
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/codecapi.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="CODECAPI_AVEncVideoForceKeyFrame" /> struct.</summary> public static unsafe class CODECAPI_AVEncVideoForceKeyFrameTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="CODECAPI_AVEncVideoForceKeyFrame" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(CODECAPI_AVEncVideoForceKeyFrame).GUID, Is.EqualTo(STATIC_CODECAPI_AVEncVideoForceKeyFrame)); } /// <summary>Validates that the <see cref="CODECAPI_AVEncVideoForceKeyFrame" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<CODECAPI_AVEncVideoForceKeyFrame>(), Is.EqualTo(sizeof(CODECAPI_AVEncVideoForceKeyFrame))); } /// <summary>Validates that the <see cref="CODECAPI_AVEncVideoForceKeyFrame" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(CODECAPI_AVEncVideoForceKeyFrame).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="CODECAPI_AVEncVideoForceKeyFrame" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(CODECAPI_AVEncVideoForceKeyFrame), Is.EqualTo(1)); } } }
42.688889
145
0.697553
[ "MIT" ]
Ethereal77/terrafx.interop.windows
tests/Interop/Windows/um/codecapi/CODECAPI_AVEncVideoForceKeyFrameTests.cs
1,923
C#
namespace Ship_Game { public sealed class Message { public string Text; public int Index; public int SetPlayerContactStep; public int SetFactionContactStep; public bool SetWar; public bool EndWar; public Array<Response> ResponseOptions = new Array<Response>(); public bool EndTransmission; } }
27.285714
72
0.623037
[ "MIT" ]
UnGaucho/StarDrive
Ship_Game/Message.cs
382
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by \generate-code.bat. // // Changes to this file will be lost when the code is regenerated. // The build server regenerates the code before each build and a pre-build // step will regenerate the code on each local build. // // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. // Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; using System.Globalization; using System.Linq; using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; #nullable enable // ReSharper disable once CheckNamespace namespace UnitsNet { /// <inheritdoc /> /// <summary> /// The Volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour. /// </summary> public partial struct ReactiveEnergy : IQuantity<ReactiveEnergyUnit>, IEquatable<ReactiveEnergy>, IComparable, IComparable<ReactiveEnergy>, IConvertible, IFormattable { /// <summary> /// The numeric value this quantity was constructed with. /// </summary> private readonly decimal _value; /// <summary> /// The unit this quantity was constructed with. /// </summary> private readonly ReactiveEnergyUnit? _unit; static ReactiveEnergy() { BaseDimensions = new BaseDimensions(2, 1, -1, 0, 0, 0, 0); Info = new QuantityInfo<ReactiveEnergyUnit>(QuantityType.ReactiveEnergy, new UnitInfo<ReactiveEnergyUnit>[] { new UnitInfo<ReactiveEnergyUnit>(ReactiveEnergyUnit.KilovoltampereReactiveHour, BaseUnits.Undefined), new UnitInfo<ReactiveEnergyUnit>(ReactiveEnergyUnit.MegavoltampereReactiveHour, BaseUnits.Undefined), new UnitInfo<ReactiveEnergyUnit>(ReactiveEnergyUnit.VoltampereReactiveHour, BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions); } /// <summary> /// Creates the quantity with the given numeric value and unit. /// </summary> /// <param name="value">The numeric value to construct this quantity with.</param> /// <param name="unit">The unit representation to construct this quantity with.</param> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public ReactiveEnergy(decimal value, ReactiveEnergyUnit unit) { if(unit == ReactiveEnergyUnit.Undefined) throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); _value = value; _unit = unit; } /// <summary> /// Creates an instance of the quantity with the given numeric value in units compatible with the given <see cref="UnitSystem"/>. /// If multiple compatible units were found, the first match is used. /// </summary> /// <param name="value">The numeric value to construct this quantity with.</param> /// <param name="unitSystem">The unit system to create the quantity with.</param> /// <exception cref="ArgumentNullException">The given <see cref="UnitSystem"/> is null.</exception> /// <exception cref="ArgumentException">No unit was found for the given <see cref="UnitSystem"/>.</exception> public ReactiveEnergy(decimal value, UnitSystem unitSystem) { if(unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); _value = value; _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } #region Static Properties /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ReactiveEnergyUnit> Info { get; } /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> public static BaseDimensions BaseDimensions { get; } /// <summary> /// The base unit of ReactiveEnergy, which is VoltampereReactiveHour. All conversions go via this value. /// </summary> public static ReactiveEnergyUnit BaseUnit { get; } = ReactiveEnergyUnit.VoltampereReactiveHour; /// <summary> /// Represents the largest possible value of ReactiveEnergy /// </summary> public static ReactiveEnergy MaxValue { get; } = new ReactiveEnergy(decimal.MaxValue, BaseUnit); /// <summary> /// Represents the smallest possible value of ReactiveEnergy /// </summary> public static ReactiveEnergy MinValue { get; } = new ReactiveEnergy(decimal.MinValue, BaseUnit); /// <summary> /// The <see cref="QuantityType" /> of this quantity. /// </summary> public static QuantityType QuantityType { get; } = QuantityType.ReactiveEnergy; /// <summary> /// All units of measurement for the ReactiveEnergy quantity. /// </summary> public static ReactiveEnergyUnit[] Units { get; } = Enum.GetValues(typeof(ReactiveEnergyUnit)).Cast<ReactiveEnergyUnit>().Except(new ReactiveEnergyUnit[]{ ReactiveEnergyUnit.Undefined }).ToArray(); /// <summary> /// Gets an instance of this quantity with a value of 0 in the base unit VoltampereReactiveHour. /// </summary> public static ReactiveEnergy Zero { get; } = new ReactiveEnergy(0, BaseUnit); #endregion #region Properties /// <summary> /// The numeric value this quantity was constructed with. /// </summary> public decimal Value => _value; Enum IQuantity.Unit => Unit; /// <inheritdoc /> public ReactiveEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// <inheritdoc /> public QuantityInfo<ReactiveEnergyUnit> QuantityInfo => Info; /// <inheritdoc cref="IQuantity.QuantityInfo"/> QuantityInfo IQuantity.QuantityInfo => Info; /// <summary> /// The <see cref="QuantityType" /> of this quantity. /// </summary> public QuantityType Type => ReactiveEnergy.QuantityType; /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> public BaseDimensions Dimensions => ReactiveEnergy.BaseDimensions; #endregion #region Conversion Properties /// <summary> /// Get ReactiveEnergy in KilovoltampereReactiveHours. /// </summary> public decimal KilovoltampereReactiveHours => As(ReactiveEnergyUnit.KilovoltampereReactiveHour); /// <summary> /// Get ReactiveEnergy in MegavoltampereReactiveHours. /// </summary> public decimal MegavoltampereReactiveHours => As(ReactiveEnergyUnit.MegavoltampereReactiveHour); /// <summary> /// Get ReactiveEnergy in VoltampereReactiveHours. /// </summary> public decimal VoltampereReactiveHours => As(ReactiveEnergyUnit.VoltampereReactiveHour); #endregion #region Static Methods /// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <returns>Unit abbreviation string.</returns> public static string GetAbbreviation(ReactiveEnergyUnit unit) { return GetAbbreviation(unit, null); } /// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <returns>Unit abbreviation string.</returns> /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> public static string GetAbbreviation(ReactiveEnergyUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } #endregion #region Static Factory Methods /// <summary> /// Get ReactiveEnergy from KilovoltampereReactiveHours. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static ReactiveEnergy FromKilovoltampereReactiveHours(QuantityValue kilovoltamperereactivehours) { decimal value = (decimal) kilovoltamperereactivehours; return new ReactiveEnergy(value, ReactiveEnergyUnit.KilovoltampereReactiveHour); } /// <summary> /// Get ReactiveEnergy from MegavoltampereReactiveHours. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static ReactiveEnergy FromMegavoltampereReactiveHours(QuantityValue megavoltamperereactivehours) { decimal value = (decimal) megavoltamperereactivehours; return new ReactiveEnergy(value, ReactiveEnergyUnit.MegavoltampereReactiveHour); } /// <summary> /// Get ReactiveEnergy from VoltampereReactiveHours. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static ReactiveEnergy FromVoltampereReactiveHours(QuantityValue voltamperereactivehours) { decimal value = (decimal) voltamperereactivehours; return new ReactiveEnergy(value, ReactiveEnergyUnit.VoltampereReactiveHour); } /// <summary> /// Dynamically convert from value and unit enum <see cref="ReactiveEnergyUnit" /> to <see cref="ReactiveEnergy" />. /// </summary> /// <param name="value">Value to convert from.</param> /// <param name="fromUnit">Unit to convert from.</param> /// <returns>ReactiveEnergy unit value.</returns> public static ReactiveEnergy From(QuantityValue value, ReactiveEnergyUnit fromUnit) { return new ReactiveEnergy((decimal)value, fromUnit); } #endregion #region Static Parse Methods /// <summary> /// Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="ArgumentException"> /// Expected string to have one or two pairs of quantity and unit in the format /// "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in" /// </exception> /// <exception cref="AmbiguousUnitParseException"> /// More than one unit is represented by the specified unit abbreviation. /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. /// </exception> /// <exception cref="UnitsNetException"> /// If anything else goes wrong, typically due to a bug or unhandled case. /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish /// Units.NET exceptions from other exceptions. /// </exception> public static ReactiveEnergy Parse(string str) { return Parse(str, null); } /// <summary> /// Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="ArgumentException"> /// Expected string to have one or two pairs of quantity and unit in the format /// "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in" /// </exception> /// <exception cref="AmbiguousUnitParseException"> /// More than one unit is represented by the specified unit abbreviation. /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. /// </exception> /// <exception cref="UnitsNetException"> /// If anything else goes wrong, typically due to a bug or unhandled case. /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish /// Units.NET exceptions from other exceptions. /// </exception> /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> public static ReactiveEnergy Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse<ReactiveEnergy, ReactiveEnergyUnit>( str, provider, From); } /// <summary> /// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="result">Resulting unit quantity if successful.</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> public static bool TryParse(string? str, out ReactiveEnergy result) { return TryParse(str, null, out result); } /// <summary> /// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="result">Resulting unit quantity if successful.</param> /// <returns>True if successful, otherwise false.</returns> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> public static bool TryParse(string? str, IFormatProvider? provider, out ReactiveEnergy result) { return QuantityParser.Default.TryParse<ReactiveEnergy, ReactiveEnergyUnit>( str, provider, From, out result); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> public static ReactiveEnergyUnit ParseUnit(string str) { return ParseUnit(str, null); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> public static ReactiveEnergyUnit ParseUnit(string str, IFormatProvider? provider) { return UnitParser.Default.Parse<ReactiveEnergyUnit>(str, provider); } /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ReactiveEnergyUnit)"/> public static bool TryParseUnit(string str, out ReactiveEnergyUnit unit) { return TryParseUnit(str, null, out unit); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="unit">The parsed unit if successful.</param> /// <returns>True if successful, otherwise false.</returns> /// <example> /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// </example> /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> public static bool TryParseUnit(string str, IFormatProvider? provider, out ReactiveEnergyUnit unit) { return UnitParser.Default.TryParse<ReactiveEnergyUnit>(str, provider, out unit); } #endregion #region Arithmetic Operators /// <summary>Negate the value.</summary> public static ReactiveEnergy operator -(ReactiveEnergy right) { return new ReactiveEnergy(-right.Value, right.Unit); } /// <summary>Get <see cref="ReactiveEnergy"/> from adding two <see cref="ReactiveEnergy"/>.</summary> public static ReactiveEnergy operator +(ReactiveEnergy left, ReactiveEnergy right) { return new ReactiveEnergy(left.Value + right.GetValueAs(left.Unit), left.Unit); } /// <summary>Get <see cref="ReactiveEnergy"/> from subtracting two <see cref="ReactiveEnergy"/>.</summary> public static ReactiveEnergy operator -(ReactiveEnergy left, ReactiveEnergy right) { return new ReactiveEnergy(left.Value - right.GetValueAs(left.Unit), left.Unit); } /// <summary>Get <see cref="ReactiveEnergy"/> from multiplying value and <see cref="ReactiveEnergy"/>.</summary> public static ReactiveEnergy operator *(decimal left, ReactiveEnergy right) { return new ReactiveEnergy(left * right.Value, right.Unit); } /// <summary>Get <see cref="ReactiveEnergy"/> from multiplying value and <see cref="ReactiveEnergy"/>.</summary> public static ReactiveEnergy operator *(ReactiveEnergy left, decimal right) { return new ReactiveEnergy(left.Value * right, left.Unit); } /// <summary>Get <see cref="ReactiveEnergy"/> from dividing <see cref="ReactiveEnergy"/> by value.</summary> public static ReactiveEnergy operator /(ReactiveEnergy left, decimal right) { return new ReactiveEnergy(left.Value / right, left.Unit); } /// <summary>Get ratio value from dividing <see cref="ReactiveEnergy"/> by <see cref="ReactiveEnergy"/>.</summary> public static decimal operator /(ReactiveEnergy left, ReactiveEnergy right) { return left.VoltampereReactiveHours / right.VoltampereReactiveHours; } #endregion #region Equality / IComparable /// <summary>Returns true if less or equal to.</summary> public static bool operator <=(ReactiveEnergy left, ReactiveEnergy right) { return left.Value <= right.GetValueAs(left.Unit); } /// <summary>Returns true if greater than or equal to.</summary> public static bool operator >=(ReactiveEnergy left, ReactiveEnergy right) { return left.Value >= right.GetValueAs(left.Unit); } /// <summary>Returns true if less than.</summary> public static bool operator <(ReactiveEnergy left, ReactiveEnergy right) { return left.Value < right.GetValueAs(left.Unit); } /// <summary>Returns true if greater than.</summary> public static bool operator >(ReactiveEnergy left, ReactiveEnergy right) { return left.Value > right.GetValueAs(left.Unit); } /// <summary>Returns true if exactly equal.</summary> /// <remarks>Consider using <see cref="Equals(ReactiveEnergy, decimal, ComparisonType)"/> for safely comparing floating point values.</remarks> public static bool operator ==(ReactiveEnergy left, ReactiveEnergy right) { return left.Equals(right); } /// <summary>Returns true if not exactly equal.</summary> /// <remarks>Consider using <see cref="Equals(ReactiveEnergy, decimal, ComparisonType)"/> for safely comparing floating point values.</remarks> public static bool operator !=(ReactiveEnergy left, ReactiveEnergy right) { return !(left == right); } /// <inheritdoc /> public int CompareTo(object obj) { if(obj is null) throw new ArgumentNullException(nameof(obj)); if(!(obj is ReactiveEnergy objReactiveEnergy)) throw new ArgumentException("Expected type ReactiveEnergy.", nameof(obj)); return CompareTo(objReactiveEnergy); } /// <inheritdoc /> public int CompareTo(ReactiveEnergy other) { return _value.CompareTo(other.GetValueAs(this.Unit)); } /// <inheritdoc /> /// <remarks>Consider using <see cref="Equals(ReactiveEnergy, decimal, ComparisonType)"/> for safely comparing floating point values.</remarks> public override bool Equals(object obj) { if(obj is null || !(obj is ReactiveEnergy objReactiveEnergy)) return false; return Equals(objReactiveEnergy); } /// <inheritdoc /> /// <remarks>Consider using <see cref="Equals(ReactiveEnergy, decimal, ComparisonType)"/> for safely comparing floating point values.</remarks> public bool Equals(ReactiveEnergy other) { return _value.Equals(other.GetValueAs(this.Unit)); } /// <summary> /// <para> /// Compare equality to another ReactiveEnergy within the given absolute or relative tolerance. /// </para> /// <para> /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of /// this quantity's value to be considered equal. /// <example> /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). /// <code> /// var a = Length.FromMeters(2.0); /// var b = Length.FromInches(50.0); /// a.Equals(b, 0.01, ComparisonType.Relative); /// </code> /// </example> /// </para> /// <para> /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into /// this quantity's unit for comparison. /// <example> /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). /// <code> /// var a = Length.FromMeters(2.0); /// var b = Length.FromInches(50.0); /// a.Equals(b, 0.01, ComparisonType.Absolute); /// </code> /// </example> /// </para> /// <para> /// Note that it is advised against specifying zero difference, due to the nature /// of floating point operations and using System.Double internally. /// </para> /// </summary> /// <param name="other">The other quantity to compare to.</param> /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> /// <param name="comparisonType">The comparison type: either relative or absolute.</param> /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> public bool Equals(ReactiveEnergy other, decimal tolerance, ComparisonType comparisonType) { if(tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); decimal thisValue = (decimal)this.Value; decimal otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A hash code for the current ReactiveEnergy.</returns> public override int GetHashCode() { return new { QuantityType, Value, Unit }.GetHashCode(); } #endregion #region Conversion Methods /// <summary> /// Convert to the unit representation <paramref name="unit" />. /// </summary> /// <returns>Value converted to the specified unit.</returns> public decimal As(ReactiveEnergyUnit unit) { if(Unit == unit) return Convert.ToDecimal(Value); var converted = GetValueAs(unit); return Convert.ToDecimal(converted); } /// <inheritdoc cref="IQuantity.As(UnitSystem)"/> public decimal As(UnitSystem unitSystem) { if(unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); if(firstUnitInfo == null) throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); return As(firstUnitInfo.Value); } /// <inheritdoc /> decimal IQuantity.As(Enum unit) { if(!(unit is ReactiveEnergyUnit unitAsReactiveEnergyUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactiveEnergyUnit)} is supported.", nameof(unit)); return As(unitAsReactiveEnergyUnit); } /// <summary> /// Converts this ReactiveEnergy to another ReactiveEnergy with the unit representation <paramref name="unit" />. /// </summary> /// <returns>A ReactiveEnergy with the specified unit.</returns> public ReactiveEnergy ToUnit(ReactiveEnergyUnit unit) { var convertedValue = GetValueAs(unit); return new ReactiveEnergy(convertedValue, unit); } /// <inheritdoc /> IQuantity IQuantity.ToUnit(Enum unit) { if(!(unit is ReactiveEnergyUnit unitAsReactiveEnergyUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReactiveEnergyUnit)} is supported.", nameof(unit)); return ToUnit(unitAsReactiveEnergyUnit); } /// <inheritdoc cref="IQuantity.ToUnit(UnitSystem)"/> public ReactiveEnergy ToUnit(UnitSystem unitSystem) { if(unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); if(firstUnitInfo == null) throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); return ToUnit(firstUnitInfo.Value); } /// <inheritdoc /> IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); /// <inheritdoc /> IQuantity<ReactiveEnergyUnit> IQuantity<ReactiveEnergyUnit>.ToUnit(ReactiveEnergyUnit unit) => ToUnit(unit); /// <inheritdoc /> IQuantity<ReactiveEnergyUnit> IQuantity<ReactiveEnergyUnit>.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); /// <summary> /// Converts the current value + unit to the base unit. /// This is typically the first step in converting from one unit to another. /// </summary> /// <returns>The value in the base unit representation.</returns> private decimal GetValueInBaseUnit() { switch(Unit) { case ReactiveEnergyUnit.KilovoltampereReactiveHour: return (_value) * 1e3m; case ReactiveEnergyUnit.MegavoltampereReactiveHour: return (_value) * 1e6m; case ReactiveEnergyUnit.VoltampereReactiveHour: return _value; default: throw new NotImplementedException($"Can not convert {Unit} to base units."); } } /// <summary> /// Converts the current value + unit to the base unit. /// This is typically the first step in converting from one unit to another. /// </summary> /// <returns>The value in the base unit representation.</returns> internal ReactiveEnergy ToBaseUnit() { var baseUnitValue = GetValueInBaseUnit(); return new ReactiveEnergy(baseUnitValue, BaseUnit); } private decimal GetValueAs(ReactiveEnergyUnit unit) { if(Unit == unit) return _value; var baseUnitValue = GetValueInBaseUnit(); switch(unit) { case ReactiveEnergyUnit.KilovoltampereReactiveHour: return (baseUnitValue) / 1e3m; case ReactiveEnergyUnit.MegavoltampereReactiveHour: return (baseUnitValue) / 1e6m; case ReactiveEnergyUnit.VoltampereReactiveHour: return baseUnitValue; default: throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } } #endregion #region ToString Methods /// <summary> /// Gets the default string representation of value and unit. /// </summary> /// <returns>String representation.</returns> public override string ToString() { return ToString("g"); } /// <summary> /// Gets the default string representation of value and unit using the given format provider. /// </summary> /// <returns>String representation.</returns> /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> public string ToString(IFormatProvider? provider) { return ToString("g", provider); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="significantDigitsAfterRadix">The number of significant digits after the radix point.</param> /// <returns>String representation.</returns> /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) { var value = Convert.ToDecimal(Value); var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); return ToString(provider, format); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="format">String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively."</param> /// <param name="args">Arguments for string format. Value and unit are implicitly included as arguments 0 and 1.</param> /// <returns>String representation.</returns> /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); provider = provider ?? CultureInfo.CurrentUICulture; var value = Convert.ToDecimal(Value); var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> /// <summary> /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentUICulture" />. /// </summary> /// <param name="format">The format string.</param> /// <returns>The string representation.</returns> public string ToString(string format) { return ToString(format, CultureInfo.CurrentUICulture); } /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> /// <summary> /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentUICulture" /> if null. /// </summary> /// <param name="format">The format string.</param> /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> /// <returns>The string representation.</returns> public string ToString(string format, IFormatProvider? provider) { return QuantityFormatter.Format<ReactiveEnergyUnit>(this, format, provider); } #endregion #region IConvertible Methods TypeCode IConvertible.GetTypeCode() { return TypeCode.Object; } bool IConvertible.ToBoolean(IFormatProvider provider) { throw new InvalidCastException($"Converting {typeof(ReactiveEnergy)} to bool is not supported."); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(_value); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException($"Converting {typeof(ReactiveEnergy)} to char is not supported."); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException($"Converting {typeof(ReactiveEnergy)} to DateTime is not supported."); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(_value); } string IConvertible.ToString(IFormatProvider provider) { return ToString("g", provider); } object IConvertible.ToType(Type conversionType, IFormatProvider provider) { if(conversionType == typeof(ReactiveEnergy)) return this; else if(conversionType == typeof(ReactiveEnergyUnit)) return Unit; else if(conversionType == typeof(QuantityType)) return ReactiveEnergy.QuantityType; else if(conversionType == typeof(BaseDimensions)) return ReactiveEnergy.BaseDimensions; else throw new InvalidCastException($"Converting {typeof(ReactiveEnergy)} to {conversionType} is not supported."); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(_value); } #endregion } }
44.073281
222
0.616965
[ "MIT-feh" ]
IjaCZECH/UnitsNet
UnitsNet/GeneratedCode/Quantities/ReactiveEnergy.g.cs
39,095
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Kujikatsu078.Algorithms; using Kujikatsu078.Collections; using Kujikatsu078.Extensions; using Kujikatsu078.Numerics; using Kujikatsu078.Questions; namespace Kujikatsu078.Questions { public class QuestionD : AtCoderQuestionBase { public override IEnumerable<object> Solve(TextReader inputStream) { throw new NotImplementedException(); } } }
24
73
0.763889
[ "MIT" ]
terry-u16/AtCoder
Kujikatsu078/Kujikatsu078/Kujikatsu078/Questions/QuestionD.cs
578
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace FinnovationLabs.OpenBanking.Library.BankApiModels.UkObRw.V3p1p8.Pisp.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; public partial class OBWriteFileConsentResponse4 { /// <summary> /// Initializes a new instance of the OBWriteFileConsentResponse4 /// class. /// </summary> public OBWriteFileConsentResponse4() { CustomInit(); } /// <summary> /// Initializes a new instance of the OBWriteFileConsentResponse4 /// class. /// </summary> public OBWriteFileConsentResponse4(OBWriteFileConsentResponse4Data data, Links links = default(Links), Meta meta = default(Meta)) { Data = data; Links = links; Meta = meta; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "Data")] public OBWriteFileConsentResponse4Data Data { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "Links")] public Links Links { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "Meta")] public Meta Meta { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Data == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Data"); } if (Data != null) { Data.Validate(); } if (Links != null) { Links.Validate(); } } } }
28.177215
137
0.540431
[ "MIT" ]
finlabsuk/open-banking-connector
src/OpenBanking.Library.BankApiModels/UkObRw/V3p1p8/Pisp/Models/OBWriteFileConsentResponse4.cs
2,226
C#
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft. All rights reserved. namespace Microsoft.Samples.HyperV.Storage { using System; using System.Globalization; using System.Reflection; class Program { /// <summary> /// Entry point of the program. /// </summary> /// <param name="args">Command line arguments.</param> static void Main( string[] args) { if (args.Length == 3) { if (string.Equals(args[0], "GetVirtualHardDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string virtualHardDiskPath = args[2]; StorageGetSample.GetVirtualHardDisk( serverName, virtualHardDiskPath); } else if (string.Equals(args[0], "ValidateVirtualHardDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string virtualHardDiskPath = args[2]; StorageValidateSample.ValidateVirtualHardDisk( serverName, virtualHardDiskPath); } else if (string.Equals(args[0], "DetachVirtualHardDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string virtualHardDiskPath = args[2]; StorageDetachSample.DetachVirtualHardDisk( serverName, virtualHardDiskPath); } else if (string.Equals(args[0], "CreateVirtualFloppyDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string virtualHardDiskPath = args[2]; StorageFloppySample.CreateVirtualFloppyDisk( serverName, virtualHardDiskPath); } else { ShowUsage(); } } else if (args.Length == 4) { if (string.Equals(args[0], "CompactVirtualHardDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string virtualHardDiskPath = args[2]; string mode = args[3]; if (string.Equals(mode, "2", StringComparison.OrdinalIgnoreCase)) { StorageAttachSample.AttachVirtualHardDisk( serverName, virtualHardDiskPath, "false", "true"); } StorageCompactSample.CompactVirtualHardDisk( serverName, virtualHardDiskPath, mode); if (string.Equals(mode, "2", StringComparison.OrdinalIgnoreCase)) { StorageDetachSample.DetachVirtualHardDisk( serverName, virtualHardDiskPath); } } else if (string.Equals(args[0], "MergeVirtualHardDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string sourcePath = args[2]; string destinationPath = args[3]; StorageMergeSample.MergeVirtualHardDisk( serverName, sourcePath, destinationPath); } else if (string.Equals(args[0], "ResizeVirtualHardDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string virtualHardDiskPath = args[2]; UInt64 fileSize = UInt64.Parse(args[3], CultureInfo.CurrentCulture); StorageResizeSample.ResizeVirtualHardDisk( serverName, virtualHardDiskPath, fileSize); } else if (string.Equals(args[0], "SetVirtualHardDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string virtualHardDiskPath = args[2]; Int32 sectorSize; string parentPath = args[3]; if (Int32.TryParse(args[3], NumberStyles.None, CultureInfo.CurrentCulture, out sectorSize)) { StorageSetSample.SetVirtualHardDisk( serverName, virtualHardDiskPath, null, sectorSize); } else { StorageSetSample.SetVirtualHardDisk( serverName, virtualHardDiskPath, parentPath, 0); } } else { ShowUsage(); } } else if (args.Length == 5) { if (string.Equals(args[0], "AttachVirtualHardDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string virtualHardDiskPath = args[2]; string assignDriveLetter = args[3]; string readOnly = args[4]; StorageAttachSample.AttachVirtualHardDisk( serverName, virtualHardDiskPath, assignDriveLetter, readOnly); } else if (string.Equals(args[0], "CreateDifferencingVirtualHardDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string virtualHardDiskPath = args[2]; string parentPath = args[3]; VirtualHardDiskType type = VirtualHardDiskType.Differencing; VirtualHardDiskFormat format; if (string.Equals(args[4], "vhdx", StringComparison.OrdinalIgnoreCase)) { format = VirtualHardDiskFormat.Vhdx; } else { format = VirtualHardDiskFormat.Vhd; } StorageCreateSample.CreateVirtualHardDisk( serverName, virtualHardDiskPath, parentPath, type, format, 0, 0, 0, 0); } else if (string.Equals(args[0], "ConvertVirtualHardDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string sourcePath = args[2]; string destinationPath = args[3]; VirtualHardDiskFormat format; if (string.Equals(args[4], "vhdx", StringComparison.OrdinalIgnoreCase)) { format = VirtualHardDiskFormat.Vhdx; } else { format = VirtualHardDiskFormat.Vhd; } StorageConvertSample.ConvertVirtualHardDisk( serverName, sourcePath, destinationPath, format); } else { ShowUsage(); } } else if (args.Length == 6) { if (string.Equals(args[0], "SetParentVirtualHardDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string ChildPath = args[2]; string ParentPath = args[3]; string LeafPath = args[4]; string IgnoreIDMismatch = args[5]; if (string.Equals(LeafPath, "null", StringComparison.OrdinalIgnoreCase)) { // Only valid if VHD is not online. LeafPath = null; } StorageSetParentSample.SetParentVirtualHardDisk( serverName, ChildPath, ParentPath, LeafPath, IgnoreIDMismatch); } else { ShowUsage(); } } else if (args.Length == 8) { if (string.Equals(args[0], "CreateFixedVirtualHardDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string virtualHardDiskPath = args[2]; string parentPath = null; VirtualHardDiskType type = VirtualHardDiskType.FixedSize; VirtualHardDiskFormat format; if (string.Equals(args[3], "vhdx", StringComparison.OrdinalIgnoreCase)) { format = VirtualHardDiskFormat.Vhdx; } else { format = VirtualHardDiskFormat.Vhd; } Int64 fileSize = Int64.Parse(args[4], CultureInfo.CurrentCulture); Int32 blockSize = Int32.Parse(args[5], CultureInfo.CurrentCulture); Int32 logicalSectorSize = Int32.Parse(args[6], CultureInfo.CurrentCulture); Int32 physicalSectorSize = Int32.Parse(args[7], CultureInfo.CurrentCulture); StorageCreateSample.CreateVirtualHardDisk( serverName, virtualHardDiskPath, parentPath, type, format, fileSize, blockSize, logicalSectorSize, physicalSectorSize); } else if (string.Equals(args[0], "CreateDynamicVirtualHardDisk", StringComparison.OrdinalIgnoreCase)) { string serverName = args[1]; string virtualHardDiskPath = args[2]; string parentPath = null; VirtualHardDiskType type = VirtualHardDiskType.DynamicallyExpanding; VirtualHardDiskFormat format; if (string.Equals(args[3], "vhdx", StringComparison.OrdinalIgnoreCase)) { format = VirtualHardDiskFormat.Vhdx; } else { format = VirtualHardDiskFormat.Vhd; } Int64 fileSize = Int64.Parse(args[4], CultureInfo.CurrentCulture); Int32 blockSize = Int32.Parse(args[5], CultureInfo.CurrentCulture); Int32 logicalSectorSize = Int32.Parse(args[6], CultureInfo.CurrentCulture); Int32 physicalSectorSize = Int32.Parse(args[7], CultureInfo.CurrentCulture); StorageCreateSample.CreateVirtualHardDisk( serverName, virtualHardDiskPath, parentPath, type, format, fileSize, blockSize, logicalSectorSize, physicalSectorSize); } else { ShowUsage(); } } else { ShowUsage(); } } /// <summary> /// Displays the command line usage for the program. /// </summary> static void ShowUsage() { string moduleName = Assembly.GetExecutingAssembly().GetModules()[0].Name; Console.WriteLine("\nUsage:\t{0} <SampleName> <Arguments>\n", moduleName); Console.WriteLine("Supported SampleNames and Arguments:\n"); Console.WriteLine(" GetVirtualHardDisk <server> <path>"); Console.WriteLine(" SetVirtualHardDisk <server> <path> [<parent> | <physical sector size>]"); Console.WriteLine(" ValidateVirtualHardDisk <server> <path>"); Console.WriteLine(" CreateFixedVirtualHardDisk <server> <path> <file size> <block size> <logical sector size> <physical sector size>"); Console.WriteLine(" CreateDynamicVirtualHardDisk <server> <path> <file size> <block size> <logical sector size> <physical sector size>"); Console.WriteLine(" CreateDifferencingVirtualHardDisk <server> <path> <parent path>"); Console.WriteLine(" CreateVirtualFloppyDisk <server> <path>"); Console.WriteLine(" AttachVirtualHardDisk <server> <path> <assign drive letter> <read only>"); Console.WriteLine(" DetachVirtualHardDisk <server> <path>"); Console.WriteLine(" SetParentVirtualHardDisk <child> <parent> <leaf> <ignore id mismatch>"); Console.WriteLine(" ConvertVirtualHardDisk <server> <source path> <destination path> <format>"); Console.WriteLine(" MergeVirtualHardDisk <server> <source path> <destination path>"); Console.WriteLine(" CompactVirtualHardDisk <server> <path> <mode>"); Console.WriteLine(" ResizeVirtualHardDisk <server> <path> <file size>"); Console.WriteLine("\n"); Console.WriteLine("Examples:\n"); Console.WriteLine(" {0} GetVirtualHardDisk . c:\\fixed.vhd", moduleName); Console.WriteLine(" {0} SetVirtualHardDisk . c:\\diff.vhdx c:\\dynamic.vhdx", moduleName); Console.WriteLine(" {0} SetVirtualHardDisk . c:\\diff.vhdx 512", moduleName); Console.WriteLine(" {0} ValidateVirtualHardDisk . c:\\fixed.vhd", moduleName); Console.WriteLine(" {0} CreateFixedVirtualHardDisk . c:\\fixed.vhd vhd 1073741824 0 0 0", moduleName); Console.WriteLine(" {0} CreateDynamicVirtualHardDisk . c:\\dynamic.vhd vhd 1073741824 0 0 0", moduleName); Console.WriteLine(" {0} CreateDifferencingVirtualHardDisk . c:\\diff.vhd c:\\dynamic.vhd vhd", moduleName); Console.WriteLine(" {0} CreateVirtualFloppyDisk . c:\\floppy.vfd", moduleName); Console.WriteLine(" {0} AttachVirtualHardDisk . c:\\fixed.vhd true true", moduleName); Console.WriteLine(" {0} DetachVirtualHardDisk . c:\\fixed.vhd", moduleName); Console.WriteLine(" {0} SetParentVirtualHardDisk . c:\\diff.vhd c:\\fixed.vhd null false", moduleName); Console.WriteLine(" {0} ConvertVirtualHardDisk . c:\\dynamic.vhd c:\\fixed.vhd vhd", moduleName); Console.WriteLine(" {0} MergeVirtualHardDisk . c:\\diff.vhd c:\\dynamic.vhd", moduleName); Console.WriteLine(" {0} CompactVirtualHardDisk . c:\\dynamic.vhd 0", moduleName); Console.WriteLine(" {0} ResizeVirtualHardDisk . c:\\dynamic.vhd 2147483648", moduleName); Console.WriteLine("\n"); Console.WriteLine("\n"); } } }
45.504021
152
0.463972
[ "MIT" ]
9578577/Windows-classic-samples
Samples/Hyper-V/Storage/cs/Program.cs
16,601
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/ShObjIdl.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="ExplorerBrowser" /> struct.</summary> public static unsafe partial class ExplorerBrowserTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="ExplorerBrowser" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(ExplorerBrowser).GUID, Is.EqualTo(IID_ExplorerBrowser)); } /// <summary>Validates that the <see cref="ExplorerBrowser" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<ExplorerBrowser>(), Is.EqualTo(sizeof(ExplorerBrowser))); } /// <summary>Validates that the <see cref="ExplorerBrowser" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(ExplorerBrowser).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="ExplorerBrowser" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(ExplorerBrowser), Is.EqualTo(1)); } }
36.818182
145
0.709877
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/Windows/um/ShObjIdl/ExplorerBrowserTests.cs
1,622
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 04:45:50 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; #nullable enable namespace go { public static partial class runtime_package { [GeneratedCode("go2cs", "0.1.0.0")] private partial struct stackt { // Constructors public stackt(NilType _) { this.ss_sp = default; this.ss_flags = default; this.ss_size = default; } public stackt(ref ptr<byte> ss_sp = default, int ss_flags = default, System.UIntPtr ss_size = default) { this.ss_sp = ss_sp; this.ss_flags = ss_flags; this.ss_size = ss_size; } // Enable comparisons between nil and stackt struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(stackt value, NilType nil) => value.Equals(default(stackt)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(stackt value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, stackt value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, stackt value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator stackt(NilType nil) => default(stackt); } [GeneratedCode("go2cs", "0.1.0.0")] private static stackt stackt_cast(dynamic value) { return new stackt(ref value.ss_sp, value.ss_flags, value.ss_size); } } }
34.5
114
0.576993
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/runtime/defs_linux_386_stacktStruct.cs
2,208
C#
using System.Linq; using Sentry.Internals.DiagnosticSource; namespace Sentry { /// <summary> /// The additional Sentry Options extensions from Sentry Diagnostic Listener. /// </summary> public static class SentryOptionsDiagnosticExtensions { /// <summary> /// Attach Sentry to System DiagnosticSource. /// </summary> /// <param name="options">The Sentry options.</param> public static void AddDiagnosticSourceIntegration(this SentryOptions options) => options.AddIntegration(new SentryDiagnosticListenerIntegration()); /// <summary> /// Disables the integrations with Diagnostic source. /// </summary> /// <param name="options">The SentryOptions to remove the integration from.</param> public static void DisableDiagnosticSourceIntegration(this SentryOptions options) => options.Integrations = options.Integrations?.Where(p => p.GetType() != typeof(SentryDiagnosticListenerIntegration)).ToArray(); } }
38.814815
119
0.671756
[ "MIT" ]
kanadaj/sentry-dotnet
src/Sentry.DiagnosticSource/SentryOptionsDiagnosticExtensions.cs
1,048
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Engine.Models { public class Player : INotifyPropertyChanged { private string _name; private string _characterClass; private int _hitPoints; private int _experiencePoints; private int _level; private int _gold; public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } public string CharacterClass { get { return _characterClass; } set { _characterClass = value; OnPropertyChanged("CharacterClass"); } } public int HitPoints { get { return _hitPoints; } set { _hitPoints = value; OnPropertyChanged("HitPoints"); } } public int ExperiencePoints { get { return _experiencePoints; } set { _experiencePoints = value; OnPropertyChanged("ExperiencePoints"); } } public int Level { get { return _level; } set { _level = value; OnPropertyChanged("Level"); } } public int Gold { get { return _gold; } set { _gold = value; OnPropertyChanged("Gold"); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertName)); } } } /* One way that Scott Lily explained the starting points of building a program by listing out the requirements of a game. A user can create a player, different classes and bonuses for each class. The player can move to locations, fight monsters, obtain treasures and skill points. In battle, hit points might be lost or regained. If a player loses, then he returns home and is completely healed. The location might have a quest, monster, loot, or so forth. If the quest is failed, then the player is sent back home. If the quest is completed then the player gets skills, loot and moves forward. The location might have a merchant or trader, so the player can buy/sell items. Player can also save/load game at a checkpoint. SO now take all the nouns and turn them into classes, then determine properties of the classes. */
29
120
0.570565
[ "MIT" ]
ajohnson819/RPG-D-D
Engine/Models/Player.cs
2,815
C#
// Copyright (c) 2019, WebsitePanel-Support.net. // Distributed by websitepanel-support.net // Build and fixed by Key4ce - IT Professionals // https://www.key4ce.com // // Original source: // Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace WebsitePanel.Providers.FTP.IIs70.Config { using Microsoft.Web.Administration; using System; internal class MessagesElement : ConfigurationElement { public bool AllowLocalDetailedErrors { get { return (bool) base["allowLocalDetailedErrors"]; } set { base["allowLocalDetailedErrors"] = value; } } public string BannerMessage { get { return (string) base["bannerMessage"]; } set { base["bannerMessage"] = value; } } public string ExitMessage { get { return (string) base["exitMessage"]; } set { base["exitMessage"] = value; } } public bool ExpandVariables { get { return (bool) base["expandVariables"]; } set { base["expandVariables"] = value; } } public string GreetingMessage { get { return (string) base["greetingMessage"]; } set { base["greetingMessage"] = value; } } public string MaxClientsMessage { get { return (string) base["maxClientsMessage"]; } set { base["maxClientsMessage"] = value; } } public bool SuppressDefaultBanner { get { return (bool) base["suppressDefaultBanner"]; } set { base["suppressDefaultBanner"] = value; } } } }
30.757813
84
0.541529
[ "BSD-3-Clause" ]
Key4ce/Websitepanel
WebsitePanel/Sources/WebsitePanel.Providers.FTP.IIs70/Configuration/MessagesElement.cs
3,937
C#
namespace Umbraco.Inception.Converters { using System; using System.ComponentModel; using Umbraco.Core.Models; using Umbraco.Inception.BL; using Umbraco.Inception.Extensions; using Umbraco.Web; /// <summary> /// The model converter. /// </summary> /// <typeparam name="T">The <see cref="T:System.Type"/> to convert to and from.</typeparam> public class ModelConverter<T> : TypeConverter { /// <summary> /// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context. /// </summary> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param> /// <param name="sourceType">A <see cref="T:System.Type" /> that represents the type you want to convert from.</param> /// <returns> /// true if this converter can perform the conversion; otherwise, false. /// </returns> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } // Always call the base to see if it can perform the conversion. return base.CanConvertFrom(context, sourceType); } /// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param> /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> to use as the current culture.</param> /// <param name="value">The <see cref="T:System.Object" /> to convert.</param> /// <returns> /// An <see cref="T:System.Object" /> that represents the converted value. /// </returns> public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { int id; if (int.TryParse(value as string, out id)) { UmbracoHelper helper = ConverterHelper.GetUmbracoHelper(); IPublishedContent content = helper.TypedContent(id); return content.ConvertToModel<T>(); } // Always call base, even if you can't convert. return base.ConvertFrom(context, culture, value); } /// <summary> /// Returns whether this converter can convert the object to the specified type, using the specified context. /// </summary> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param> /// <param name="destinationType">A <see cref="T:System.Type" /> that represents the type you want to convert to.</param> /// <returns> /// true if this converter can perform the conversion; otherwise, false. /// </returns> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(T)) { return true; } // Always call the base to see if it can perform the conversion. return base.CanConvertTo(context, destinationType); } /// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param> /// <param name="culture">A <see cref="T:System.Globalization.CultureInfo" />. If null is passed, the current culture is assumed.</param> /// <param name="value">The <see cref="T:System.Object" /> to convert.</param> /// <param name="destinationType">The <see cref="T:System.Type" /> to convert the <paramref name="value" /> parameter to.</param> /// <returns> /// An <see cref="T:System.Object" /> that represents the converted value. /// </returns> public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { T target = (T)value; UmbracoGeneratedBase baseObject = target as UmbracoGeneratedBase; if (baseObject != null && baseObject.UmbracoId != null) { return baseObject.UmbracoId; } // Always call base, even if you can't convert. return base.ConvertTo(context, culture, value, destinationType); } } }
48.762376
150
0.616447
[ "MIT" ]
Qite/Umbraco-Inception
Umbraco.Inception/Converters/ModelConverter.cs
4,927
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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. */ namespace TencentCloud.Vod.V20180717.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class ProcessMediaByUrlRequest : AbstractModel { /// <summary> /// 输入视频信息,包括视频 URL , 名称、视频自定义 ID。 /// </summary> [JsonProperty("InputInfo")] public MediaInputInfo InputInfo{ get; set; } /// <summary> /// 输出文件 COS 路径信息。 /// </summary> [JsonProperty("OutputInfo")] public MediaOutputInfo OutputInfo{ get; set; } /// <summary> /// 视频内容审核类型任务参数。 /// </summary> [JsonProperty("AiContentReviewTask")] public AiContentReviewTaskInput AiContentReviewTask{ get; set; } /// <summary> /// 视频内容分析类型任务参数。 /// </summary> [JsonProperty("AiAnalysisTask")] public AiAnalysisTaskInput AiAnalysisTask{ get; set; } /// <summary> /// 视频内容识别类型任务参数。 /// </summary> [JsonProperty("AiRecognitionTask")] public AiRecognitionTaskInput AiRecognitionTask{ get; set; } /// <summary> /// 任务流的优先级,数值越大优先级越高,取值范围是 -10 到 10,不填代表 0。 /// </summary> [JsonProperty("TasksPriority")] public long? TasksPriority{ get; set; } /// <summary> /// 任务流状态变更通知模式,可取值有 Finish,Change 和 None,不填代表 Finish。 /// </summary> [JsonProperty("TasksNotifyMode")] public string TasksNotifyMode{ get; set; } /// <summary> /// 来源上下文,用于透传用户请求信息,任务流状态变更回调将返回该字段值,最长 1000 个字符。 /// </summary> [JsonProperty("SessionContext")] public string SessionContext{ get; set; } /// <summary> /// 用于去重的识别码,如果七天内曾有过相同的识别码的请求,则本次的请求会返回错误。最长 50 个字符,不带或者带空字符串表示不做去重。 /// </summary> [JsonProperty("SessionId")] public string SessionId{ get; set; } /// <summary> /// 点播[子应用](/document/product/266/14574) ID。如果要访问子应用中的资源,则将该字段填写为子应用 ID;否则无需填写该字段。 /// </summary> [JsonProperty("SubAppId")] public ulong? SubAppId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamObj(map, prefix + "InputInfo.", this.InputInfo); this.SetParamObj(map, prefix + "OutputInfo.", this.OutputInfo); this.SetParamObj(map, prefix + "AiContentReviewTask.", this.AiContentReviewTask); this.SetParamObj(map, prefix + "AiAnalysisTask.", this.AiAnalysisTask); this.SetParamObj(map, prefix + "AiRecognitionTask.", this.AiRecognitionTask); this.SetParamSimple(map, prefix + "TasksPriority", this.TasksPriority); this.SetParamSimple(map, prefix + "TasksNotifyMode", this.TasksNotifyMode); this.SetParamSimple(map, prefix + "SessionContext", this.SessionContext); this.SetParamSimple(map, prefix + "SessionId", this.SessionId); this.SetParamSimple(map, prefix + "SubAppId", this.SubAppId); } } }
35.542056
93
0.618196
[ "Apache-2.0" ]
allenlooplee/tencentcloud-sdk-dotnet
TencentCloud/Vod/V20180717/Models/ProcessMediaByUrlRequest.cs
4,333
C#
#region License /*** * Copyright © 2018-2021, 张强 (943620963@qq.com). * * 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. */ #endregion using System; using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using Newtonsoft.Json; using ZqUtils.Extensions; /**************************** * [Author] 张强 * [Date] 2015-10-26 * [Describe] XML工具类 * **************************/ namespace ZqUtils.Helpers { /// <summary> /// XML工具类 /// </summary> public class XmlHelper { #region XML转换为Dictionary /// <summary> /// XML字符串转换为Dictionary /// </summary> /// <param name="xml">XML字符串</param> /// <param name="rootNode">根节点</param> /// <returns>Dictionary</returns> public static Dictionary<string, string> XmlToDictionary(string xml, string rootNode = "xml") { var dic = new Dictionary<string, string>(); if (!xml.IsNull()) { var xmlDoc = new XmlDocument { //修复XML外部实体注入漏洞(XML External Entity Injection,简称 XXE) XmlResolver = null }; xmlDoc.LoadXml(xml); var root = xmlDoc.SelectSingleNode(rootNode); var xnl = root.ChildNodes; foreach (XmlNode xnf in xnl) { dic.Add(xnf.Name, xnf.InnerText); } } return dic; } /// <summary> /// Stream转换为Dictionary /// </summary> /// <param name="stream">XML字节流</param> /// <param name="rootNode">根节点</param> /// <returns>Dictionary</returns> public static Dictionary<string, string> XmlToDictionary(Stream stream, string rootNode = "xml") { var dic = new Dictionary<string, string>(); if (stream?.Length > 0) { var xmlDoc = new XmlDocument { //修复XML外部实体注入漏洞(XML External Entity Injection,简称 XXE) XmlResolver = null }; xmlDoc.Load(stream); var root = xmlDoc.SelectSingleNode(rootNode); var xnl = root.ChildNodes; foreach (XmlNode xnf in xnl) { dic.Add(xnf.Name, xnf.InnerText); } } return dic; } #endregion #region XML转换为JSON字符串 /// <summary> /// XML字符串转JSON字符串 /// </summary> /// <param name="xml">XML字符串</param> /// <returns>JSON字符串</returns> public static string XmlToJson(string xml) { if (xml.IsNullOrEmpty()) return null; var doc = new XmlDocument() { //修复XML外部实体注入漏洞(XML External Entity Injection,简称 XXE) XmlResolver = null }; doc.LoadXml(xml); return JsonConvert.SerializeXmlNode(doc); } #endregion #region XML序列化初始化 /// <summary> /// XML序列化初始化 /// </summary> /// <param name="stream">字节流</param> /// <param name="o">要序列化的对象</param> /// <param name="encoding">编码方式</param> private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding) { if (o == null) throw new ArgumentNullException("o"); var serializer = new XmlSerializer(o.GetType()); var settings = new XmlWriterSettings { Indent = true, NewLineChars = "\r\n", Encoding = encoding ?? throw new ArgumentNullException("encoding"), IndentChars = " " }; using (var writer = XmlWriter.Create(stream, settings)) { serializer.Serialize(writer, o); writer.Close(); } } #endregion #region 将一个对象序列化为XML字符串 /// <summary> /// 将一个对象序列化为XML字符串 /// </summary> /// <param name="o">要序列化的对象</param> /// <param name="encoding">编码方式</param> /// <returns>序列化产生的XML字符串</returns> public static string XmlSerialize(object o, Encoding encoding) { using (var stream = new MemoryStream()) { XmlSerializeInternal(stream, o, encoding); stream.Position = 0; using (var reader = new StreamReader(stream, encoding)) { return reader.ReadToEnd(); } } } #endregion #region 将一个对象按XML序列化的方式写入到一个文件 /// <summary> /// 将一个对象按XML序列化的方式写入到一个文件 /// </summary> /// <param name="o">要序列化的对象</param> /// <param name="path">保存文件路径</param> /// <param name="encoding">编码方式</param> public static void XmlSerializeToFile(object o, string path, Encoding encoding) { if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path"); using (var file = new FileStream(path, FileMode.Create, FileAccess.Write)) { XmlSerializeInternal(file, o, encoding); } } #endregion #region 从XML字符串中反序列化对象 /// <summary> /// 从XML字符串中反序列化对象 /// </summary> /// <typeparam name="T">结果对象类型</typeparam> /// <param name="s">包含对象的XML字符串</param> /// <param name="encoding">编码方式</param> /// <returns>反序列化得到的对象</returns> public static T XmlDeserialize<T>(string s, Encoding encoding) { if (string.IsNullOrEmpty(s)) throw new ArgumentNullException("s"); if (encoding == null) throw new ArgumentNullException("encoding"); var serializer = new XmlSerializer(typeof(T)); using (var ms = new MemoryStream(encoding.GetBytes(s))) { using (var sr = new StreamReader(ms, encoding)) { return (T)serializer.Deserialize(sr); } } } #endregion #region 读入一个文件,并按XML的方式反序列化对象 /// <summary> /// 读入一个文件,并按XML的方式反序列化对象。 /// </summary> /// <typeparam name="T">结果对象类型</typeparam> /// <param name="path">文件路径</param> /// <param name="encoding">编码方式</param> /// <returns>反序列化得到的对象</returns> public static T XmlDeserializeFromFile<T>(string path, Encoding encoding) { if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path"); if (encoding == null) throw new ArgumentNullException("encoding"); var xml = File.ReadAllText(path, encoding); return XmlDeserialize<T>(xml, encoding); } #endregion } }
33.701357
104
0.528061
[ "Apache-2.0" ]
786744873/ZqUtils
ZqUtils/Helpers/XmlHelper.cs
8,103
C#
using System.Windows; using System.Windows.Controls; namespace Panuon.UI.Silver { public class Loading : Control { #region Fields #endregion #region Ctor static Loading() { DefaultStyleKeyProperty.OverrideMetadata(typeof(Loading), new FrameworkPropertyMetadata(typeof(Loading))); } #endregion #region Properties #region LoadingStyle public LoadingStyle LoadingStyle { get { return (LoadingStyle)GetValue(LoadingStyleProperty); } set { SetValue(LoadingStyleProperty, value); } } public static readonly DependencyProperty LoadingStyleProperty = DependencyProperty.Register("LoadingStyle", typeof(LoadingStyle), typeof(Loading)); #endregion #region Speed public LoadingSpeed Speed { get { return (LoadingSpeed)GetValue(SpeedProperty); } set { SetValue(SpeedProperty, value); } } public static readonly DependencyProperty SpeedProperty = DependencyProperty.Register("Speed", typeof(LoadingSpeed), typeof(Loading)); #endregion #region Thickness public double Thickness { get { return (double)GetValue(ThicknessProperty); } set { SetValue(ThicknessProperty, value); } } public static readonly DependencyProperty ThicknessProperty = DependencyProperty.Register("Thickness", typeof(double), typeof(Loading)); #endregion #region CornerRadius public CornerRadius CornerRadius { get { return (CornerRadius)GetValue(CornerRadiusProperty); } set { SetValue(CornerRadiusProperty, value); } } public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(Loading)); #endregion #region IsLoading public bool IsLoading { get { return (bool)GetValue(IsLoadingProperty); } set { SetValue(IsLoadingProperty, value); } } public static readonly DependencyProperty IsLoadingProperty = DependencyProperty.Register("IsLoading", typeof(bool), typeof(Loading)); #endregion #endregion #region Internal Properties #region Percent internal double Percent { get { return (double)GetValue(PercentProperty); } set { SetValue(PercentProperty, value); } } internal static readonly DependencyProperty PercentProperty = DependencyProperty.Register("Percent", typeof(double), typeof(Loading)); #endregion #endregion } }
29.463158
118
0.623794
[ "MIT" ]
sillsun/PanuonUI.Silver
SharedResources/Panuon.UI.Silver/Controls/Loading.cs
2,801
C#
using Forge.Enum; using Forge.Packets; using Forge.Packets.Client.Forge.Handshake; namespace Forge.PacketHandlers.Server.Forge.Handshake { public class HandshakeResetHandler : ForgeMessageHandler<HandshakeResetPacket, ForgeClientPacketHandlerContext> { public override PluginMessageSubPacket Handle(HandshakeResetPacket packet) { Context.State = FMLHandshakeClientState.HELLO; return null; } } }
27
115
0.732026
[ "MIT" ]
MineLib/Forge_1.7.10
PacketHandlers/Server/Forge/Handshake/HandshakeResetHandler.cs
461
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Markup; // 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("NotifyIcon for WPF")] [assembly: AssemblyDescription("NotifyIcon implementation for the WPF platform.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("hardcodet.net")] [assembly: AssemblyProduct("NotifyIcon WPF")] [assembly: AssemblyCopyright("Copyright © Philipp Sumi 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.0.5.0")] [assembly: AssemblyFileVersion("1.0.5.0")] //provides simplified declaration in XAML [assembly: XmlnsPrefix("http://www.hardcodet.net/taskbar", "tb")] [assembly: XmlnsDefinition("http://www.hardcodet.net/taskbar", "Hardcodet.Wpf.TaskbarNotification")] // 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.*")]
38.6
100
0.755281
[ "MIT" ]
Nels-P-Olsen/Summoner
NotifyIconWpf/Properties/AssemblyInfo.cs
2,512
C#
using System.Text.RegularExpressions; /** * CSSastrawi is licensed under The MIT License (MIT) * * Copyright (c) 2017 Muhammad Reza Irvanda * * 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. * */ namespace CSSastrawi.Morphology.Defaultimpl.Visitor.Prefixrules { /** * Disambiguate Prefix Rule 31b. * * Original Rule 31 : penyV -&gt; peny-sV. * * Modified by Confix Stripping, shifted to 31b. */ public class PrefixRule31b : Disambiguator { const string prefixRule = "^peny([aiueo])(.*)$"; public string Disambiguate(string word) { var rule = new Regex(prefixRule, RegexOptions.Compiled); var match = rule.Match(word); if (match.Success) { var groups = match.Groups; return "s" + groups[0].Value + groups[1].Value; } return word; } } }
36.055556
79
0.678993
[ "MIT" ]
muzavan/cssastrawi
CSSastrawi.Source/morphology/defaultimpl/visitor/prefixrules/PrefixRule31b.cs
1,947
C#
namespace RentCar.Services.Mapping { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using AutoMapper; using AutoMapper.Configuration; /// <summary> /// This class configures the Auto Mapper that lets the system use better data controls. /// </summary> public static class AutoMapperConfig { private static bool initialized; public static void RegisterMappings(params Assembly[] assemblies) { if (initialized) { return; } initialized = true; var types = assemblies.SelectMany(a => a.GetExportedTypes()).ToList(); var config = new MapperConfigurationExpression(); config.CreateProfile( "ReflectionProfile", configuration => { // IMapFrom<> foreach (var map in GetFromMaps(types)) { configuration.CreateMap(map.Source, map.Destination); } // IMapTo<> foreach (var map in GetToMaps(types)) { configuration.CreateMap(map.Source, map.Destination); } // IHaveCustomMappings foreach (var map in GetCustomMappings(types)) { map.CreateMappings(configuration); } }); Mapper.Initialize(config); } private static IEnumerable<TypesMap> GetFromMaps(IEnumerable<Type> types) { var fromMaps = from t in types from i in t.GetTypeInfo().GetInterfaces() where i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>) && !t.GetTypeInfo().IsAbstract && !t.GetTypeInfo().IsInterface select new TypesMap { Source = i.GetTypeInfo().GetGenericArguments()[0], Destination = t, }; return fromMaps; } private static IEnumerable<TypesMap> GetToMaps(IEnumerable<Type> types) { var toMaps = from t in types from i in t.GetTypeInfo().GetInterfaces() where i.GetTypeInfo().IsGenericType && i.GetTypeInfo().GetGenericTypeDefinition() == typeof(IMapTo<>) && !t.GetTypeInfo().IsAbstract && !t.GetTypeInfo().IsInterface select new TypesMap { Source = t, Destination = i.GetTypeInfo().GetGenericArguments()[0], }; return toMaps; } private static IEnumerable<IHaveCustomMappings> GetCustomMappings(IEnumerable<Type> types) { var customMaps = from t in types from i in t.GetTypeInfo().GetInterfaces() where typeof(IHaveCustomMappings).GetTypeInfo().IsAssignableFrom(t) && !t.GetTypeInfo().IsAbstract && !t.GetTypeInfo().IsInterface select (IHaveCustomMappings)Activator.CreateInstance(t); return customMaps; } private class TypesMap { public Type Source { get; set; } public Type Destination { get; set; } } } }
40.368421
99
0.469883
[ "MIT" ]
dimitarkole/RentACarManager
Services/RentCar.Services.Mapping/AutoMapperConfig.cs
3,837
C#
namespace nunit.integration.tests.Dsl { using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using System.Xml.XPath; internal class XmlParser { public IEnumerable<IEnumerable<ItemValue>> Parse(string xmlFileName, string xPathExpression) { var doc = XDocument.Load(Path.GetFullPath(xmlFileName)); return from item in doc.XPathSelectElements(xPathExpression) let attributes = from attr in item.Attributes() select new ItemValue(attr.Name.LocalName, attr.Value) select Enumerable.Repeat(new ItemValue(string.Empty, item.Value), 1).Concat(attributes); } } internal class ItemValue { public ItemValue(string name, string value) { Name = name; Value = value; } public string Name { get; private set; } public string Value { get; private set; } } }
28.638889
104
0.595538
[ "MIT" ]
NikolayPianikov/teamcity-event-listener
src/nunit.integration.tests/Dsl/XmlParser.cs
1,033
C#
using System; using System.Collections.Generic; using System.Linq; using Babylon.Investments.Shared.Notifications; using Babylon.Investments.Shared.Specifications.Base; using Babylon.Investments.Shared.Specifications.Interfaces; namespace Babylon.Investments.Shared.Specifications { public class OrSpecification<T> : CompositeSpecification<T> { public OrSpecification( ISpecification<T> firstSpecification, ISpecification<T> secondSpecification) : base(firstSpecification, secondSpecification) { } public OrSpecification( IResultedSpecification<T> firstSpecification, IResultedSpecification<T> secondSpecification) : base(firstSpecification, secondSpecification) { } public OrSpecification(IEnumerable<ISpecification<T>> rulesToValidate) : base(rulesToValidate) { } public OrSpecification(IEnumerable<IResultedSpecification<T>> rulesToValidate) : base(rulesToValidate) { } public override bool IsPrimitiveSatisfiedBy(T entityToEvaluate) { if (!ChildPrimitiveSpecifications.Any()) return true; var rulesResult = ChildPrimitiveSpecifications .Select(rule => rule.IsPrimitiveSatisfiedBy(entityToEvaluate)) .ToList(); return rulesResult.Any(expression => expression); } public override Result IsSatisfiedBy(T domainEntity) { if (!ChildResultSpecifications.Any()) return Result.Ok(); var rulesResult = ChildResultSpecifications .Select(rule => rule.IsSatisfiedBy(domainEntity)) .ToList(); return rulesResult.Any(result => result.IsSuccess) ? Result.Ok() : Result.Failure(rulesResult.SelectMany(x => x.Errors)); } } }
34.2
110
0.60575
[ "MIT" ]
levibrian/ivas-transactions-api
src/Babylon.Investments/Babylon.Investments.Shared/Specifications/OrSpecification.cs
2,054
C#
using Discord; using Discord.Commands; using Discord.WebSocket; using NadekoBot.Services; using NadekoBot.Services.Impl; using NLog; using NLog.Config; using NLog.Targets; using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; using System.Collections.Generic; using NadekoBot.Modules.Permissions; using NadekoBot.TypeReaders; using System.Collections.Concurrent; using NadekoBot.Modules.Music; using NadekoBot.Services.Database.Models; namespace NadekoBot { public class NadekoBot { private Logger _log; public static Color OkColor { get; } public static Color ErrorColor { get; } public static CommandService CommandService { get; private set; } public static CommandHandler CommandHandler { get; private set; } public static DiscordShardedClient Client { get; private set; } public static BotCredentials Credentials { get; private set; } public static GoogleApiService Google { get; private set; } public static StatsService Stats { get; private set; } public static IImagesService Images { get; private set; } public static ConcurrentDictionary<string, string> ModulePrefixes { get; private set; } public static bool Ready { get; private set; } public static IEnumerable<GuildConfig> AllGuildConfigs { get; } public static BotConfig BotConfig { get; } static NadekoBot() { SetupLogger(); Credentials = new BotCredentials(); using (var uow = DbHandler.UnitOfWork()) { AllGuildConfigs = uow.GuildConfigs.GetAllGuildConfigs(); BotConfig = uow.BotConfig.GetOrCreate(); OkColor = new Color(Convert.ToUInt32(BotConfig.OkColor, 16)); ErrorColor = new Color(Convert.ToUInt32(BotConfig.ErrorColor, 16)); } } public async Task RunAsync(params string[] args) { _log = LogManager.GetCurrentClassLogger(); _log.Info("Starting NadekoBot v" + StatsService.BotVersion); //create client Client = new DiscordShardedClient(new DiscordSocketConfig { AudioMode = Discord.Audio.AudioMode.Outgoing, MessageCacheSize = 10, LogLevel = LogSeverity.Warning, TotalShards = Credentials.TotalShards, ConnectionTimeout = int.MaxValue, #if !GLOBAL_NADEKO //AlwaysDownloadUsers = true, #endif }); #if GLOBAL_NADEKO Client.Log += Client_Log; #endif //initialize Services CommandService = new CommandService(new CommandServiceConfig() { CaseSensitiveCommands = false, DefaultRunMode = RunMode.Sync }); Google = new GoogleApiService(); CommandHandler = new CommandHandler(Client, CommandService); Stats = new StatsService(Client, CommandHandler); Images = await ImagesService.Create().ConfigureAwait(false); ////setup DI //var depMap = new DependencyMap(); //depMap.Add<ILocalization>(Localizer); //depMap.Add<ShardedDiscordClient>(Client); //depMap.Add<CommandService>(CommandService); //depMap.Add<IGoogleApiService>(Google); //setup typereaders CommandService.AddTypeReader<PermissionAction>(new PermissionActionTypeReader()); CommandService.AddTypeReader<CommandInfo>(new CommandTypeReader()); CommandService.AddTypeReader<ModuleInfo>(new ModuleTypeReader()); CommandService.AddTypeReader<IGuild>(new GuildTypeReader()); //connect await Client.LoginAsync(TokenType.Bot, Credentials.Token).ConfigureAwait(false); await Client.ConnectAsync().ConfigureAwait(false); //await Client.DownloadAllUsersAsync().ConfigureAwait(false); Stats.Initialize(); _log.Info("Connected"); //load commands and prefixes ModulePrefixes = new ConcurrentDictionary<string, string>(NadekoBot.BotConfig.ModulePrefixes.OrderByDescending(mp => mp.Prefix.Length).ToDictionary(m => m.ModuleName, m => m.Prefix)); // start handling messages received in commandhandler await CommandHandler.StartHandling().ConfigureAwait(false); var _ = await Task.Run(() => CommandService.AddModulesAsync(this.GetType().GetTypeInfo().Assembly)).ConfigureAwait(false); #if !GLOBAL_NADEKO await CommandService.AddModuleAsync<Music>().ConfigureAwait(false); #endif Ready = true; Console.WriteLine(await Stats.Print().ConfigureAwait(false)); } private Task Client_Log(LogMessage arg) { _log.Warn(arg.Source + " | " + arg.Message); if (arg.Exception != null) _log.Warn(arg.Exception); return Task.CompletedTask; } public async Task RunAndBlockAsync(params string[] args) { await RunAsync(args).ConfigureAwait(false); await Task.Delay(-1).ConfigureAwait(false); } private static void SetupLogger() { try { var logConfig = new LoggingConfiguration(); var consoleTarget = new ColoredConsoleTarget(); consoleTarget.Layout = @"${date:format=HH\:mm\:ss} ${logger} | ${message}"; logConfig.AddTarget("Console", consoleTarget); logConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget)); LogManager.Configuration = logConfig; } catch (Exception ex) { Console.WriteLine(ex); } } } }
35.674699
195
0.620567
[ "Unlicense" ]
justinkruit/DiscordBot
src/NadekoBot/NadekoBot.cs
5,924
C#
using System.Collections.ObjectModel; using System.Diagnostics; using Octokit.Internal; using System; using System.Collections.Generic; using System.Linq; using System.Globalization; using System.Diagnostics.CodeAnalysis; namespace Octokit { /// <summary> /// Searching Issues /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public class SearchIssuesRequest : BaseSearchRequest { public SearchIssuesRequest(string term) : base(term) { } public SearchIssuesRequest(string term, string owner, string name) : this(term) { Ensure.ArgumentNotNullOrEmptyString(owner, "owner"); Ensure.ArgumentNotNullOrEmptyString(name, "name"); this.Repo = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", owner, name); } /// <summary> /// Optional Sort field. One of comments, created, or updated. /// If not provided, results are sorted by best match. /// </summary> /// <remarks> /// http://developer.github.com/v3/search/#search-issues /// </remarks> public IssueSearchSort? SortField { get; set; } public override string Sort { get { return SortField.ToParameter(); } } /// <summary> /// Qualifies which fields are searched. With this qualifier you can restrict /// the search to just the title, body, comments, or any combination of these. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#search-in /// </remarks> private IEnumerable<IssueInQualifier> _inQualifier; public IEnumerable<IssueInQualifier> In { get { return _inQualifier; } set { if (value != null && value.Any()) { _inQualifier = value.Distinct().ToList(); } } } /// <summary> /// With this qualifier you can restrict the search to issues or pull request only. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#type /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public IssueTypeQualifier? Type { get; set; } /// <summary> /// Finds issues created by a certain user. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#author /// </remarks> public string Author { get; set; } /// <summary> /// Finds issues that are assigned to a certain user. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#assignee /// </remarks> public string Assignee { get; set; } /// <summary> /// Finds issues that mention a certain user. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#mentions /// </remarks> public string Mentions { get; set; } /// <summary> /// Finds issues that a certain user commented on. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#commenter /// </remarks> public string Commenter { get; set; } /// <summary> /// Finds issues that were either created by a certain user, assigned to that user, /// mention that user, or were commented on by that user. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#involves /// </remarks> public string Involves { get; set; } /// <summary> /// Filter issues based on whether they’re open or closed. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#state /// </remarks> public ItemState? State { get; set; } private IEnumerable<string> _labels; /// <summary> /// Filters issues based on their labels. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#labels /// </remarks> public IEnumerable<string> Labels { get { return _labels; } set { if (value != null && value.Any()) { _labels = value.Distinct().ToList(); } } } /// <summary> /// Searches for issues within repositories that match a certain language. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#language /// </remarks> public Language? Language { get; set; } /// <summary> /// Filters issues based on times of creation. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#created-and-last-updated /// </remarks> public DateRange Created { get; set; } /// <summary> /// Filters issues based on times when they were last updated. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#created-and-last-updated /// </remarks> public DateRange Updated { get; set; } /// <summary> /// Filters issues based on the quantity of comments. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#comments /// </remarks> public Range Comments { get; set; } /// <summary> /// Limits searches to a specific user. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#users-organizations-and-repositories /// </remarks> public string User { get; set; } /// <summary> /// Limits searches to a specific repository. /// </summary> /// <remarks> /// https://help.github.com/articles/searching-issues#users-organizations-and-repositories /// </remarks> public string Repo { get; set; } public override IReadOnlyList<string> MergedQualifiers() { var parameters = new List<string>(); if (In != null) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "in:{0}", String.Join(",", In.Select(i => i.ToParameter())))); } if (Type != null) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "type:{0}", Type.ToParameter())); } if (Author.IsNotBlank()) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "author:{0}", Author)); } if (Assignee.IsNotBlank()) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "assignee:{0}", Assignee)); } if (Mentions.IsNotBlank()) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "mentions:{0}", Mentions)); } if (Commenter.IsNotBlank()) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "commenter:{0}", Commenter)); } if (Involves.IsNotBlank()) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "involves:{0}", Involves)); } if (State.HasValue) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "state:{0}", State.Value.ToParameter())); } if (Labels != null) { foreach (var label in Labels) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "label:{0}", label)); } } if (Language != null) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "language:{0}", Language)); } if (Created != null) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "created:{0}", Created)); } if (Updated != null) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "updated:{0}", Updated)); } if (Comments != null) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "comments:{0}", Comments)); } if (User.IsNotBlank()) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "user:{0}", User)); } if (Repo.IsNotBlank()) { parameters.Add(String.Format(CultureInfo.InvariantCulture, "repo:{0}", Repo)); } return new ReadOnlyCollection<string>(parameters); } internal string DebuggerDisplay { get { return String.Format(CultureInfo.InvariantCulture, "Term: {0}", Term); } } } public enum IssueSearchSort { /// <summary> /// search by number of comments /// </summary> [Parameter(Value = "comments")] Comments, /// <summary> /// search by created /// </summary> [Parameter(Value = "created")] Created, /// <summary> /// search by last updated /// </summary> [Parameter(Value = "updated")] Updated } public enum IssueInQualifier { [Parameter(Value = "title")] Title, [Parameter(Value = "body")] Body, [Parameter(Value = "comment")] Comment } public enum IssueTypeQualifier { [Parameter(Value = "pr")] PR, [Parameter(Value = "issue")] Issue } }
31.663551
116
0.526958
[ "MIT" ]
darrelmiller/octokit.net
Octokit/Models/Request/SearchIssuesRequest.cs
10,168
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities.Editor; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using UnityEditor; using UnityEditor.Build.Reporting; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Build.Editor { /// <summary> /// Class containing various utility methods to build a WSA solution from a Unity project. /// </summary> public static class UwpPlayerBuildTools { private static void ParseBuildCommandLine(ref UwpBuildInfo buildInfo) { IBuildInfo iBuildInfo = buildInfo; UnityPlayerBuildTools.ParseBuildCommandLine(ref iBuildInfo); string[] arguments = Environment.GetCommandLineArgs(); for (int i = 0; i < arguments.Length; ++i) { switch (arguments[i]) { case "-buildAppx": buildInfo.BuildAppx = true; break; case "-rebuildAppx": buildInfo.RebuildAppx = true; break; case "-targetUwpSdk": // Note: the min sdk target cannot be changed. EditorUserBuildSettings.wsaUWPSDK = arguments[++i]; break; } } } /// <summary> /// Do a build configured for UWP Applications to the specified path, returns the error from <see cref="BuildPlayer(UwpBuildInfo, CancellationToken)"/> /// </summary> /// <param name="buildDirectory"></param> /// <param name="showDialog">Should the user be prompted to build the appx as well?</param> /// <param name="cancellationToken"></param> /// <returns>True, if build was successful.</returns> public static async Task<bool> BuildPlayer(string buildDirectory, bool showDialog = true, CancellationToken cancellationToken = default) { if (UnityPlayerBuildTools.CheckBuildScenes() == false) { return false; } var buildInfo = new UwpBuildInfo { OutputDirectory = buildDirectory, Scenes = EditorBuildSettings.scenes.Where(scene => scene.enabled && !string.IsNullOrEmpty(scene.path)).Select(scene => scene.path), BuildAppx = !showDialog, BuildPlatform = EditorUserBuildSettings.wsaArchitecture, GazeInputCapabilityEnabled = UwpBuildDeployPreferences.GazeInputCapabilityEnabled, // Configure a post build action that will compile the generated solution PostBuildAction = PostBuildAction }; async void PostBuildAction(IBuildInfo innerBuildInfo, BuildReport buildReport) { if (buildReport.summary.result != BuildResult.Succeeded) { EditorUtility.DisplayDialog($"{PlayerSettings.productName} WindowsStoreApp Build {buildReport.summary.result}!", "See console for details", "OK"); } else { var uwpBuildInfo = innerBuildInfo as UwpBuildInfo; Debug.Assert(uwpBuildInfo != null); if (uwpBuildInfo.GazeInputCapabilityEnabled) { UwpAppxBuildTools.AddGazeInputCapability(uwpBuildInfo); } if (showDialog && !EditorUtility.DisplayDialog(PlayerSettings.productName, "Build Complete", "OK", "Build AppX")) { EditorAssemblyReloadManager.LockReloadAssemblies = true; await UwpAppxBuildTools.BuildAppxAsync(uwpBuildInfo, cancellationToken); EditorAssemblyReloadManager.LockReloadAssemblies = false; } } } return await BuildPlayer(buildInfo, cancellationToken); } /// <summary> /// Build the Uwp Player. /// </summary> /// <param name="buildInfo"></param> /// <param name="cancellationToken"></param> public static async Task<bool> BuildPlayer(UwpBuildInfo buildInfo, CancellationToken cancellationToken = default) { #region Gather Build Data if (buildInfo.IsCommandLine) { ParseBuildCommandLine(ref buildInfo); } #endregion Gather Build Data BuildReport buildReport = UnityPlayerBuildTools.BuildUnityPlayer(buildInfo); bool success = buildReport != null && buildReport.summary.result == BuildResult.Succeeded; if (success && buildInfo.BuildAppx) { success &= await UwpAppxBuildTools.BuildAppxAsync(buildInfo, cancellationToken); } return success; } } }
40.328125
166
0.576908
[ "MIT" ]
ActiveNick/HoloBot
Assets/MixedRealityToolkit/Utilities/BuildAndDeploy/UwpPlayerBuildTools.cs
5,162
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/ocidl.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop.Windows; /// <include file='CTRLINFO.xml' path='doc/member[@name="CTRLINFO"]/*' /> public enum CTRLINFO { /// <include file='CTRLINFO.xml' path='doc/member[@name="CTRLINFO.CTRLINFO_EATS_RETURN"]/*' /> CTRLINFO_EATS_RETURN = 1, /// <include file='CTRLINFO.xml' path='doc/member[@name="CTRLINFO.CTRLINFO_EATS_ESCAPE"]/*' /> CTRLINFO_EATS_ESCAPE = 2, }
39.882353
145
0.721239
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
sources/Interop/Windows/Windows/um/ocidl/CTRLINFO.cs
680
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.832 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace NTICS_KEY_MANAGER.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.592593
150
0.582788
[ "MIT" ]
sabatex/URDBTool
NTICS/NTICS_KEY_MANAGER/Properties/Settings.Designer.cs
1,071
C#
using System; using System.Collections.Generic; using System.Text; using FlubuCore.Context; using FlubuCore.Tasks; using FlubuCore.Tasks.Process; namespace FlubuCore.Azure.Tasks.Batch { public partial class AzureBatchJobTask : ExternalProcessTaskBase<AzureBatchJobTask> { /// <summary> /// Manage Batch jobs. /// </summary> public AzureBatchJobTask() { WithArguments("az batch job"); } protected override string Description { get; set; } } }
21
88
0.630037
[ "MIT" ]
flubu-core/FlubuCore.Azure
FlubuCore.Azure/Tasks/Batch/AzureBatchJobTask.cs
546
C#
// --------------------------------------------------------------------------------------------- #region // Copyright (c) 2005-2015, SIL International. // <copyright from='2005' to='2015' company='SIL International'> // Copyright (c) 2005-2015, SIL International. // // This software is distributed under the MIT License, as specified in the LICENSE.txt file. // </copyright> #endregion // using System; using System.Collections.Generic; namespace SIL.PaToFdoInterfaces { #region IPaLexEntry interface /// ---------------------------------------------------------------------------------------- public interface IPaLexEntry { /// ------------------------------------------------------------------------------------ IPaMultiString LexemeForm { get; } /// ------------------------------------------------------------------------------------ IEnumerable<IPaLexPronunciation> Pronunciations { get; } /// ------------------------------------------------------------------------------------ IEnumerable<IPaLexSense> Senses { get; } /// ------------------------------------------------------------------------------------ bool ExcludeAsHeadword { get; } /// ------------------------------------------------------------------------------------ string ImportResidue { get; } /// ------------------------------------------------------------------------------------ DateTime DateCreated { get; } /// ------------------------------------------------------------------------------------ DateTime DateModified { get; } /// ------------------------------------------------------------------------------------ IPaCmPossibility MorphType { get; } /// ------------------------------------------------------------------------------------ IPaMultiString CitationForm { get; } /// ------------------------------------------------------------------------------------ IPaMultiString SummaryDefinition { get; } /// ------------------------------------------------------------------------------------ IPaMultiString Etymology { get; } /// ------------------------------------------------------------------------------------ IPaMultiString Note { get; } /// ------------------------------------------------------------------------------------ IPaMultiString LiteralMeaning { get; } /// ------------------------------------------------------------------------------------ IPaMultiString Bibliography { get; } /// ------------------------------------------------------------------------------------ IPaMultiString Restrictions { get; } /// ------------------------------------------------------------------------------------ IEnumerable<IPaMultiString> Allomorphs { get; } /// ------------------------------------------------------------------------------------ IEnumerable<IPaMultiString> ComplexForms { get; } /// ------------------------------------------------------------------------------------ IEnumerable<IPaComplexFormInfo> ComplexFormInfo { get; } /// ------------------------------------------------------------------------------------ IEnumerable<IPaVariant> Variants { get; } /// ------------------------------------------------------------------------------------ IEnumerable<IPaVariantOfInfo> VariantOfInfo { get; } /// ------------------------------------------------------------------------------------ Guid Guid { get; } } #endregion }
41.564706
97
0.275969
[ "MIT" ]
sillsdev/phonology-assistant
src/PaToFdoInterfaces/IPaLexEntry.cs
3,533
C#