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.Text; using System.Threading.Tasks; namespace suporteZ { /// <summary> /// <para>Classe usada para disparar exceções conhecidas na execução dos comandos.</para> /// </summary> public class ComandoException: Exception { /// <summary> /// <para>Lista de sinalização possível que determinará o comportamento do tratador de exceções.</para> /// </summary> public enum ListaParaSinal { /// <summary> /// <para>Sinaliza finalização por causa de erros do aplicativo.</para> /// </summary> FinalizarComErroDoAplicativo = 1, /// <summary> /// <para>Sinaliza finalização por causa de erros da biblioteca.</para> /// </summary> FinalizarComErroDaBiblioteca = 1, /// <summary> /// <para>Sinaliza finalização com sucesso, sem erros.</para> /// </summary> FinalizarComSucesso = 2 } /// <summary> /// <para>Sinal recebido com esta instância de exceção.</para> /// </summary> public ListaParaSinal Sinal { get; private set; } /// <summary> /// <para>Construtor.</para> /// </summary> /// <param name="sinal"><para>Sinalização do tipo de exceção.</para></param> public ComandoException(ListaParaSinal sinal) : this(sinal, string.Empty) { } /// <summary> /// <para>Construtor.</para> /// </summary> /// <param name="sinal"><para>Sinalização do tipo de exceção.</para></param> /// <param name="mensagem"><para>Mensagem do erro para o usuário.</para></param> public ComandoException(ListaParaSinal sinal, string mensagem) : base(mensagem) { Sinal = sinal; } } }
32.844828
111
0.570604
[ "MIT" ]
sergiocabral/App.Suporte-Z
src/suporte-z/ComandoException.cs
1,935
C#
using System; using NQuery.Text; namespace NQuery { public struct SyntaxNodeOrToken { private readonly SyntaxNode _syntaxNode; private readonly SyntaxToken _syntaxToken; internal SyntaxNodeOrToken(SyntaxToken syntaxToken) { _syntaxToken = syntaxToken; _syntaxNode = null; } internal SyntaxNodeOrToken(SyntaxNode syntaxNode) { _syntaxToken = null; _syntaxNode = syntaxNode; } public bool IsToken => !IsNode; public bool IsNode => _syntaxNode != null; public SyntaxToken AsToken() { return _syntaxToken; } public SyntaxNode AsNode() { return _syntaxNode; } public bool IsEquivalentTo(SyntaxNodeOrToken other) { return SyntaxTreeEquivalence.AreEquivalent(this, other); } public SyntaxNode Parent => IsNode ? AsNode().Parent : AsToken().Parent; public SyntaxTree SyntaxTree => Parent.SyntaxTree; public SyntaxKind Kind => IsNode ? AsNode().Kind : AsToken().Kind; public TextSpan Span => IsNode ? AsNode().Span : AsToken().Span; public TextSpan FullSpan => IsNode ? AsNode().FullSpan : AsToken().FullSpan; public bool IsMissing => IsNode ? AsNode().IsMissing : AsToken().IsMissing; public static implicit operator SyntaxNodeOrToken(SyntaxToken syntaxToken) { return new SyntaxNodeOrToken(syntaxToken); } public static implicit operator SyntaxNodeOrToken(SyntaxNode syntaxNode) { return new SyntaxNodeOrToken(syntaxNode); } } }
26.246154
84
0.61313
[ "MIT" ]
dallmair/nquery-vnext
src/NQuery/SyntaxNodeOrToken.cs
1,706
C#
using MLStudy; using System; using System.Collections.Generic; using System.Text; using NumSharp; namespace PlayGround.Plays { public class Performance : IPlay { public void Play() { var data = DataEmulator.Instance.RandomArray(200000); var t1 = new TensorOld(data, 500, 400); var t2 = new TensorOld(data, 400, 500); var tResult = new TensorOld(new double[250000], 500, 500); var a1 = new double[500, 400]; var a2 = new double[400, 500]; var result = new double[500, 500]; var rand = new Random(); for (int i = 0; i < 500; i++) { for (int j = 0; j < 400; j++) { a1[i, j] = rand.NextDouble(); a2[j, i] = rand.NextDouble(); } } var np = new NumSharp.Core.NumPy<double>(); var arr1 = np.array(data).reshape(500, 400); var arr2 = np.array(data).reshape(400, 500); var arr3 = np.array(new double[250000]).reshape(500, 500); var arrResult = np.array(new double[250000]).reshape(500, 500); var fast1 = Array.CreateInstance(typeof(double), 500, 400); var fast2 = Array.CreateInstance(typeof(double), 400, 500); var fastResult = Array.CreateInstance(typeof(double), 500, 500); for (int i = 0; i < 500; i++) { for (int j = 0; j < 400; j++) { fast1.SetValue(rand.NextDouble(), i, j); fast2.SetValue(rand.NextDouble(), j, i); } } var sum = 0d; var start1 = DateTime.Now; for (int i = 0; i < 500; i++) { for (int j = 0; j < 500; j++) { sum = 0d; for (int k = 0; k < 400; k++) { sum += a1[i, k] * a2[k, j]; } result[i, j] = sum; } } var start3 = DateTime.Now; for (int i = 0; i < 500; i++) { for (int j = 0; j < 500; j++) { sum = 0d; for (int k = 0; k < 400; k++) { sum += arr1[i, k] * arr2[k, j]; } arrResult[i, j] = sum; } } var ts3 = DateTime.Now - start3; Console.WriteLine($"NDArry Time:{ts3.TotalMilliseconds} ms"); var start4 = DateTime.Now; //for (int i = 0; i < 500; i++) //{ // for (int j = 0; j < 500; j++) // { // sum = 0d; // for (int k = 0; k < 400; k++) // { // sum += t1.GetValueFast(i, k) * t2.GetValueFast(k, j); // } // tResult.SetValueFast(sum, i, j); // } //} TensorOld.Multiple(t1, t2, tResult); var ts4 = DateTime.Now - start4; Console.WriteLine($"Tensor Time:{ts4.TotalMilliseconds} ms"); var tens = new TensTest(); var start5 = DateTime.Now; tens.Multi(); var ts5 = DateTime.Now - start5; Console.WriteLine($"Tens Time:{ts5.TotalMilliseconds} ms"); } } public class TensTest { public double[,] a1 { get; set; } public double[,] a2 { get; set; } public double[,] result { get; set; } public double this[int index] { get { return 0.123; } } public TensTest() { a1 = new double[500, 400]; a2 = new double[400, 500]; result = new double[500, 500]; var rand = new Random(); for (int i = 0; i < 500; i++) { for (int j = 0; j < 400; j++) { a1[i, j] = rand.NextDouble(); a2[j, i] = rand.NextDouble(); } } result = new double[500, 500]; } public void Multi() { var sum = 0d; for (int i = 0; i < 500; i++) { for (int j = 0; j < 500; j++) { for (int k = 0; k < 400; k++) { sum += a1[i, k] * a2[k, j]; } result[i, j] = sum; } } } } }
30.461538
79
0.379209
[ "Apache-2.0" ]
durow/MLSharp
PlayGround/Plays/Performance.cs
4,754
C#
using System; using System.Collections.Generic; using System.Text; using Imml.ComponentModel; using Imml.Numerics; namespace Imml.Scene.Layout { /// <summary> /// Defines uniformly sized cells for placement of elements. /// </summary> /// <remarks>An undefined grid defaults to a size of 1,1,1 with 1 row, column and layer. Child elements added to the grid are limited in maximum size to the size of the cell they occupy. New elements are added to the next available cell in a column, row, layer order.</remarks> public class Grid : VisibleElement { #region Properties /// <summary> /// Gets or sets the rows. /// </summary> /// <value> /// The rows. /// </value> /// <remarks>The number of horizontal segments to divide the grid into</remarks> public virtual int Rows { get; set; } /// <summary> /// Gets or sets the columns. /// </summary> /// <value> /// The columns. /// </value> /// <remarks>The number of vertical segments to divide the grid into</remarks> public virtual int Columns { get; set; } /// <summary> /// Gets or sets the layers. /// </summary> /// <value> /// The layers. /// </value> /// <remarks>The number of depth segments to divide the grid into</remarks> public virtual int Layers { get; set; } protected Vector3 _Size; /// <summary> /// Gets or sets the size. /// </summary> /// <value> /// The size. /// </value> public virtual Vector3 Size { get { return _Size; } set { if (_Size.X == value.X && _Size.Y == value.Y && _Size.Z == value.Z) return; Vector3 oldValue = _Size; _Size = value; base.RaisePropertyChanged("Size", oldValue, _Size); } } #endregion /// <summary> /// Initializes a new instance of the <see cref="Grid"/> class. /// </summary> public Grid() { this.Rows = 1; this.Columns = 1; this.Layers = 1; this.Size = new Vector3(1, 1, 1); } } }
29.923077
281
0.517995
[ "MIT" ]
craigomatic/IMML
src/Imml/Scene/Layout/Grid.cs
2,334
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ECharts.Entities { public class GaugePointer { public object length { get; set; } public int? width { get; set; } public object color { get; set; } public int? shadowBlur { get; set; } public object shadowColor { get; set; } public GaugePointer ShadowBlur(int shadowBlur) { this.shadowBlur = shadowBlur; return this; } public GaugePointer ShadowColor(object shadowColor) { this.shadowColor = shadowColor; return this; } public GaugePointer Color(object color) { this.color = color; return this; } public GaugePointer Length(object length) { this.length = length; return this; } public GaugePointer Width(int width) { this.width = width; return this; } } }
20.428571
60
0.520105
[ "MIT" ]
15110217966/echartsSDK
EChartsSDK/ECharts/Entities/series/guage/GaugePointer.cs
1,146
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SnippetStudio.ClientBase.Localisation { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class CommonLoc { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal CommonLoc() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SnippetStudio.ClientBase.Localisation.CommonLoc", typeof(CommonLoc).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Cancel. /// </summary> public static string Cancel { get { return ResourceManager.GetString("Cancel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Delete. /// </summary> public static string Delete { get { return ResourceManager.GetString("Delete", resourceCulture); } } /// <summary> /// Looks up a localized string similar to New. /// </summary> public static string New { get { return ResourceManager.GetString("New", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No. /// </summary> public static string No { get { return ResourceManager.GetString("No", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Ok. /// </summary> public static string Ok { get { return ResourceManager.GetString("Ok", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Refresh. /// </summary> public static string Refresh { get { return ResourceManager.GetString("Refresh", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Save. /// </summary> public static string Save { get { return ResourceManager.GetString("Save", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Yes. /// </summary> public static string Yes { get { return ResourceManager.GetString("Yes", resourceCulture); } } } }
36.330882
192
0.55171
[ "MIT" ]
najlot/SnippetStudio
src/SnippetStudio.ClientBase/Localisation/CommonLoc.Designer.cs
4,943
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("aula09")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("aula09")] [assembly: System.Reflection.AssemblyTitleAttribute("aula09")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.416667
80
0.643299
[ "MIT" ]
jonatasvnascimento/CsharpCFB
Aulas/aula09/obj/Release/net5.0/aula09.AssemblyInfo.cs
970
C#
using System; using System.Reflection; using System.Text; using Abp.AspNetCore; using Abp.AspNetCore.Configuration; using Abp.Modules; using Abp.Reflection.Extensions; using Abp.Zero.Configuration; using Acme.PhoneBook.Authentication.JwtBearer; using Acme.PhoneBook.Configuration; using Acme.PhoneBook.EntityFrameworkCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; #if FEATURE_SIGNALR using Abp.Web.SignalR; #endif namespace Acme.PhoneBook { [DependsOn( typeof(PhoneBookApplicationModule), typeof(PhoneBookEntityFrameworkModule), typeof(AbpAspNetCoreModule) #if FEATURE_SIGNALR ,typeof(AbpWebSignalRModule) #endif )] public class PhoneBookWebCoreModule : AbpModule { private readonly IHostingEnvironment _env; private readonly IConfigurationRoot _appConfiguration; public PhoneBookWebCoreModule(IHostingEnvironment env) { _env = env; _appConfiguration = env.GetAppConfiguration(); } public override void PreInitialize() { Configuration.DefaultNameOrConnectionString = _appConfiguration.GetConnectionString( PhoneBookConsts.ConnectionStringName ); //Use database for language management Configuration.Modules.Zero().LanguageManagement.EnableDbLocalization(); Configuration.Modules.AbpAspNetCore() .CreateControllersForAppServices( typeof(PhoneBookApplicationModule).GetAssembly() ); ConfigureTokenAuth(); } private void ConfigureTokenAuth() { IocManager.Register<TokenAuthConfiguration>(); var tokenAuthConfig = IocManager.Resolve<TokenAuthConfiguration>(); tokenAuthConfig.SecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_appConfiguration["Authentication:JwtBearer:SecurityKey"])); tokenAuthConfig.Issuer = _appConfiguration["Authentication:JwtBearer:Issuer"]; tokenAuthConfig.Audience = _appConfiguration["Authentication:JwtBearer:Audience"]; tokenAuthConfig.SigningCredentials = new SigningCredentials(tokenAuthConfig.SecurityKey, SecurityAlgorithms.HmacSha256); tokenAuthConfig.Expiration = TimeSpan.FromDays(1); } public override void Initialize() { IocManager.RegisterAssemblyByConvention(typeof(PhoneBookWebCoreModule).GetAssembly()); } } }
33.934211
151
0.703373
[ "MIT" ]
Jimmey-Jiang/aspnetboilerplate-samples
StoredProcedureDemo/src/Acme.PhoneBook.Web.Core/PhoneBookWebCoreModule.cs
2,581
C#
using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.ExtensionsAPI.Tree; namespace JetBrains.ReSharper.Plugins.Json.Psi.Tree.Impl { public abstract class JsonNewFileElement : FileElementBase, IJsonNewTreeNode { public override PsiLanguageType Language => JsonNewLanguage.Instance; public abstract void Accept(TreeNodeVisitor visitor); public abstract void Accept<TContext>(TreeNodeVisitor<TContext> visitor, TContext context); public abstract TReturn Accept<TContext, TReturn>(TreeNodeVisitor<TContext, TReturn> visitor, TContext context); } }
42.642857
120
0.775544
[ "Apache-2.0" ]
SirDuke/resharper-unity
resharper/resharper-json/src/Json/Psi/Tree/Impl/JsonNewFileElement.cs
597
C#
using System; #if WISEJ using Wisej.Web; #else using System.Windows.Forms; #endif using MvvmFx.CaliburnMicro; using SimpleParameters.UI.ViewModels; namespace SimpleParameters.UI.Views { public partial class MenuStripView : UserControl, IHaveDataContext { public MenuStripView() { InitializeComponent(); } #region IHaveDataContext implementation public event EventHandler<DataContextChangedEventArgs> DataContextChanged = delegate { }; private MenuStripViewModel _viewModel; public object DataContext { get { return _viewModel; } set { if (value != _viewModel) { _viewModel = value as MenuStripViewModel; DataContextChanged(this, new DataContextChangedEventArgs()); } } } #endregion } }
23.3
97
0.593348
[ "MIT" ]
MvvmFx/MvvmFx
Samples/CaliburnMicro/SimpleParameters.WinForms/Views/MenuStripView.cs
934
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis.Formatting { internal partial class TokenStream { // gain of having hand written iterator seems about 50-100ms over auto generated one. // not sure whether it is worth it. but I already wrote it to test, so going to just keep it. private class Iterator : IEnumerable<(int index, SyntaxToken currentToken, SyntaxToken nextToken)> { private readonly SegmentedList<SyntaxToken> _tokensIncludingZeroWidth; public Iterator(SegmentedList<SyntaxToken> tokensIncludingZeroWidth) => _tokensIncludingZeroWidth = tokensIncludingZeroWidth; public IEnumerator<(int index, SyntaxToken currentToken, SyntaxToken nextToken)> GetEnumerator() => new Enumerator(_tokensIncludingZeroWidth); System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); private struct Enumerator : IEnumerator<(int index, SyntaxToken currentToken, SyntaxToken nextToken)> { private readonly SegmentedList<SyntaxToken> _tokensIncludingZeroWidth; private readonly int _maxCount; private (int index, SyntaxToken currentToken, SyntaxToken nextToken) _current; private int _index; public Enumerator(SegmentedList<SyntaxToken> tokensIncludingZeroWidth) { _tokensIncludingZeroWidth = tokensIncludingZeroWidth; _maxCount = _tokensIncludingZeroWidth.Count - 1; _index = 0; _current = default; } public void Dispose() { } public bool MoveNext() { if (_index < _maxCount) { _current = (_index, _tokensIncludingZeroWidth[_index], _tokensIncludingZeroWidth[_index + 1]); _index++; return true; } return MoveNextRare(); } private bool MoveNextRare() { _index = _maxCount + 1; _current = default; return false; } public (int index, SyntaxToken currentToken, SyntaxToken nextToken) Current => _current; object System.Collections.IEnumerator.Current { get { if (_index == 0 || _index == _maxCount + 1) { throw new InvalidOperationException(); } return Current; } } void System.Collections.IEnumerator.Reset() { _index = 0; _current = new ValueTuple<int, SyntaxToken, SyntaxToken>(); } } } } }
36.815217
118
0.542073
[ "MIT" ]
333fred/roslyn
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/TokenStream.Iterator.cs
3,389
C#
using System.Linq; using Microsoft.EntityFrameworkCore; using Abp.Authorization; using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.MultiTenancy; using Exceed.Authorization; using Exceed.Authorization.Roles; using Exceed.Authorization.Users; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; namespace Exceed.EntityFrameworkCore.Seed.Host { public class HostRoleAndUserCreator { private readonly ExceedDbContext _context; public HostRoleAndUserCreator(ExceedDbContext context) { _context = context; } public void Create() { CreateHostRoleAndUsers(); } private void CreateHostRoleAndUsers() { // Admin role for host var adminRoleForHost = _context.Roles.IgnoreQueryFilters().FirstOrDefault(r => r.TenantId == null && r.Name == StaticRoleNames.Host.Admin); if (adminRoleForHost == null) { adminRoleForHost = _context.Roles.Add(new Role(null, StaticRoleNames.Host.Admin, StaticRoleNames.Host.Admin) { IsStatic = true, IsDefault = true }).Entity; _context.SaveChanges(); } // Grant all permissions to admin role for host var grantedPermissions = _context.Permissions.IgnoreQueryFilters() .OfType<RolePermissionSetting>() .Where(p => p.TenantId == null && p.RoleId == adminRoleForHost.Id) .Select(p => p.Name) .ToList(); var permissions = PermissionFinder .GetAllPermissions(new ExceedAuthorizationProvider()) .Where(p => p.MultiTenancySides.HasFlag(MultiTenancySides.Host) && !grantedPermissions.Contains(p.Name)) .ToList(); if (permissions.Any()) { _context.Permissions.AddRange( permissions.Select(permission => new RolePermissionSetting { TenantId = null, Name = permission.Name, IsGranted = true, RoleId = adminRoleForHost.Id }) ); _context.SaveChanges(); } // Admin user for host var adminUserForHost = _context.Users.IgnoreQueryFilters().FirstOrDefault(u => u.TenantId == null && u.UserName == AbpUserBase.AdminUserName); if (adminUserForHost == null) { var user = new User { TenantId = null, UserName = AbpUserBase.AdminUserName, Name = "admin", Surname = "admin", EmailAddress = "admin@aspnetboilerplate.com", IsEmailConfirmed = true, IsActive = true }; user.Password = new PasswordHasher<User>(new OptionsWrapper<PasswordHasherOptions>(new PasswordHasherOptions())).HashPassword(user, "123qwe"); user.SetNormalizedNames(); adminUserForHost = _context.Users.Add(user).Entity; _context.SaveChanges(); // Assign Admin role to admin user _context.UserRoles.Add(new UserRole(null, adminUserForHost.Id, adminRoleForHost.Id)); _context.SaveChanges(); _context.SaveChanges(); } } } }
35.757576
171
0.560169
[ "MIT" ]
yiershan/Excced
aspnet-core/src/Exceed.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/HostRoleAndUserCreator.cs
3,540
C#
using System; namespace Chloe.Infrastructure { /// <summary> /// 数据库数据转换器。 /// </summary> public interface IDbValueConverter { /// <summary> /// 从数据库读取数据时,当表字段类型与实体属性类型不一致时调用。 /// </summary> /// <param name="value"></param> /// <returns></returns> object Convert(object value); } public class DbValueConverter : IDbValueConverter { Type _type; public DbValueConverter(Type type) { this._type = type; } public virtual object Convert(object value) { return System.Convert.ChangeType(value, this._type); } } public class DbValueConverter<T> : DbValueConverter, IDbValueConverter { public DbValueConverter() : base(typeof(T)) { } } internal class InternalDbValueConverter : IDbValueConverter { Func<object, object> _converter; public InternalDbValueConverter(Func<object, object> converter) { this._converter = converter; } public object Convert(object value) { return this._converter(value); } } public class Byte_ValueConverter : DbValueConverter<Byte> { public override object Convert(object value) { return System.Convert.ToByte(value); } } public class SByte_ValueConverter : DbValueConverter<SByte> { public override object Convert(object value) { return System.Convert.ToSByte(value); } } public class Int16_ValueConverter : DbValueConverter<Int16> { public override object Convert(object value) { return System.Convert.ToInt16(value); } } public class UInt16_ValueConverter : DbValueConverter<UInt16> { public override object Convert(object value) { return System.Convert.ToUInt16(value); } } public class Int32_ValueConverter : DbValueConverter<Int32> { public override object Convert(object value) { return System.Convert.ToInt32(value); } } public class UInt32_ValueConverter : DbValueConverter<UInt32> { public override object Convert(object value) { return System.Convert.ToUInt32(value); } } public class Int64_ValueConverter : DbValueConverter<Int64> { public override object Convert(object value) { return System.Convert.ToInt64(value); } } public class UInt64_ValueConverter : DbValueConverter<UInt64> { public override object Convert(object value) { return System.Convert.ToUInt64(value); } } public class Single_ValueConverter : DbValueConverter<Single> { public override object Convert(object value) { return System.Convert.ToSingle(value); } } public class Double_ValueConverter : DbValueConverter<Double> { public override object Convert(object value) { return System.Convert.ToDouble(value); } } public class Decimal_ValueConverter : DbValueConverter<Decimal> { public override object Convert(object value) { return System.Convert.ToDecimal(value); } } public class Boolean_ValueConverter : DbValueConverter<Boolean> { public override object Convert(object value) { return System.Convert.ToBoolean(value); } } public class String_ValueConverter : DbValueConverter<String> { public override object Convert(object value) { return System.Convert.ToString(value); } } public class Guid_ValueConverter : DbValueConverter<Guid> { public override object Convert(object value) { Type valueType = value.GetType(); if (valueType == typeof(string)) return Guid.Parse((string)value); if (valueType == typeof(byte[])) return new Guid((byte[])value); return base.Convert(value); } } public class DateTime_ValueConverter : DbValueConverter<DateTime> { public override object Convert(object value) { return System.Convert.ToDateTime(value); } } public class DateTimeOffset_ValueConverter : DbValueConverter<DateTimeOffset> { public override object Convert(object value) { return base.Convert(value); } } public class TimeSpan_ValueConverter : DbValueConverter<TimeSpan> { public override object Convert(object value) { return base.Convert(value); } } public class Binary_ValueConverter : DbValueConverter<DateTimeOffset> { public override object Convert(object value) { return base.Convert(value); } } }
27.67033
81
0.596108
[ "MIT" ]
johnnyleecn/Chloe
src/Chloe/Infrastructure/IDbValueConverter.cs
5,116
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum RoadType { Straight, Curved, Ramp, Hill, Split, End, Pickup } [System.Serializable] public class RoadConfig : System.Object { [SerializeField] public RoadType roadType; [SerializeField] public int branch; [SerializeField] public float curveAngle; [SerializeField] public float rampAngle; [SerializeField] public float length; //when true, give the road a powerup section private bool powerUp; public bool PowerUp { get { return powerUp; } } //constructor used for creating road sections via script public RoadConfig(RoadType roadType, int branch, float curveAngle, float rampAngle, float length) { this.roadType = roadType; this.branch = branch; this.curveAngle = curveAngle; this.rampAngle = rampAngle; this.length = length; powerUp = false; } //alternative constructor for indicating config has a powerup section public RoadConfig(RoadType roadType, int branch, float curveAngle, float rampAngle, float length, bool powerUp) : this(roadType, branch, curveAngle, rampAngle, length) { this.powerUp = powerUp; } //to be determined by RoadManager private float begin; //properties for begin and end public float Begin { get { return begin; } set { begin = value; } } //unnessesary ??? private float end; public float End { get { return end; } set { end = value; } } }
29.055556
115
0.666667
[ "Unlicense" ]
Dayn9/TruckDriving
CarTest/Assets/scripts/RoadConfig.cs
1,571
C#
using System.Reflection; namespace FluentAssertions.Equivalency { /// <summary> /// Represents a rule that defines how to map the properties from the subject-under-test with the properties /// on the expectation object. /// </summary> public interface IMatchingRule { /// <summary> /// Attempts to find a property on the expectation that should be compared with the /// <paramref name="subjectProperty"/> during a structural equality. /// </summary> /// <remarks> /// Whether or not a match is required or optional is up to the specific rule. If no match is found and this is not an issue, /// simply return <c>null</c>. /// </remarks> /// <param name="subjectProperty"> /// The <see cref="PropertyInfo"/> of the subject's property for which a match must be found. Can never /// be <c>null</c>. /// </param> /// <param name="expectation"> /// The expectation object for which a matching property must be returned. Can never be <c>null</c>. /// </param> /// <param name="propertyPath"> /// The dotted path from the root object to the current property. Will never be <c>null</c>. /// </param> /// <returns> /// Returns the <see cref="PropertyInfo"/> of the property with which to compare the subject with, or <c>null</c> /// if no match was found. /// </returns> PropertyInfo Match(PropertyInfo subjectProperty, object expectation, string propertyPath); } }
44.914286
133
0.613232
[ "Apache-2.0" ]
blairconrad/fluentassertions
FluentAssertions.Net35/Equivalency/IMatchingRule.cs
1,572
C#
using System.Linq; namespace DragonSpark.Application.Entities.Queries.Runtime.Shape; public readonly record struct Composition<T>(IQueryable<T> Current, ulong? Count = null);
35.4
89
0.80791
[ "MIT" ]
DragonSpark/Framework
DragonSpark.Application/Entities/Queries/Runtime/Shape/Composition.cs
179
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyOnDeath : MonoBehaviour { public GameObject particle; private void Update() { if (this.GetComponent<EnemyHP>().hp < 1) { Instantiate(particle, transform.position, Quaternion.Euler(0, 0, 0)); //create particle Destroy(this.gameObject); } } }
22.555556
100
0.642857
[ "MIT" ]
ExplosiveFridge/ProjectVelocity
Assets/Scripts/Enemy/EnemyOnDeath.cs
408
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Playground { public partial class TestWindow : Form { public TestWindow() { InitializeComponent(); } } }
18.047619
42
0.691293
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-Extended-NET-5.470
Source/Krypton Toolkit Suite Extended/Demos/Playground/TestWindow.cs
381
C#
namespace DesktopBackgroundChanger { partial class EditConfigForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SaveButton = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.LinkTextBox = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.changeTimeout = new System.Windows.Forms.NumericUpDown(); this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); ((System.ComponentModel.ISupportInitialize)(this.changeTimeout)).BeginInit(); this.SuspendLayout(); // // SaveButton // this.SaveButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.SaveButton.Location = new System.Drawing.Point(376, 224); this.SaveButton.Name = "SaveButton"; this.SaveButton.Size = new System.Drawing.Size(75, 23); this.SaveButton.TabIndex = 0; this.SaveButton.Text = "Save"; this.SaveButton.UseVisualStyleBackColor = true; this.SaveButton.Click += new System.EventHandler(this.SaveButton_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(13, 13); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(30, 13); this.label1.TabIndex = 1; this.label1.Text = "Link:"; // // LinkTextBox // this.LinkTextBox.Location = new System.Drawing.Point(49, 13); this.LinkTextBox.Name = "LinkTextBox"; this.LinkTextBox.Size = new System.Drawing.Size(402, 20); this.LinkTextBox.TabIndex = 2; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(13, 36); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(200, 13); this.label2.TabIndex = 3; this.label2.Text = "Time in ms between background change"; // // changeTimeout // this.changeTimeout.Increment = new decimal(new int[] { 100, 0, 0, 0}); this.changeTimeout.Location = new System.Drawing.Point(219, 36); this.changeTimeout.Maximum = new decimal(new int[] { 10000, 0, 0, 0}); this.changeTimeout.Minimum = new decimal(new int[] { 250, 0, 0, 0}); this.changeTimeout.Name = "changeTimeout"; this.changeTimeout.Size = new System.Drawing.Size(120, 20); this.changeTimeout.TabIndex = 4; this.changeTimeout.Value = new decimal(new int[] { 250, 0, 0, 0}); // // saveFileDialog1 // this.saveFileDialog1.FileName = "config.json"; this.saveFileDialog1.Filter = "Json files| *.json; *.JSON"; // // EditConfigForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(463, 259); this.Controls.Add(this.changeTimeout); this.Controls.Add(this.label2); this.Controls.Add(this.LinkTextBox); this.Controls.Add(this.label1); this.Controls.Add(this.SaveButton); this.Name = "EditConfigForm"; this.Text = "EditConfigForm"; ((System.ComponentModel.ISupportInitialize)(this.changeTimeout)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button SaveButton; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox LinkTextBox; private System.Windows.Forms.Label label2; private System.Windows.Forms.NumericUpDown changeTimeout; private System.Windows.Forms.SaveFileDialog saveFileDialog1; } }
39.274074
161
0.556017
[ "MIT" ]
Dko1905/CSharpBackgroundChanger
DesktopBackgroundChanger/EditConfigForm.Designer.cs
5,304
C#
/* Copyright 2014 Nils Rehwald 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 CrypTool.PluginBase; using CrypTool.PluginBase.Miscellaneous; using System.ComponentModel; using System.Windows; namespace CrypTool.Plugins.WatermarkCreator { public class WatermarkCreatorSettings : ISettings { #region Private Variables private int _watermarkAlgorithm = 0; private int _textSize = 50; private int _font = 3; private int _location = 1; private int _opacity = 1000; private int _boxSize = 10; private readonly int _errorCorrection = 0; private long _s1 = 19; private long _s2 = 24; private int _locPercentage = 0; private int _advanced = 0; #endregion #region TaskPane Settings [TaskPane("ModificationTypeCap", "ModificationTypeDes", null, 0, false, ControlType.ComboBox, new string[] { "WatermarkCreatorSettings_ModificationType_EmbedText", "WatermarkCreatorSettings_ModificationType_EmbedInvisibleText", "WatermarkCreatorSettings_ModificationType_ExtractText" })] public int ModificationType { get => _watermarkAlgorithm; set { if (_watermarkAlgorithm != value) { _watermarkAlgorithm = value; OnPropertyChanged("ModificationType"); } } } [TaskPane("TextSizeMaxCap", "TextSizeMaxDes", null, 10, false, ControlType.TextBox)] public int TextSizeMax { get => _textSize; set { if (_textSize != value) { _textSize = value; OnPropertyChanged("TextSizeMax"); } } } [TaskPane("FontTypeCap", "FontTypeDes", null, 11, false, ControlType.ComboBox, new string[] { "Aharoni", "Andalus", "Arabic Typesetting", "Arial", "Arial Black", "Calibri", "Buxton Sketch", "Cambria Math", "Comic Sans MS", "DFKai-SB", "Franklin Gothic Medium", "Lucida Console", "Simplified Arabic", "SketchFlow Print", "Symbol", "Times New Roman", "Traditional Arabic", "Webdings", "Wingdings"})] public int FontType { get => _font; set { if (_font != value) { _font = value; OnPropertyChanged("FontType"); } } } [TaskPane("WatermarkLocationCap", "WatermarkLocationDes", null, 12, false, ControlType.ComboBox, new string[] { "TopLoc", "BotLoc", "OtherLoc" })] public int WatermarkLocation { get => _location; set { if (_location != value) { _location = value; OnPropertyChanged("WatermarkLocation"); } } } [TaskPane("LocationPercentageCap", "LocationPercentageDes", null, 13, true, ControlType.Slider, 5, 95)] public int LocationPercentage { get => _locPercentage; set { if (_locPercentage != value) { _locPercentage = value; OnPropertyChanged("LocationPercentage"); } } } [TaskPane("OpacityCap", "OpacityDes", null, 11, false, ControlType.TextBox)] public int Opacity { get => _opacity; set { if (_opacity != value) { _opacity = value; OnPropertyChanged("Opacity"); } } } [TaskPane("BoxSizeCap", "BoxSizeDes", null, 10, false, ControlType.TextBox)] public int BoxSize { get => _boxSize; set { if (_boxSize != value) { _boxSize = value; OnPropertyChanged("BoxSize"); } } } [TaskPane("Seed1", "Seed", null, 14, false, ControlType.TextBox)] public long Seed1 { get => _s1; set { if (_s1 != value) { _s1 = value; OnPropertyChanged("Seed1"); } } } [TaskPane("Seed2", "Seed", null, 15, false, ControlType.TextBox)] public long Seed2 { get => _s2; set { if (_s2 != value) { _s2 = value; OnPropertyChanged("Seed2"); } } } [TaskPane("AdvancedModeCap", "AdvancedModeDes", null, 5, false, ControlType.ComboBox, new string[] { "AdvancedModeList1", "AdvancedModeList2" })] public int AdvancedMode { get => _advanced; set { if (_advanced != value) { _advanced = value; OnPropertyChanged("AdvancedMode"); } } } //Managing visibility of options public void UpdateTaskPaneVisibility() { SettingChanged("ModificationType", Visibility.Visible); SettingChanged("TextSizeMax", Visibility.Collapsed); SettingChanged("FontType", Visibility.Collapsed); SettingChanged("WatermarkLocation", Visibility.Collapsed); SettingChanged("Opacity", Visibility.Collapsed); SettingChanged("BoxSize", Visibility.Collapsed); SettingChanged("Seed1", Visibility.Collapsed); SettingChanged("Seed2", Visibility.Collapsed); SettingChanged("LocationPercentage", Visibility.Collapsed); SettingChanged("AdvancedMode", Visibility.Collapsed); switch (ModificationType) { case 0: //Visible Watermark (embedding) SettingChanged("TextSizeMax", Visibility.Visible); SettingChanged("FontType", Visibility.Visible); SettingChanged("WatermarkLocation", Visibility.Visible); break; case 1: //Invisible Watermark (embedding) SettingChanged("AdvancedMode", Visibility.Visible); break; case 2: //Invisible Watermark (extracting) SettingChanged("AdvancedMode", Visibility.Visible); break; } switch (WatermarkLocation) { case 2: SettingChanged("LocationPercentage", Visibility.Visible); break; default: SettingChanged("LocationPercentage", Visibility.Collapsed); break; } //only show this settings for invisible water marks and when we are in "advanced mode" if (AdvancedMode == 1 && ModificationType > 0) { SettingChanged("Opacity", Visibility.Visible); SettingChanged("BoxSize", Visibility.Visible); SettingChanged("Seed1", Visibility.Visible); SettingChanged("Seed2", Visibility.Visible); } } private void SettingChanged(string setting, Visibility vis) { if (TaskPaneAttributeChanged != null) { TaskPaneAttributeChanged(this, new TaskPaneAttributeChangedEventArgs(new TaskPaneAttribteContainer(setting, vis))); } } #endregion #region Events public event PropertyChangedEventHandler PropertyChanged; public event TaskPaneAttributeChangedHandler TaskPaneAttributeChanged; private void OnPropertyChanged(string propertyName) { EventsHelper.PropertyChanged(PropertyChanged, this, propertyName); } public void Initialize() { UpdateTaskPaneVisibility(); } #endregion } }
33.045113
295
0.528555
[ "Apache-2.0" ]
CrypToolProject/CrypTool-2
CrypPlugins/WatermarkCreator/WatermarkCreatorSettings.cs
8,792
C#
/* Copyright 2012-2021 Marco De Salvo 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 RDFSharp.Model; using System.Collections.Generic; using System.Data; namespace RDFSharp.Query { /// <summary> /// RDFIsLiteralFilter represents a filter for literal values of a variable. /// </summary> public class RDFIsLiteralFilter : RDFFilter { #region Properties /// <summary> /// Variable to be filtered /// </summary> public RDFVariable Variable { get; internal set; } #endregion #region Ctors /// <summary> /// Default-ctor to build a filter on the given variable /// </summary> public RDFIsLiteralFilter(RDFVariable variable) { if (variable != null) { this.Variable = variable; } else { throw new RDFQueryException("Cannot create RDFIsLiteralFilter because given \"variable\" parameter is null."); } } #endregion #region Interfaces /// <summary> /// Gives the string representation of the filter /// </summary> public override string ToString() => this.ToString(new List<RDFNamespace>()); internal override string ToString(List<RDFNamespace> prefixes) => string.Concat("FILTER ( ISLITERAL(", this.Variable, ") )"); #endregion #region Methods /// <summary> /// Applies the filter on the column corresponding to the variable in the given datarow /// </summary> internal override bool ApplyFilter(DataRow row, bool applyNegation) { bool keepRow = true; //Check is performed only if the row contains a column named like the filter's variable if (row.Table.Columns.Contains(this.Variable.ToString())) { //Apply a negation logic on result of an "IsUri" filter RDFIsUriFilter isUriFilter = new RDFIsUriFilter(this.Variable); keepRow = isUriFilter.ApplyFilter(row, true); //Apply the eventual negation if (applyNegation) keepRow = !keepRow; } return keepRow; } #endregion } }
30.934783
126
0.601195
[ "Apache-2.0" ]
mdesalvo/RDFSharp
RDFSharp/Query/Mirella/Algebra/Filters/RDFIsLiteralFilter.cs
2,848
C#
using System.Collections; using System.Collections.Generic; using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; using NetOffice.CollectionsGeneric; namespace NetOffice.ExcelApi { /// <summary> /// DispatchInterface Axes /// SupportByVersion Excel, 9,10,11,12,14,15,16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Excel.Axes(object)"/> </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] [EntityType(EntityType.IsDispatchInterface), Enumerator(Enumerator.Reference, EnumeratorInvoke.Method), HasIndexProperty(IndexInvoke.Method, "_Default")] public class Axes : COMObject, IEnumerableProvider<NetOffice.ExcelApi.Axis> { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(Axes); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public Axes(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public Axes(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Axes(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Axes(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Axes(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Axes(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Axes() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Axes(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Excel.Axes.Application"/> </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Application Application { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Application>(this, "Application", NetOffice.ExcelApi.Application.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Excel.Axes.Creator"/> </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Enums.XlCreator Creator { get { return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCreator>(this, "Creator"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Excel.Axes.Parent"/> </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16), ProxyResult] public object Parent { get { return Factory.ExecuteReferencePropertyGet(this, "Parent"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Excel.Axes.Count"/> </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public Int32 Count { get { return Factory.ExecuteInt32PropertyGet(this, "Count"); } } #endregion #region Methods /// <summary> /// SupportByVersion Excel 12, 14, 15, 16 /// Custom Indexer /// </summary> /// <param name="type">NetOffice.ExcelApi.Enums.XlAxisType type</param> [SupportByVersion("Excel", 12, 14, 15, 16)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty, CustomIndexer] public NetOffice.ExcelApi.Axis this[NetOffice.ExcelApi.Enums.XlAxisType type] { get { return Factory.ExecuteKnownReferenceMethodGet<NetOffice.ExcelApi.Axis>(this, "_Default", NetOffice.ExcelApi.Axis.LateBindingApiWrapperType, type, 1); } } /// <summary> /// SupportByVersion Excel 12, 14, 15, 16 /// </summary> /// <param name="type">NetOffice.ExcelApi.Enums.XlAxisType type</param> /// <param name="axisGroup">optional NetOffice.ExcelApi.Enums.XlAxisGroup AxisGroup = 1</param> [SupportByVersion("Excel", 12,14,15,16)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty] public NetOffice.ExcelApi.Axis this[NetOffice.ExcelApi.Enums.XlAxisType type, object axisGroup] { get { return Factory.ExecuteKnownReferenceMethodGet<NetOffice.ExcelApi.Axis>(this, "_Default", NetOffice.ExcelApi.Axis.LateBindingApiWrapperType, type, axisGroup); } } #endregion #region IEnumerableProvider<NetOffice.ExcelApi.Axis> ICOMObject IEnumerableProvider<NetOffice.ExcelApi.Axis>.GetComObjectEnumerator(ICOMObject parent) { return NetOffice.Utils.GetComObjectEnumeratorAsMethod(parent, this, false); } IEnumerable IEnumerableProvider<NetOffice.ExcelApi.Axis>.FetchVariantComObjectEnumerator(ICOMObject parent, ICOMObject enumerator) { return NetOffice.Utils.FetchVariantComObjectEnumerator(parent, enumerator, false); } #endregion #region IEnumerable<NetOffice.ExcelApi.Axis> /// <summary> /// SupportByVersion Excel, 9,10,11,12,14,15,16 /// </summary> [SupportByVersion("Excel", 9, 10, 11, 12, 14, 15, 16)] public IEnumerator<NetOffice.ExcelApi.Axis> GetEnumerator() { NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable); foreach (NetOffice.ExcelApi.Axis item in innerEnumerator) yield return item; } #endregion #region IEnumerable /// <summary> /// SupportByVersion Excel, 9,10,11,12,14,15,16 /// </summary> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator() { return NetOffice.Utils.GetProxyEnumeratorAsMethod(this, false); } #endregion #pragma warning restore } }
34.286853
163
0.674994
[ "MIT" ]
NetOfficeFw/NetOffice
Source/Excel/DispatchInterfaces/Axes.cs
8,608
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; #pragma warning disable SA1121 // We use our own aliases since they differ per platform #if TARGET_WINDOWS using NativeType = System.Int32; #else using NativeType = System.IntPtr; #endif namespace System.Runtime.InteropServices { /// <summary> /// <see cref="CLong"/> is an immutable value type that represents the <c>long</c> type in C and C++. /// It is meant to be used as an exchange type at the managed/unmanaged boundary to accurately represent /// in managed code unmanaged APIs that use the <c>long</c> type. /// This type has 32-bits of storage on all Windows platforms and 32-bit Unix-based platforms. /// It has 64-bits of storage on 64-bit Unix platforms. /// </summary> [CLSCompliant(false)] [Intrinsic] public readonly struct CLong : IEquatable<CLong> { private readonly NativeType _value; /// <summary> /// Constructs an instance from a 32-bit integer. /// </summary> /// <param name="value">The integer vaule.</param> public CLong(int value) { _value = (NativeType)value; } /// <summary> /// Constructs an instance from a native sized integer. /// </summary> /// <param name="value">The integer vaule.</param> /// <exception cref="OverflowException"><paramref name="value"/> is outside the range of the underlying storage type.</exception> public CLong(nint value) { _value = checked((NativeType)value); } /// <summary> /// The underlying integer value of this instance. /// </summary> public nint Value => _value; /// <summary> /// Returns a value indicating whether this instance is equal to a specified object. /// </summary> /// <param name="o">An object to compare with this instance.</param> /// <returns><c>true</c> if <paramref name="o"/> is an instance of <see cref="CLong"/> and equals the value of this instance; otherwise, <c>false</c>.</returns> public override bool Equals([NotNullWhen(true)] object? o) => o is CLong other && Equals(other); /// <summary> /// Returns a value indicating whether this instance is equal to a specified <see cref="CLong"/> value. /// </summary> /// <param name="other">A <see cref="CLong"/> value to compare to this instance.</param> /// <returns><c>true</c> if <paramref name="other"/> has the same value as this instance; otherwise, <c>false</c>.</returns> public bool Equals(CLong other) => _value == other._value; /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A 32-bit signed integer hash code.</returns> public override int GetHashCode() => _value.GetHashCode(); /// <summary> /// Converts the numeric value of this instance to its equivalent string representation. /// </summary> /// <returns>The string representation of the value of this instance, consisting of a negative sign if the value is negative, and a sequence of digits ranging from 0 to 9 with no leading zeroes.</returns> public override string ToString() => _value.ToString(); } }
43.5625
212
0.637877
[ "MIT" ]
333fred/runtime
src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/CLong.cs
3,485
C#
/* * Copyright 2022 MASES s.r.l. * * 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. * * Refer to LICENSE for more information. */ using MASES.JCOBridge.C2JBridge; namespace Java.Awt.Font { public class TextHitInfo : JVMBridgeBase<TextHitInfo> { public override string ClassName => "java.awt.font.TextHitInfo"; } }
29.964286
75
0.731824
[ "Apache-2.0" ]
masesdevelopers/JNet
src/net/JNet/Java/Awt/Font/TextHitInfo.cs
841
C#
/** * Copyright 2018, 2019 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using Newtonsoft.Json; namespace IBM.Watson.Discovery.V1.Model { /// <summary> /// A passage query result. /// </summary> public class QueryPassages { /// <summary> /// The unique identifier of the document from which the passage has been extracted. /// </summary> [JsonProperty("document_id", NullValueHandling = NullValueHandling.Ignore)] public string DocumentId { get; set; } /// <summary> /// The confidence score of the passages's analysis. A higher score indicates greater confidence. /// </summary> [JsonProperty("passage_score", NullValueHandling = NullValueHandling.Ignore)] public double? PassageScore { get; set; } /// <summary> /// The content of the extracted passage. /// </summary> [JsonProperty("passage_text", NullValueHandling = NullValueHandling.Ignore)] public string PassageText { get; set; } /// <summary> /// The position of the first character of the extracted passage in the originating field. /// </summary> [JsonProperty("start_offset", NullValueHandling = NullValueHandling.Ignore)] public long? StartOffset { get; set; } /// <summary> /// The position of the last character of the extracted passage in the originating field. /// </summary> [JsonProperty("end_offset", NullValueHandling = NullValueHandling.Ignore)] public long? EndOffset { get; set; } /// <summary> /// The label of the field from which the passage has been extracted. /// </summary> [JsonProperty("field", NullValueHandling = NullValueHandling.Ignore)] public string Field { get; set; } } }
40.084746
105
0.659619
[ "MIT" ]
AkshaySharmaDEV/CovIt
Assets/unity-sdk-5.0.2/Scripts/Services/Discovery/V1/Model/QueryPassages.cs
2,365
C#
namespace HareDu.Tests { using System.Threading.Tasks; using Core; using Core.Extensions; using Extensions; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using Shouldly; [TestFixture] public class ConsumerTests : HareDuTesting { [Test] public void Verify_can_get_all_consumers() { var container = GetContainerBuilder("TestData/ConsumerInfo.json").BuildServiceProvider(); var result = container.GetService<IBrokerObjectFactory>() .Object<Consumer>() .GetAll() .GetResult(); result.HasFaulted.ShouldBeFalse(); result.HasData.ShouldBeTrue(); result.Data.ShouldNotBeNull(); result.Data.Count.ShouldBe(2); result.Data[0].ChannelDetails.ShouldNotBeNull(); result.Data[0].ChannelDetails?.Name.ShouldBe("127.0.0.0:61113 -> 127.0.0.0:5672 (1)"); result.Data[0].ChannelDetails?.Node.ShouldBe("rabbit@localhost"); result.Data[0].ChannelDetails?.Number.ShouldBe(1); result.Data[0].ChannelDetails?.ConnectionName.ShouldBe("127.0.0.0:61113 -> 127.0.0.0:5672"); result.Data[0].ChannelDetails?.PeerHost.ShouldBe("127.0.0.0"); result.Data[0].ChannelDetails?.PeerPort.ShouldBe(99883); result.Data[0].ChannelDetails?.User.ShouldBe("guest"); result.Data[0].QueueConsumerDetails.ShouldNotBeNull(); result.Data[0].QueueConsumerDetails?.Name.ShouldBe("fake_queue"); result.Data[0].QueueConsumerDetails?.VirtualHost.ShouldBe("TestVirtualHost"); result.Data[0].ConsumerTag.ShouldBe("amq.ctag-fOtZo9ajuHDYQQ5hzrgasA"); result.Data[0].PreFetchCount.ShouldBe<ulong>(0); result.Data[0].Exclusive.ShouldBeFalse(); result.Data[0].AcknowledgementRequired.ShouldBeTrue(); } [Test] public async Task Verify_can_get_all_consumers1() { var services = GetContainerBuilder("TestData/ConsumerInfo.json").BuildServiceProvider(); var result = await services.GetService<IBrokerObjectFactory>() .Object<Consumer>() .GetAll(); Assert.Multiple(() => { Assert.IsFalse(result.HasFaulted); Assert.IsTrue(result.HasData); Assert.IsNotNull(result.Data[0].ChannelDetails); Assert.IsNotNull(result.Data); Assert.AreEqual(2, result.Data.Count); Assert.AreEqual("127.0.0.0:61113 -> 127.0.0.0:5672 (1)", result.Data[0].ChannelDetails?.Name); Assert.AreEqual("rabbit@localhost", result.Data[0].ChannelDetails?.Node); Assert.AreEqual(1, result.Data[0].ChannelDetails?.Number); Assert.AreEqual("127.0.0.0:61113 -> 127.0.0.0:5672", result.Data[0].ChannelDetails?.ConnectionName); Assert.AreEqual("127.0.0.0", result.Data[0].ChannelDetails?.PeerHost); Assert.AreEqual(99883, result.Data[0].ChannelDetails?.PeerPort); Assert.AreEqual("guest", result.Data[0].ChannelDetails?.User); Assert.IsNotNull(result.Data[0].QueueConsumerDetails); Assert.AreEqual("fake_queue", result.Data[0].QueueConsumerDetails?.Name); Assert.AreEqual("TestVirtualHost", result.Data[0].QueueConsumerDetails?.VirtualHost); Assert.AreEqual("amq.ctag-fOtZo9ajuHDYQQ5hzrgasA", result.Data[0].ConsumerTag); Assert.AreEqual(0, result.Data[0].PreFetchCount); Assert.IsFalse(result.Data[0].Exclusive); Assert.IsTrue(result.Data[0].AcknowledgementRequired); }); } [Test] public async Task Verify_can_get_all_consumers2() { var services = GetContainerBuilder("TestData/ConsumerInfo.json").BuildServiceProvider(); var result = await services.GetService<IBrokerObjectFactory>() .GetAllConsumers(); Assert.Multiple(() => { Assert.IsFalse(result.HasFaulted); Assert.IsTrue(result.HasData); Assert.IsNotNull(result.Data[0].ChannelDetails); Assert.IsNotNull(result.Data); Assert.AreEqual(2, result.Data.Count); Assert.AreEqual("127.0.0.0:61113 -> 127.0.0.0:5672 (1)", result.Data[0].ChannelDetails?.Name); Assert.AreEqual("rabbit@localhost", result.Data[0].ChannelDetails?.Node); Assert.AreEqual(1, result.Data[0].ChannelDetails?.Number); Assert.AreEqual("127.0.0.0:61113 -> 127.0.0.0:5672", result.Data[0].ChannelDetails?.ConnectionName); Assert.AreEqual("127.0.0.0", result.Data[0].ChannelDetails?.PeerHost); Assert.AreEqual(99883, result.Data[0].ChannelDetails?.PeerPort); Assert.AreEqual("guest", result.Data[0].ChannelDetails?.User); Assert.IsNotNull(result.Data[0].QueueConsumerDetails); Assert.AreEqual("fake_queue", result.Data[0].QueueConsumerDetails?.Name); Assert.AreEqual("TestVirtualHost", result.Data[0].QueueConsumerDetails?.VirtualHost); Assert.AreEqual("amq.ctag-fOtZo9ajuHDYQQ5hzrgasA", result.Data[0].ConsumerTag); Assert.AreEqual(0, result.Data[0].PreFetchCount); Assert.IsFalse(result.Data[0].Exclusive); Assert.IsTrue(result.Data[0].AcknowledgementRequired); }); } } }
52.425926
116
0.611268
[ "Apache-2.0" ]
ahives/HareDu1
src/HareDu.Tests/ConsumerTests.cs
5,662
C#
// ------------------------------------------------------------------------------------------------- // <copyright file="ElementGroupingErrorCategory.cs" company="RHEA System S.A."> // // Copyright 2022 RHEA System S.A. // // 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. // // </copyright> // ------------------------------------------------------------------------------------------------ namespace Kalliope.Core { using Kalliope.Common; /// <summary> /// Grouping Errors /// </summary> [Description("Grouping Errors")] [Domain(isAbstract: true, general: "ModelErrorCategory")] public abstract class ElementGroupingErrorCategory : ModelErrorCategory { } }
36.941176
102
0.569268
[ "Apache-2.0" ]
RHEAGROUP/Kalliope
Kalliope/Core/ModelErrorCategories/ElementGroupingErrorCategory.cs
1,258
C#
namespace DioPOO.src.Entities.Heroes { public class Acolyte : Hero { public Acolyte(string Name, int Level, string HeroType, int HP, int MP, string Weapon) : base(Name, Level, HeroType, HP, MP, Weapon) { this.Name = Name; this.Level = Level; this.HeroType = HeroType; this.HP = HP; this.MP = MP; this.Weapon = Weapon; } public override string Attack() { return this.Name + " Atacou com a sua " + this.Weapon; } public string Heal() { return this.Name + " Lançou magia de Cura!"; } public string Protect() { return this.Name + " Lançou magia de Proteção"; } public string Attack(int Bonus) { if (Bonus > 6) { return this.Name + " Lançou magia super efetiva com bônus de ataque de " + Bonus; } else { return this.Name + " Lançou uma magia com força fraca com bonus de " + Bonus; } } } }
25.222222
140
0.482819
[ "MIT" ]
Raphael-Azevedo/DioGFTPoo
DioPOO/src/Entities/Heroes/Acolyte.cs
1,143
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.Reflection; namespace System.Linq.Expressions.Tests { static class ReflectionExtensions { public static ConstructorInfo GetDeclaredConstructor(this TypeInfo type, Type[] parameterTypes) { return type.DeclaredConstructors.SingleOrDefault(c => c.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)); } } }
33.875
144
0.728782
[ "MIT" ]
mellinoe/corefx
src/System.Linq.Expressions/tests/Catalog/ReflectionExtensions.cs
544
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Element { public static class ElementBuffFactor { /// <summary> /// First entry = attacker /// Second entry = receiver /// Data = elemental multiplier /// </summary> //public static List<List<float>> elementCounterTable; public static float[,] elementCounterTable; static ElementBuffFactor() { elementCounterTable = new float[7, 7]; int empty = ElementTypeToInt.CastElementTypeToInt(ElementType.EMPTY); int fire = ElementTypeToInt.CastElementTypeToInt(ElementType.FIRE); int water = ElementTypeToInt.CastElementTypeToInt(ElementType.WATER); int ice = ElementTypeToInt.CastElementTypeToInt(ElementType.ICE); int grass = ElementTypeToInt.CastElementTypeToInt(ElementType.GRASS); int dark = ElementTypeToInt.CastElementTypeToInt(ElementType.DARK); int holy = ElementTypeToInt.CastElementTypeToInt(ElementType.HOLY); //Empty attacker: elementCounterTable[empty,empty] = 1f; elementCounterTable[empty,fire] = 1f; elementCounterTable[empty,water] = 1f; elementCounterTable[empty,ice] = 1f; elementCounterTable[empty,grass] = 1f; elementCounterTable[empty,dark] = 1f; elementCounterTable[empty,holy] = 1.25f; //fire attacker: elementCounterTable[fire,empty] = 1f; elementCounterTable[fire,fire] = 1f; elementCounterTable[fire,water] = 0.85f; elementCounterTable[fire,ice] = 1.25f; elementCounterTable[fire,grass] = 1.25f; elementCounterTable[fire,dark] = 1f; elementCounterTable[fire,holy] = 0.85f; //water attacker: elementCounterTable[water,empty] = 1f; elementCounterTable[water,fire] = 1.25f; elementCounterTable[water,water] = 1f; elementCounterTable[water,ice] = 1f; elementCounterTable[water,grass] = 0.85f; elementCounterTable[water,dark] = 1f; elementCounterTable[water,holy] = 1f; //ice attacker: elementCounterTable[ice,empty] = 1f; elementCounterTable[ice,fire] = 0.85f; elementCounterTable[ice,water] = 1f; elementCounterTable[ice,ice] = 1f; elementCounterTable[ice,grass] = 1.25f; elementCounterTable[ice,dark] = 1f; elementCounterTable[ice,holy] = 1f; //grass attacker: elementCounterTable[grass,empty] = 1f; elementCounterTable[grass,fire] = 0.85f; elementCounterTable[grass,water] = 1.25f; elementCounterTable[grass,ice] = 1f; elementCounterTable[grass,grass] = 1f; elementCounterTable[grass,dark] = 1f; elementCounterTable[grass,holy] = 1.25f; //dark attacker: elementCounterTable[dark,empty] = 1f; elementCounterTable[dark,fire] = 1.25f; elementCounterTable[dark,water] = 1f; elementCounterTable[dark,ice] = 1f; elementCounterTable[dark,grass] = 1f; elementCounterTable[dark,dark] = 1.25f; elementCounterTable[dark,holy] = 0.85f; //holy attacker: elementCounterTable[holy,empty] = 1f; elementCounterTable[holy,fire] = 0.85f; elementCounterTable[holy,water] = 1f; elementCounterTable[holy,ice] = 1.25f; elementCounterTable[holy,grass] = 0.85f; elementCounterTable[holy,dark] = 1.25f; elementCounterTable[holy,holy] = 1f; } public static float GetElementalBuffFactor(ElementType attackElement, ElementType receiverElement) { int attacker = ElementTypeToInt.CastElementTypeToInt(attackElement); int receiver = ElementTypeToInt.CastElementTypeToInt(receiverElement); return elementCounterTable[attacker,receiver]; } //public static List<ElementType> } }
40.52381
106
0.607521
[ "MIT" ]
HongCFull/Comp4971C
Assets/Scripts/Gameplay/Combat/Element/ElementBuffFactor.cs
4,255
C#
using UnityEngine; using System.Collections; using UnityEngine.Events; namespace Invector.CharacterController { public class vOnDeadTrigger : MonoBehaviour { public UnityEvent OnDead; void Start() { vCharacter character = GetComponent<vCharacter>(); if (character) character.onDead.AddListener(OnDeadHandle); } public void OnDeadHandle(GameObject target) { OnDead.Invoke(); } } }
21.869565
62
0.606362
[ "MIT" ]
boveloco/AMazeSurvivor
Assets/Controller/Basic Locomotion/Scripts/CharacterController/vOnDeadTrigger.cs
505
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; namespace CZGL.SystemInfo.Linux { /// <summary> /// 获取 Linux 系统动态资源消耗信息 /// </summary> public class DynamicInfo { private Tasks _tasks; private CpuState _cpuState; private Mem _mem; private Swap _swap; private Dictionary<int,PidInfo> _pidInfo; /// <summary> /// 获取 Linux 系统动态资源消耗信息 /// </summary> /// <exception cref="PlatformNotSupportedException">当算法不支持时</exception> public DynamicInfo() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { var psi = new ProcessStartInfo("top", "-b -n 1") { RedirectStandardOutput = true }; var proc = Process.Start(psi); if (proc != null) { using (var sr = proc.StandardOutput) { Dictionary <int,string> dic=new Dictionary<int, string>(); try { int i = -1; int n = 0; while (!sr.EndOfStream) { ++i; string str = sr.ReadLine(); if (i == 0 || i == 5 || i == 6) continue; dic.Add(n, str); ++n; } SetTasks(dic[0]); SetCpuState(dic[1]); SetMem(dic[2]); SetSwap(dic[3]); SetPidInfo(dic.Where(x => x.Key > 3).Select(x => x.Value).ToArray()); } catch{} if (!proc.HasExited) { proc.Kill(); } } } else { throw new PlatformNotSupportedException($"The current operating system is not supported({nameof(CZGL.SystemInfo.Linux)}s)."); } } else { throw new PlatformNotSupportedException($"The current operating system is not supported(nameof(CZGL.SystemInfo.Linux))."); } } #region 获取信息算法 /// <summary> /// 设置系统进程信息 /// </summary> /// <param name="line"></param> private void SetTasks(string line) { // Tasks: 246 total, 1 running, 174 sleeping, 0 stopped, 0 zombie line = line.Replace(" ", string.Empty); line = line.Substring(line.IndexOf(':')+1); string[] any = line.Split(','); if(any.Length!=5) return; try { _tasks = new Tasks() { Total = Convert.ToInt32(GetNum(ref any[0])), Running = Convert.ToInt32(GetNum(ref any[1])), Sleeping = Convert.ToInt32(GetNum(ref any[2])), Stopped = Convert.ToInt32(GetNum(ref any[3])), Zombie = Convert.ToInt32(GetNum(ref any[4])) }; _tasks.IsSuccess = true; } catch { return; } } /// <summary> /// 设置CPU信息 /// </summary> /// <param name="line"></param> private void SetCpuState(string line) { // %Cpu(s): 4.9 us, 0.9 sy, 0.0 ni, 93.8 id, 0.4 wa, 0.0 hi, 0.0 si, 0.0 st line = line.Replace(" ", string.Empty); line = line.Substring(line.IndexOf(':')+1); string[] any = line.Split(','); if(any.Length!=8) return; try { _cpuState = new CpuState() { UserSpace =Convert.ToDouble(GetNum(ref any[0])), Sysctl =Convert.ToDouble(GetNum(ref any[1])), NI =Convert.ToDouble(GetNum(ref any[2])), Idolt =Convert.ToDouble(GetNum(ref any[3])), WaitIO =Convert.ToDouble(GetNum(ref any[4])), HardwareIRQ =Convert.ToDouble(GetNum(ref any[5])), SoftwareInterrupts =Convert.ToDouble(GetNum(ref any[6])) }; _cpuState.IsSuccess = true; } catch { return; } } /// <summary> /// 设置内存信息 /// </summary> /// <param name="line"></param> private void SetMem(string line) { // KiB Mem : 8105472 total, 1098760 free, 4061184 used, 2945528 buff/cache line = line.Replace(" ", string.Empty); line = line.Substring(line.IndexOf(':')+1); string[] any = line.Split(','); if(any.Length!=4) return; try { _mem = new Mem() { Total = Convert.ToInt32(GetNum(ref any[0])), Free = Convert.ToInt32(GetNum(ref any[1])), Used = Convert.ToInt32(GetNum(ref any[2])), Buffers = Convert.ToInt32(GetNum(ref any[3])) }; _mem.IsSuccess = true; } catch { return; } } /// <summary> /// 设置虚拟内存信息 /// </summary> /// <param name="line"></param> private void SetSwap(string line) { // KiB Swap: 4194300 total, 4194300 free, 0 used. 3678612 avail Mem line = line.Replace(" ", string.Empty); line = line.Substring(line.IndexOf(':')+1); string[] any = line.Split(','); if(any.Length!=3) return; try { string[] used = any[2].Split('.'); _swap = new Swap() { Total = Convert.ToInt32(GetNum(ref any[0])), Free = Convert.ToInt32(GetNum(ref any[1])), Used = Convert.ToInt32(GetNum(ref used[0])), AvailMem = Convert.ToInt32(GetNum(ref used[1])) }; _mem.IsSuccess = true; } catch { return; } } private void SetPidInfo(string[] lines) { // PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND // 7214 whuanle 20 0 5159720 1.508g 134084 S 27.9 19.5 16:21.66 mono-sgen try { List<PidInfo> pids=new List<PidInfo>(); for (int i = 0; i < lines.Length; i++) { pids.Add(SetPidInfoLine(lines[i])); } _pidInfo = pids.ToDictionary(x=>x.PID,x=>x); } catch { _pidInfo = default; } } /// <summary> /// 获取一个进程的信息 /// </summary> /// <param name="line"></param> /// <returns></returns> /// <exception cref="Exception"></exception> private PidInfo SetPidInfoLine(string line) { try { string[] result = GetStringArray(line.Trim()); return new PidInfo() { PID = Convert.ToInt32(result[0]), User = result[1], PR = result[2], Nice = Convert.ToInt32(result[3]), VIRT = result[4], RES = result[5], SHR = result[6], State = Convert.ToChar(result[7]), CPU = Convert.ToDouble(result[8]), Mem = Convert.ToDouble(result[9]), Command = result[11], IsSuccess = true }; } catch(Exception ex) { throw ex; } } /// <summary> /// 去除字符串中的空格并生成字符串数组 /// </summary> /// <param name="line"></param> /// <returns></returns> private string[] GetStringArray(string line) { // 7214 whuanle 20 0 5159720 1.508g 134084 S 27.9 19.5 16:21.66 mono-sgen return line.Split(' ').Where(x => x != string.Empty).ToArray(); } /// <summary> /// 从字符串中提取数字 /// </summary> /// <param name="str"></param> /// <returns></returns> private string GetNum(ref string str) { return str.Substring(0, GetCharIndex(ref str)); } /// <summary> /// 获取数字索引后一位位置 /// </summary> /// <param name="str"></param> /// <returns></returns> private int GetCharIndex(ref string str) { for (int i = 0; i < str.Length; i++) { if (char.IsLetter(str[i])) return i; } return -1; } #endregion /// <summary> /// 获取进程列表 /// </summary> /// <returns></returns> public Tasks GetTasks() { return _tasks; } /// <summary> /// 获取CPU负载状态 /// </summary> /// <returns></returns> public CpuState GetCpuState() { return _cpuState; } /// <summary> /// 获取系统内存使用信息 /// </summary> /// <returns></returns> public Mem GetMem() { return _mem; } /// <summary> /// 获取虚拟内存使用信息 /// </summary> /// <returns></returns> public Swap GetSwap() { return _swap; } /// <summary> /// 获取所有进程的使用资源信息 /// </summary> /// <returns></returns> public Dictionary<int,PidInfo> GetPidInfo() { return _pidInfo; } } }
31.269006
147
0.395642
[ "Apache-2.0" ]
LGinC/CZGL.SystemInfo
src/CZGL.SystemInfo.Linux/DynamicInfo.cs
11,002
C#
using System.Collections.Generic; using Microsoft.Maui.Layouts; using Microsoft.Maui.Primitives; using NSubstitute; using Xunit; namespace Microsoft.Maui.UnitTests.Layouts { [Category(TestCategory.Core, TestCategory.Layout)] public class LayoutExtensionTests { [Fact] public void FrameExcludesMargin() { var element = Substitute.For<IView>(); var margin = new Thickness(20); element.Margin.Returns(margin); var bounds = new Rectangle(0, 0, 100, 100); var frame = element.ComputeFrame(bounds); // With a margin of 20 all the way around, we expect the actual frame // to be 60x60, with an x,y position of 20,20 Assert.Equal(20, frame.Top); Assert.Equal(20, frame.Left); Assert.Equal(60, frame.Width); Assert.Equal(60, frame.Height); } [Theory] [InlineData(LayoutAlignment.Fill)] [InlineData(LayoutAlignment.Start)] [InlineData(LayoutAlignment.Center)] [InlineData(LayoutAlignment.End)] public void FrameSizeGoesToZeroWhenMarginsExceedBounds(LayoutAlignment layoutAlignment) { var element = Substitute.For<IView>(); var margin = new Thickness(200); element.Margin.Returns(margin); element.HorizontalLayoutAlignment.Returns(layoutAlignment); element.VerticalLayoutAlignment.Returns(layoutAlignment); var bounds = new Rectangle(0, 0, 100, 100); var frame = element.ComputeFrame(bounds); // The margin is simply too large for the bounds; since negative widths/heights on a frame don't make sense, // we expect them to collapse to zero Assert.Equal(0, frame.Height); Assert.Equal(0, frame.Width); } [Fact] public void DesiredSizeIncludesMargin() { var widthConstraint = 400; var heightConstraint = 655; var handler = Substitute.For<IViewHandler>(); var element = Substitute.For<IView>(); var margin = new Thickness(20); // Our "native" control will request a size of (100,50) when we call GetDesiredSize handler.GetDesiredSize(Arg.Any<double>(), Arg.Any<double>()).Returns(new Size(100, 50)); element.Handler.Returns(handler); element.Margin.Returns(margin); var desiredSize = element.ComputeDesiredSize(widthConstraint, heightConstraint); // Because the actual ("native") measurement comes back with (100,50) // and the margin on the IFrameworkElement is 20, the expected width is (100 + 20 + 20) = 140 // and the expected height is (50 + 20 + 20) = 90 Assert.Equal(140, desiredSize.Width); Assert.Equal(90, desiredSize.Height); } public static IEnumerable<object[]> AlignmentTestData() { var margin = Thickness.Zero; // No margin yield return new object[] { LayoutAlignment.Start, margin, 0, 100 }; yield return new object[] { LayoutAlignment.Center, margin, 100, 100 }; yield return new object[] { LayoutAlignment.End, margin, 200, 100 }; yield return new object[] { LayoutAlignment.Fill, margin, 0, 300 }; // Even margin margin = new Thickness(10); yield return new object[] { LayoutAlignment.Start, margin, 10, 100 }; yield return new object[] { LayoutAlignment.Center, margin, 100, 100 }; yield return new object[] { LayoutAlignment.End, margin, 190, 100 }; yield return new object[] { LayoutAlignment.Fill, margin, 10, 280 }; // Lopsided margin margin = new Thickness(5, 5, 10, 10); yield return new object[] { LayoutAlignment.Start, margin, 5, 100 }; yield return new object[] { LayoutAlignment.Center, margin, 97.5, 100 }; yield return new object[] { LayoutAlignment.End, margin, 190, 100 }; yield return new object[] { LayoutAlignment.Fill, margin, 5, 285 }; } [Theory] [MemberData(nameof(AlignmentTestData))] public void FrameAccountsForHorizontalLayoutAlignment(LayoutAlignment layoutAlignment, Thickness margin, double expectedX, double expectedWidth) { var widthConstraint = 300; var heightConstraint = 50; var viewSize = new Size(100, 50); var element = Substitute.For<IView>(); element.Margin.Returns(margin); element.DesiredSize.Returns(viewSize); element.HorizontalLayoutAlignment.Returns(layoutAlignment); var frame = element.ComputeFrame(new Rectangle(0, 0, widthConstraint, heightConstraint)); Assert.Equal(expectedX, frame.Left); Assert.Equal(expectedWidth, frame.Width); } [Theory] [MemberData(nameof(AlignmentTestData))] public void FrameAccountsForVerticalLayoutAlignment(LayoutAlignment layoutAlignment, Thickness margin, double expectedY, double expectedHeight) { var widthConstraint = 50; var heightConstraint = 300; var viewSize = new Size(50, 100); var element = Substitute.For<IView>(); element.Margin.Returns(margin); element.DesiredSize.Returns(viewSize); element.VerticalLayoutAlignment.Returns(layoutAlignment); var frame = element.ComputeFrame(new Rectangle(0, 0, widthConstraint, heightConstraint)); Assert.Equal(expectedY, frame.Top); Assert.Equal(expectedHeight, frame.Height); } public static IEnumerable<object[]> AlignmentTestDataRtl() { var margin = Thickness.Zero; // No margin yield return new object[] { LayoutAlignment.Start, margin, 200, 100 }; yield return new object[] { LayoutAlignment.Center, margin, 100, 100 }; yield return new object[] { LayoutAlignment.End, margin, 0, 100 }; yield return new object[] { LayoutAlignment.Fill, margin, 0, 300 }; // Even margin margin = new Thickness(10); yield return new object[] { LayoutAlignment.Start, margin, 190, 100 }; yield return new object[] { LayoutAlignment.Center, margin, 100, 100 }; yield return new object[] { LayoutAlignment.End, margin, 10, 100 }; yield return new object[] { LayoutAlignment.Fill, margin, 10, 280 }; // Lopsided margin margin = new Thickness(5, 5, 10, 10); yield return new object[] { LayoutAlignment.Start, margin, 195, 100 }; yield return new object[] { LayoutAlignment.Center, margin, 102.5, 100 }; yield return new object[] { LayoutAlignment.End, margin, 10, 100 }; yield return new object[] { LayoutAlignment.Fill, margin, 10, 285 }; } [Theory] [MemberData(nameof(AlignmentTestDataRtl))] public void FrameAccountsForHorizontalLayoutAlignmentRtl(LayoutAlignment layoutAlignment, Thickness margin, double expectedX, double expectedWidth) { var widthConstraint = 300; var heightConstraint = 50; var viewSize = new Size(100, 50); var element = Substitute.For<IView>(); element.Margin.Returns(margin); element.DesiredSize.Returns(viewSize); element.FlowDirection.Returns(FlowDirection.RightToLeft); element.HorizontalLayoutAlignment.Returns(layoutAlignment); var frame = element.ComputeFrame(new Rectangle(0, 0, widthConstraint, heightConstraint)); Assert.Equal(expectedX, frame.Left); Assert.Equal(expectedWidth, frame.Width); } } }
34.984536
111
0.721084
[ "MIT" ]
Eilon/maui
src/Core/tests/UnitTests/Layouts/LayoutExtensionTests.cs
6,789
C#
namespace USchedule.Core.Enums { public enum SubjectType { Practical = 0, Lab = 1, Lecture = 2 } }
15
31
0.518519
[ "MIT" ]
stenvix/uschedule-api
src/USchedule.Core/Enums/SubjectType.cs
137
C#
using UnityEngine; namespace SimpleKeplerOrbits { public class HyperbolaData { public double A; public double B; public double C; public double Eccentricity; public Vector3d Center; public Vector3d FocusDistance; public Vector3d Focus0; public Vector3d Focus1; public Vector3d AxisMain; public Vector3d AxisSecondary; public Vector3d Normal { get { return KeplerOrbitUtils.CrossProduct(AxisMain, AxisSecondary).normalized; } } /// <summary> /// Construct new hyperbola from 2 focuses and a point on one of branches. /// </summary> /// <param name="focus0">Focus of branch 0.</param> /// <param name="focus1">Focus of branch 1.</param> /// <param name="p0">Point on hyperbola branch 0.</param> public HyperbolaData(Vector3 focus0, Vector3 focus1, Vector3 p0) { Initialize(new Vector3d(focus0), new Vector3d(focus1), new Vector3d(p0)); } /// <summary> /// Construct new hyperbola from 2 focuses and a point on one of branches. /// </summary> /// <param name="focus0">Focus of branch 0.</param> /// <param name="focus1">Focus of branch 1.</param> /// <param name="p0">Point on hyperbola branch 0.</param> public HyperbolaData(Vector3d focus0, Vector3d focus1, Vector3d p0) { Initialize(focus0, focus1, p0); } private void Initialize(Vector3d focus0, Vector3d focus1, Vector3d p0) { Focus0 = focus0; Focus1 = focus1; FocusDistance = Focus1 - Focus0; AxisMain = FocusDistance.normalized; var tempNormal = KeplerOrbitUtils.CrossProduct(AxisMain, p0 - Focus0).normalized; AxisSecondary = KeplerOrbitUtils.CrossProduct(AxisMain, tempNormal).normalized; C = FocusDistance.magnitude * 0.5; A = System.Math.Abs(((p0 - Focus0).magnitude - (p0 - Focus1).magnitude)) * 0.5; Eccentricity = C / A; B = System.Math.Sqrt(C * C - A * A); Center = focus0 + FocusDistance * 0.5; } /// <summary> /// Get point on hyperbola curve. /// </summary> /// <param name="hyperbolicCoordinate">Hyperbola's parametric function time parameter.</param> /// <param name="isMainBranch">Is taking first branch, or, if false, second branch.</param> /// <returns>Point on hyperbola at given time (-inf..inf).</returns> /// <remarks> /// First branch is considered the branch, which was specified in constructor of hyperboal with a point, laying on that branch. /// Therefore second branch is always opposite from that. /// </remarks> public Vector3d GetSamplePointOnBranch(double hyperbolicCoordinate, bool isMainBranch) { double x = A * System.Math.Cosh(hyperbolicCoordinate); double y = B * System.Math.Sinh(hyperbolicCoordinate); Vector3d result = Center + (isMainBranch ? AxisMain : -AxisMain) * x + AxisSecondary * y; return result; } public void DebugDrawHyperbola(Color col) { var lastP00 = GetSamplePointOnBranch(0, true); var lastP01 = GetSamplePointOnBranch(0, false); var lastP10 = GetSamplePointOnBranch(0, true); var lastP11 = GetSamplePointOnBranch(0, false); float step = 0.1f; for (int i = 0; i < 100; i++) { var p00 = GetSamplePointOnBranch(i * step, true); var p01 = GetSamplePointOnBranch(i * step, false); var p10 = GetSamplePointOnBranch(-i * step, true); var p11 = GetSamplePointOnBranch(-i * step, false); Debug.DrawLine((Vector3)lastP00, (Vector3)p00, col); Debug.DrawLine((Vector3)lastP01, (Vector3)p01, col); Debug.DrawLine((Vector3)lastP10, (Vector3)p10, col); Debug.DrawLine((Vector3)lastP11, (Vector3)p11, col); lastP00 = p00; lastP01 = p01; lastP10 = p10; lastP11 = p11; } } } }
33.803738
129
0.690075
[ "MIT" ]
In-dialog/heaven2.1
Server_Heaven/Assets/SimpleKeplerOrbits/Scripts/Data/HyperbolaData.cs
3,619
C#
namespace ErlSharp.Forms { using System; using System.Collections.Generic; using System.Linq; using System.Text; using ErlSharp.Expressions; using ErlSharp.Language; public class FunctionForm : IForm { private string name; private IList<IExpression> parameterexpressions; private IExpression body; public FunctionForm(string name, IList<IExpression> parameterexpressions, IExpression body) { this.name = name; this.parameterexpressions = parameterexpressions; this.body = body; if (body is CallExpression) this.body = ((CallExpression)body).ToDelayedCallExpression(); else if (body is CompositeExpression) { var cexpr = (CompositeExpression)body; var last = cexpr.Expressions.Count - 1; if (cexpr.Expressions[last] is CallExpression) cexpr.Expressions[last] = ((CallExpression)cexpr.Expressions[last]).ToDelayedCallExpression(); } } public string Name { get { return this.name; } } public IList<IExpression> ParameterExpressions { get { return this.parameterexpressions; } } public IExpression Body { get { return this.body; } } public object Evaluate(Context context) { Context newcontext = new Context(); IList<object> parameters = new List<object>(); foreach (var pexpr in this.parameterexpressions) parameters.Add(pexpr.Evaluate(newcontext, true)); var func = new Function(context, parameters, this.body); context.SetValue(string.Format("{0}/{1}", this.name, parameters.Count), func); return func; } } }
33.285714
115
0.591202
[ "MIT" ]
ajlopez/ErlSharp
Src/ErlSharp/Forms/FunctionForm.cs
1,866
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006-2019, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to licence terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.472) // Version 5.472.0.0 www.ComponentFactory.com // ***************************************************************************** using System.ComponentModel; using System.Diagnostics; namespace ComponentFactory.Krypton.Toolkit { /// <summary> /// Redirect storage for GroupBox states. /// </summary> public class PaletteGroupBoxRedirect : PaletteDoubleRedirect { #region Instance Fields private readonly PaletteContentInheritRedirect _contentInherit; #endregion #region Identity /// <summary> /// Initialize a new instance of the PaletteGroupBoxRedirect class. /// </summary> /// <param name="redirect">Inheritence redirection instance.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> public PaletteGroupBoxRedirect(PaletteRedirect redirect, NeedPaintHandler needPaint) : this(redirect, redirect, needPaint) { } /// <summary> /// Initialize a new instance of the PaletteGroupBoxRedirect class. /// </summary> /// <param name="redirectDouble">Inheritence redirection for group border/background.</param> /// <param name="redirectContent">Inheritence redirection for group header.</param> /// <param name="needPaint">Delegate for notifying paint requests.</param> public PaletteGroupBoxRedirect(PaletteRedirect redirectDouble, PaletteRedirect redirectContent, NeedPaintHandler needPaint) : base(redirectDouble, PaletteBackStyle.ControlGroupBox, PaletteBorderStyle.ControlGroupBox, needPaint) { Debug.Assert(redirectDouble != null); Debug.Assert(redirectContent != null); _contentInherit = new PaletteContentInheritRedirect(redirectContent, PaletteContentStyle.LabelGroupBoxCaption); Content = new PaletteContent(_contentInherit, needPaint); } #endregion #region IsDefault /// <summary> /// Gets a value indicating if all values are default. /// </summary> [Browsable(false)] public override bool IsDefault => (base.IsDefault && Content.IsDefault); #endregion #region Content /// <summary> /// Gets access to the content palette details. /// </summary> [KryptonPersist] [Category("Visuals")] [Description("Overrides for defining content appearance.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public PaletteContent Content { get; } private bool ShouldSerializeContent() { return !Content.IsDefault; } /// <summary> /// Gets the content palette. /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Advanced)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IPaletteContent PaletteContent => Content; /// <summary> /// Gets and sets the content palette style. /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Advanced)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PaletteContentStyle ContentStyle { get => _contentInherit.Style; set => _contentInherit.Style = value; } #endregion } }
39.317308
157
0.641722
[ "BSD-3-Clause" ]
anuprakash/Krypton-NET-5.472
Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Palette Controls/PaletteGroupBoxRedirect.cs
4,092
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Data; using ItemsRepeaterElementIndexChangedEventArgs = Microsoft.UI.Xaml.Controls.ItemsRepeaterElementIndexChangedEventArgs; using ItemsRepeaterElementPreparedEventArgs = Microsoft.UI.Xaml.Controls.ItemsRepeaterElementPreparedEventArgs; using ItemsRepeater = Microsoft.UI.Xaml.Controls.ItemsRepeater; using SelectionModel = Microsoft.UI.Xaml.Controls.SelectionModel; namespace MUXControlsTestApp.Samples.Selection { public sealed partial class FlatSample : Page { ObservableCollection<string> _data = new ObservableCollection<string>(Enumerable.Range(0, 1000).Select(x => x.ToString())); public FlatSample() { this.InitializeComponent(); repeater.ItemTemplate = elementFactory; repeater.ItemsSource = _data; selectionModel.Source = _data; repeater.ElementPrepared += Repeater_ElementPrepared; repeater.ElementIndexChanged += Repeater_ElementIndexChanged; selectionModel.PropertyChanged += SelectionModel_PropertyChanged; } private void SelectionModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { var manager = sender as SelectionModel; if (e.PropertyName == "SelectedItem") { Debug.WriteLine("SelectedItem changed"); Debug.WriteLine(manager.SelectedItem); } else if (e.PropertyName == "SelectedIndices") { Debug.WriteLine("SelectedIndices changed"); for (int i = 0; i < manager.SelectedIndices.Count; i++) { Debug.WriteLine(string.Format("{0}:{1}", manager.SelectedIndices[i], manager.SelectedItems[i].ToString())); } } else if (e.PropertyName == "SelectedItems") { Debug.WriteLine("SelectedItems changed"); for (int i = 0; i < manager.SelectedIndices.Count; i++) { Debug.WriteLine(string.Format("{0}:{1}", manager.SelectedIndices[i], manager.SelectedItems[i].ToString())); } } else if (e.PropertyName == "SelectedIndex") { Debug.WriteLine("SelectedIndex changed"); Debug.WriteLine(manager.SelectedIndex); } var icpp = (ICustomPropertyProvider)selectionModel; var selectedItemProperty = icpp.GetCustomProperty("SelectedItem"); var canRead = selectedItemProperty.CanRead; var selectedItem = selectedItemProperty.GetValue(selectionModel); } private void Repeater_ElementIndexChanged(ItemsRepeater sender, ItemsRepeaterElementIndexChangedEventArgs args) { (args.Element as RepeaterItem).RepeatedIndex = args.NewIndex; } private void Repeater_ElementPrepared(ItemsRepeater sender, ItemsRepeaterElementPreparedEventArgs args) { (args.Element as RepeaterItem).RepeatedIndex = args.Index; } private void OnMultipleSelectionClicked(object sender, RoutedEventArgs e) { selectionModel.SingleSelect = multipleSelection.IsChecked.Value ? false : true; } private void OnGroupedClicked(object sender, RoutedEventArgs e) { Frame.NavigateWithoutAnimation(typeof(GroupedSample)); } private void OnBackClicked(object sender, RoutedEventArgs e) { Frame.GoBack(); } private void insert_Click(object sender, RoutedEventArgs e) { var index = int.Parse(indexPath.Text); _data.Insert(index, "Insert:" + index.ToString()); } private void remove_Click(object sender, RoutedEventArgs e) { var index = int.Parse(indexPath.Text); _data.RemoveAt(index); } private void clear_Click(object sender, RoutedEventArgs e) { _data.Move(0, 2); _data.Clear(); } } }
39.330357
131
0.635868
[ "MIT" ]
55995409/microsoft-ui-xaml
dev/Repeater/TestUI/Samples/Selection/Flat/FlatSample.xaml.cs
4,407
C#
//------------------------------------------------------------------------------ // <auto-generated> // Generated by the MSBuild WriteCodeFragment class. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute("ExRepository.Views")] [assembly: Microsoft.AspNetCore.Razor.Hosting.RazorLanguageVersionAttribute("2.1")] [assembly: Microsoft.AspNetCore.Razor.Hosting.RazorConfigurationNameAttribute("MVC-2.1")] [assembly: Microsoft.AspNetCore.Razor.Hosting.RazorExtensionAssemblyNameAttribute("MVC-2.1", "Microsoft.AspNetCore.Mvc.Razor.Extensions")]
51.071429
138
0.627972
[ "MIT" ]
Luminos-media/ExRepository
obj/Debug/netcoreapp2.1/ExRepository.RazorAssemblyInfo.cs
715
C#
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VSSDK.Tools.VsIdeTesting; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell; using EnvDTE; namespace EditProj_IntegrationTests { /// <summary> /// Integration test for package validation /// </summary> [TestClass] public class PackageTest { private delegate void ThreadInvoker(); private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } [TestMethod] [HostType("VS IDE")] public void PackageLoadTest() { UIThreadInvoker.Invoke((ThreadInvoker)delegate() { //Get the Shell Service IVsShell shellService = VsIdeTestHostContext.ServiceProvider.GetService(typeof(SVsShell)) as IVsShell; Assert.IsNotNull(shellService); //Validate package load IVsPackage package; Guid packageGuid = new Guid(rdomunozcom.EditProj.GuidList.guidEditProjPkgString); Assert.IsTrue(0 == shellService.LoadPackage(ref packageGuid, out package)); Assert.IsNotNull(package, "Package failed to load"); }); } } }
28.5
118
0.603509
[ "MIT" ]
MisterJimson/LetMeEdit
EditProj/EditProj_IntegrationTests/PackageTest.cs
1,712
C#
using Microsoft.Kinect; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace DroneKinectController { /// <summary> /// Interaktionslogik für MainWindow.xaml /// </summary> public partial class MainWindow : Window { /// <summary> /// Width of output drawing /// </summary> private const float RenderWidth = 640.0f; /// <summary> /// Height of our output drawing /// </summary> private const float RenderHeight = 480.0f; /// <summary> /// Thickness of drawn joint lines /// </summary> private const double JointThickness = 3; /// <summary> /// Thickness of body center ellipse /// </summary> private const double BodyCenterThickness = 10; /// <summary> /// Thickness of clip edge rectangles /// </summary> private const double ClipBoundsThickness = 10; /// <summary> /// Brush used to draw skeleton center point /// </summary> private readonly Brush centerPointBrush = Brushes.Blue; /// <summary> /// Brush used for drawing joints that are currently tracked /// </summary> private readonly Brush trackedJointBrush = new SolidColorBrush(Color.FromArgb(255, 68, 192, 68)); /// <summary> /// Brush used for drawing joints that are currently inferred /// </summary> private readonly Brush inferredJointBrush = Brushes.Yellow; /// <summary> /// Pen used for drawing bones that are currently tracked /// </summary> private readonly Pen trackedBonePen = new Pen(Brushes.Green, 6); /// <summary> /// Pen used for drawing bones that are currently inferred /// </summary> private readonly Pen inferredBonePen = new Pen(Brushes.Gray, 1); /// <summary> /// Active Kinect sensor /// </summary> private KinectSensor sensor; /// <summary> /// Drawing group for skeleton rendering output /// </summary> private DrawingGroup drawingGroup; /// <summary> /// Drawing image that we will display /// </summary> private DrawingImage imageSource; /// <summary> /// Initializes a new instance of the MainWindow class. /// </summary> /// private double lastCommandY; private double lastY; private DateTime lastTime; public MainWindow() { InitializeComponent(); } private void WindowLoaded(object sender, RoutedEventArgs e) { // Create the drawing group we'll use for drawing this.drawingGroup = new DrawingGroup(); // Create an image source that we can use in our image control this.imageSource = new DrawingImage(this.drawingGroup); // Display the drawing using our image control Image.Source = this.imageSource; // Look through all sensors and start the first connected one. // This requires that a Kinect is connected at the time of app startup. // To make your app robust against plug/unplug, // it is recommended to use KinectSensorChooser provided in Microsoft.Kinect.Toolkit (See components in Toolkit Browser). foreach (var potentialSensor in KinectSensor.KinectSensors) { if (potentialSensor.Status == KinectStatus.Connected) { this.sensor = potentialSensor; break; } } if (null != this.sensor) { // Turn on the skeleton stream to receive skeleton frames this.sensor.SkeletonStream.Enable(); // Add an event handler to be called whenever there is new color frame data this.sensor.SkeletonFrameReady += this.SensorSkeletonFrameReady; // Start the sensor! try { this.sensor.Start(); } catch (IOException) { this.sensor = null; } } } private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e) { Skeleton[] skeletons = new Skeleton[0]; using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame()) { if (skeletonFrame != null) { skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength]; skeletonFrame.CopySkeletonDataTo(skeletons); } } using (DrawingContext dc = this.drawingGroup.Open()) { // Draw a transparent background to set the render size dc.DrawRectangle(Brushes.Black, null, new Rect(0.0, 0.0, RenderWidth, RenderHeight)); if (skeletons.Length != 0) { foreach (Skeleton skel in skeletons) { RenderClippedEdges(skel, dc); if (skel.TrackingState == SkeletonTrackingState.Tracked) { this.DrawBonesAndJoints(skel, dc); if (this.lastCommandY == 0.0) { this.lastCommandY = skel.Joints[JointType.HandRight].Position.Y; this.lastY = this.lastCommandY; } Console.WriteLine(this.recognizeGesture(skel)); } else if (skel.TrackingState == SkeletonTrackingState.PositionOnly) { dc.DrawEllipse( this.centerPointBrush, null, this.SkeletonPointToScreen(skel.Position), BodyCenterThickness, BodyCenterThickness); } } } // prevent drawing outside of our render area this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, RenderWidth, RenderHeight)); } } private String recognizeGesture(Skeleton skel) { double minDif = 0.005; Joint handLeft = skel.Joints[JointType.HandLeft]; Console.WriteLine(handLeft.Position.Y); TimeSpan span = DateTime.Now - lastTime; long timeDiff = (long)span.TotalMilliseconds; Console.WriteLine("Time: "+timeDiff); if (timeDiff >= 500) { Console.WriteLine("Y-Diff:"+(handLeft.Position.Y - lastY)); if ((handLeft.Position.Y - lastY) > minDif) { //do nothing } else { if (handLeft.Position.Y > lastCommandY) { return "up"; } else { return "down"; } } lastY = handLeft.Position.Y; lastTime = DateTime.Now; return " nothing done"; } return " nothing done"; /*Joint handRight = skel.Joints[JointType.ElbowLeft]; Joint shoulderLeft = skel.Joints[JointType.ShoulderLeft]; return shoulderLeft.Position.Y + " " + elbowLeft.Position.Y + " " + wristLeft.Position.Y;*/ } private void DrawBonesAndJoints(Skeleton skeleton, DrawingContext drawingContext) { // Render Torso this.DrawBone(skeleton, drawingContext, JointType.Head, JointType.ShoulderCenter); this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.ShoulderLeft); this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.ShoulderRight); this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.Spine); this.DrawBone(skeleton, drawingContext, JointType.Spine, JointType.HipCenter); this.DrawBone(skeleton, drawingContext, JointType.HipCenter, JointType.HipLeft); this.DrawBone(skeleton, drawingContext, JointType.HipCenter, JointType.HipRight); // Left Arm this.DrawBone(skeleton, drawingContext, JointType.ShoulderLeft, JointType.ElbowLeft); this.DrawBone(skeleton, drawingContext, JointType.ElbowLeft, JointType.WristLeft); this.DrawBone(skeleton, drawingContext, JointType.WristLeft, JointType.HandLeft); // Right Arm this.DrawBone(skeleton, drawingContext, JointType.ShoulderRight, JointType.ElbowRight); this.DrawBone(skeleton, drawingContext, JointType.ElbowRight, JointType.WristRight); this.DrawBone(skeleton, drawingContext, JointType.WristRight, JointType.HandRight); // Left Leg this.DrawBone(skeleton, drawingContext, JointType.HipLeft, JointType.KneeLeft); this.DrawBone(skeleton, drawingContext, JointType.KneeLeft, JointType.AnkleLeft); this.DrawBone(skeleton, drawingContext, JointType.AnkleLeft, JointType.FootLeft); // Right Leg this.DrawBone(skeleton, drawingContext, JointType.HipRight, JointType.KneeRight); this.DrawBone(skeleton, drawingContext, JointType.KneeRight, JointType.AnkleRight); this.DrawBone(skeleton, drawingContext, JointType.AnkleRight, JointType.FootRight); // Render Joints foreach (Joint joint in skeleton.Joints) { Brush drawBrush = null; if (joint.TrackingState == JointTrackingState.Tracked) { drawBrush = this.trackedJointBrush; } else if (joint.TrackingState == JointTrackingState.Inferred) { drawBrush = this.inferredJointBrush; } if (drawBrush != null) { drawingContext.DrawEllipse(drawBrush, null, this.SkeletonPointToScreen(joint.Position), JointThickness, JointThickness); } } } private Point SkeletonPointToScreen(SkeletonPoint skelpoint) { // Convert point to depth space. // We are not using depth directly, but we do want the points in our 640x480 output resolution. DepthImagePoint depthPoint = this.sensor.CoordinateMapper.MapSkeletonPointToDepthPoint(skelpoint, DepthImageFormat.Resolution640x480Fps30); return new Point(depthPoint.X, depthPoint.Y); } private void DrawBone(Skeleton skeleton, DrawingContext drawingContext, JointType jointType0, JointType jointType1) { Joint joint0 = skeleton.Joints[jointType0]; Joint joint1 = skeleton.Joints[jointType1]; // If we can't find either of these joints, exit if (joint0.TrackingState == JointTrackingState.NotTracked || joint1.TrackingState == JointTrackingState.NotTracked) { return; } // Don't draw if both points are inferred if (joint0.TrackingState == JointTrackingState.Inferred && joint1.TrackingState == JointTrackingState.Inferred) { return; } // We assume all drawn bones are inferred unless BOTH joints are tracked Pen drawPen = this.inferredBonePen; if (joint0.TrackingState == JointTrackingState.Tracked && joint1.TrackingState == JointTrackingState.Tracked) { drawPen = this.trackedBonePen; } drawingContext.DrawLine(drawPen, this.SkeletonPointToScreen(joint0.Position), this.SkeletonPointToScreen(joint1.Position)); } private static void RenderClippedEdges(Skeleton skeleton, DrawingContext drawingContext) { if (skeleton.ClippedEdges.HasFlag(FrameEdges.Bottom)) { drawingContext.DrawRectangle( Brushes.Red, null, new Rect(0, RenderHeight - ClipBoundsThickness, RenderWidth, ClipBoundsThickness)); } if (skeleton.ClippedEdges.HasFlag(FrameEdges.Top)) { drawingContext.DrawRectangle( Brushes.Red, null, new Rect(0, 0, RenderWidth, ClipBoundsThickness)); } if (skeleton.ClippedEdges.HasFlag(FrameEdges.Left)) { drawingContext.DrawRectangle( Brushes.Red, null, new Rect(0, 0, ClipBoundsThickness, RenderHeight)); } if (skeleton.ClippedEdges.HasFlag(FrameEdges.Right)) { drawingContext.DrawRectangle( Brushes.Red, null, new Rect(RenderWidth - ClipBoundsThickness, 0, ClipBoundsThickness, RenderHeight)); } } } }
36.644909
151
0.553901
[ "Apache-2.0" ]
ffriedl/csc-at-hackathon
Kinect/DroneKinectControler/DroneKinectController/DroneKinectController/MainWindow.xaml.cs
14,038
C#
namespace Smart.IO.ByteMapper.Builders { using System; using Smart.IO.ByteMapper.Converters; public sealed class DecimalConverterBuilder : AbstractMapConverterBuilder<DecimalConverterBuilder> { public int Length { get; set; } public byte Scale { get; set; } public bool? UseGrouping { get; set; } public int GroupingSize { get; set; } = 3; public Padding? Padding { get; set; } public bool? ZeroFill { get; set; } public byte? Filler { get; set; } static DecimalConverterBuilder() { AddEntry(typeof(decimal), (b, _) => b.Length, (b, t, c) => b.CreateDecimalConverter(t, c)); AddEntry(typeof(decimal?), (b, _) => b.Length, (b, t, c) => b.CreateDecimalConverter(t, c)); } private IMapConverter CreateDecimalConverter(Type type, IBuilderContext context) { return new DecimalConverter( Length, Scale, UseGrouping ?? context.GetParameter<bool>(OptionsParameter.UseGrouping) ? GroupingSize : 0, Padding ?? context.GetParameter<Padding>(OptionsParameter.NumberPadding), ZeroFill ?? context.GetParameter<bool>(OptionsParameter.ZeroFill), Filler ?? context.GetParameter<byte>(OptionsParameter.NumberFiller), type); } } }
34.166667
108
0.586063
[ "MIT" ]
usausa/Smart-Net-ByteMapper
Smart.IO.ByteMapper.Options/IO/ByteMapper/Builders/DecimalConverterBuilder.cs
1,435
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using ContosoUniversity.Data; using ContosoUniversity.Models; using ContosoUniversity.Models.SchoolViewModels; namespace ContosoUniversity.Pages.Instructors { public class IndexModel : PageModel { private readonly ContosoUniversity.Data.SchoolContext _context; public IndexModel(ContosoUniversity.Data.SchoolContext context) { _context = context; } public InstructorIndexData InstructorData { get; set; } public int InstructorID { get; set; } public int CourseID { get; set; } public async Task OnGetAsync(int? id, int? courseID) { InstructorData = new InstructorIndexData(); InstructorData.Instructors = await _context.Instructors .Include(i => i.OfficeAssignment) .Include(i => i.CourseAssignments) .ThenInclude(i => i.Course) .ThenInclude(i => i.Department) .ToListAsync(); if (id != null) { InstructorID = id.Value; Instructor instructor = InstructorData.Instructors .Where(i => i.ID == id.Value) .Single(); InstructorData.Courses = instructor.CourseAssignments.Select(s => s.Course); } if (courseID != null) { CourseID = courseID.Value; var selectedCourse = InstructorData.Courses .Where(x => x.CourseID == courseID) .Single(); await _context.Entry(selectedCourse).Collection(x => x.Enrollments).LoadAsync(); foreach (Enrollment enrollment in selectedCourse.Enrollments) { await _context.Entry(enrollment).Reference(x => x.Student).LoadAsync(); } InstructorData.Enrollments = selectedCourse.Enrollments; } } } }
35.241935
96
0.586728
[ "MIT" ]
priyank89patel/AspNetCore_EFCore_Sample
src/ContosoUniversity/ContosoUniversity/Pages/Instructors/Index.cshtml.cs
2,187
C#
namespace SpeakerMeet.DTO { public class Speaker { public int Id { get; set; } public string Name { get; set; } public string Location { get; set; } public bool IsDeleted { get; set; } public string EmailAddress { get; set; } } }
23.583333
48
0.568905
[ "MIT" ]
PacktPublishing/Improving-your-C-Sharp-Skills
Chapter10/SpeakerMeet/SpeakerMeet.DTO/Speaker.cs
285
C#
using System; using UIKit; using Cirrious.MvvmCross.Touch.Views; using Cirrious.MvvmCross.Binding.BindingContext; using Cirrious.MvvmCross.Binding.Touch.Views; using ThinkOut.ViewModels; namespace ThinkOut.iPhone { public partial class IdeasView : MvxViewController { public IdeasViewModel VM { get { return base.ViewModel as IdeasViewModel; } } public IdeasView() : base("IdeasView", null) { } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. if (VM == null) return; Title = VM.Title; var source = new IdeasTableViewSource(ideasTableView); ideasTableView.Source = source; var set = this.CreateBindingSet<IdeasView, IdeasViewModel>(); set.Bind(source).To(vm => vm.IdeasVMs); set.Apply(); ideasTableView.ReloadData(); } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } } }
19.980769
80
0.711261
[ "MIT" ]
willbuildapps/ThinkOut-MobileApp
app/ThinkOut.iPhone/Views/IdeasView/IdeasView.cs
1,041
C#
namespace WxTeamsSharp.Interfaces.Messages { /// <summary> /// Can set a recipent for new Message. Can be a user Id, email, or room /// </summary> public interface ISendMessageTo { /// <summary> /// Send a message to room /// </summary> /// <param name="roomId">Room Id to send message to</param> /// <returns></returns> ISendMessageContent SendToRoom(string roomId); /// <summary> /// Send message to User Id /// </summary> /// <param name="toUserId">User Id to send message to</param> /// <returns></returns> ISendMessageContent SendToUserId(string toUserId); /// <summary> /// Send message to user email /// </summary> /// <param name="toUserEmail">User email to send message to</param> /// <returns></returns> ISendMessageContent SendToUserEmail(string toUserEmail); } }
31.533333
76
0.577167
[ "MIT" ]
FooBartn/WxTeamsSharp
src/WxTeamsSharp/Interfaces/Messages/ISendMessageTo.cs
948
C#
// *********************************************************************** // Assembly : XLabs.Sample // Author : XLabs Team // Created : 12-27-2015 // // Last Modified By : XLabs Team // Last Modified On : 01-04-2016 // *********************************************************************** // <copyright file="ExtendedScrollView.xaml.cs" company="XLabs Team"> // Copyright (c) XLabs Team. All rights reserved. // </copyright> // <summary> // This project is licensed under the Apache 2.0 license // https://github.com/XLabs/Xamarin-Forms-Labs/blob/master/LICENSE // // XLabs is a open source project that aims to provide a powerfull and cross // platform set of controls tailored to work with Xamarin Forms. // </summary> // *********************************************************************** // using System; using Xamarin.Forms; using XLabs.Forms.Controls; namespace XLabs.Sample.Pages.Controls { /// <summary> /// Class ExtendedScrollViewPage. /// </summary> public partial class ExtendedScrollViewPage : ContentPage { /// <summary> /// The imag e_ height /// </summary> private const int IMAGE_HEIGHT = 200; /// <summary> /// The _display alert /// </summary> bool _displayAlert = false; /// <summary> /// Initializes a new instance of the <see cref="ExtendedScrollViewPage"/> class. /// </summary> public ExtendedScrollViewPage() { InitializeComponent(); var container = new StackLayout() { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; var buttonToScroll = new Button() { Text = "Scroll to end" }; container.Children.Add(buttonToScroll); for (var i = 0; i < 10; i++) { container.Children.Add(new Image { Aspect = Aspect.AspectFill, Source = ImageSource.FromUri(new Uri("http://www.stockvault.net/data/2011/05/31/124348/small.jpg")), HeightRequest = IMAGE_HEIGHT }); } var sv = new ExtendedScrollView { Content = container, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; sv.Scrolled += async (arg1, arg2) => { if (!(arg2.Y > sv.Bounds.Height) || _displayAlert) { return; } _displayAlert = true; await DisplayAlert("Scroll event", "User scrolled pass bounds", "Ok", "cancel"); }; buttonToScroll.Clicked += (sender, e) => { sv.Position = new Point(sv.Position.X, sv.ContentSize.Height - IMAGE_HEIGHT); }; Content = sv; } } }
26.377551
105
0.59265
[ "Apache-2.0" ]
jdluzen/Xamarin-Forms-Labs
Samples/XLabs.Sample/Pages/Controls/ExtendedScrollView.xaml.cs
2,587
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Protocols.TestManager.Detector; using Microsoft.Protocols.TestManager.SMBDPlugin.Detector; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2; using System; using System.Collections.Generic; namespace Microsoft.Protocols.TestManager.SMBDPlugin { public class DetectionResultControl { public List<ResultItemMap> LoadDetectionInfo(DetectionInfo detectionInfo) { info = detectionInfo; AddDialects(); AddSmb2TransportSupport(); resultItemMapList.Add(dialectsItems); resultItemMapList.Add(smbdItems); return resultItemMapList; } #region Properties private DetectionInfo info = null; private const string dialectsDescription = @"""SMB Version Supported"" lists the SMB dialects supported by SUT SMB2 over SMBD implementation and at least SMB dialect 3.0 is required."; private const string smbdDescription = @"""SMB2 over SMBD Feature Supported"" lists the feature supported by SUT SMB2 over SMBD implementation"; private ResultItemMap dialectsItems = new ResultItemMap() { Header = "SMB Version Supported", Description = dialectsDescription }; private ResultItemMap smbdItems = new ResultItemMap() { Header = "SMB2 over SMBD Feature Supported", Description = smbdDescription }; private List<ResultItemMap> resultItemMapList = new List<ResultItemMap>(); #endregion #region Private functions private void AddDialects() { foreach (var dialect in info.SupportedSmbDialects) { string dialectName = null; switch (dialect) { case DialectRevision.Smb30: dialectName = "SMB 3.0"; break; case DialectRevision.Smb302: dialectName = "SMB 3.0.2"; break; case DialectRevision.Smb311: dialectName = "SMB 3.1.1"; break; default: throw new InvalidOperationException("Unexpected dialect!"); } AddResultItem(dialectsItems, dialectName, TestManager.Detector.DetectResult.Supported); } } private void AddSmb2TransportSupport() { if (info.DriverNonRdmaNICIPAddress == null || info.SUTNonRdmaNICIPAddress == null) { AddResultItem(smbdItems, "Multiple Channels", TestManager.Detector.DetectResult.DetectFail); } else { if (info.NonRDMATransportSupported && info.RDMATransportSupported) { AddResultItem(smbdItems, "Multiple Channels", TestManager.Detector.DetectResult.Supported); } else { AddResultItem(smbdItems, "Multiple Channels", TestManager.Detector.DetectResult.UnSupported); } } if (info.DriverRdmaNICIPAddress == null || info.SUTRdmaNICIPAddress == null) { AddResultItem(smbdItems, "RDMA Channel V1", TestManager.Detector.DetectResult.DetectFail); AddResultItem(smbdItems, "RDMA Channel V1 Remote Invalidate", TestManager.Detector.DetectResult.DetectFail); } else { if (info.RDMAChannelV1Supported) { AddResultItem(smbdItems, "RDMA Channel V1", TestManager.Detector.DetectResult.Supported); } else { AddResultItem(smbdItems, "RDMA Channel V1", TestManager.Detector.DetectResult.UnSupported); } if (info.RDMAChannelV1InvalidateSupported) { AddResultItem(smbdItems, "RDMA Channel V1 Remote Invalidate", TestManager.Detector.DetectResult.Supported); } else { AddResultItem(smbdItems, "RDMA Channel V1 Remote Invalidate", TestManager.Detector.DetectResult.UnSupported); } } } private void AddResultItem(ResultItemMap resultItemMap, string value, TestManager.Detector.DetectResult result) { string imagePath = string.Empty; switch (result) { case TestManager.Detector.DetectResult.Supported: imagePath = "/SMBDPlugin;component/Icons/supported.png"; break; case TestManager.Detector.DetectResult.UnSupported: imagePath = "/SMBDPlugin;component/Icons/unsupported.png"; break; case TestManager.Detector.DetectResult.DetectFail: imagePath = "/SMBDPlugin;component/Icons/undetected.png"; break; default: break; } ResultItem item = new ResultItem() { DetectedResult = result, ImageUrl = imagePath, Name = value }; resultItemMap.ResultItemList.Add(item); } #endregion } }
39.744526
192
0.582002
[ "MIT" ]
G-arj/WindowsProtocolTestSuites
TestSuites/MS-SMBD/src/Plugin/SMBDPlugin/DetectionResultControl.cs
5,447
C#
using Microsoft.Maui.Handlers; namespace Microsoft.Maui.DeviceTests { public partial class CheckBoxHandlerTests { NativeCheckBox GetNativeCheckBox(CheckBoxHandler checkBoxHandler) => (NativeCheckBox)checkBoxHandler.View; bool GetNativeIsChecked(CheckBoxHandler checkBoxHandler) => GetNativeCheckBox(checkBoxHandler).IsChecked; } }
26.615385
70
0.820809
[ "MIT" ]
lanicon/maui
src/Core/tests/DeviceTests/Handlers/CheckBox/CheckBoxHandlerTests.iOS.cs
348
C#
using System.Text; using API.Data; using API.Entities; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; namespace API.Exensions { public static class IdentityServiceExtensions { public static IServiceCollection AddIdentitySerivces(this IServiceCollection services, IConfiguration config){ services.AddIdentityCore<AppUser>(opt => { opt.Password.RequireNonAlphanumeric = false; }) .AddRoles<AppRole>() .AddRoleManager<RoleManager<AppRole>>() .AddSignInManager<SignInManager<AppUser>>() .AddRoleValidator<RoleValidator<AppRole>>() .AddEntityFrameworkStores<DataContext>() .AddDefaultTokenProviders(); //added for password token services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters{ ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["TokenKey"])), ValidateIssuer = false, ValidateAudience = false, }; }); //for policy based authroization services.AddAuthorization(opt => { opt.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin")); }); return services; } } }
37.454545
118
0.651092
[ "MIT" ]
hli261/inventoryManagementApp
backend/API/Exensions/IdentityServiceExtensions.cs
1,648
C#
// Copyright (c) SimpleIdServer. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using NETCore.Ldap.DER.Applications.Requests; using System.Collections.Generic; using System.Linq; namespace NETCore.Ldap.Authentication { public class AuthenticationHandlerFactory : IAuthenticationHandlerFactory { private readonly IEnumerable<IAuthenticationHandler> _authenticationHandlers; public AuthenticationHandlerFactory(IEnumerable<IAuthenticationHandler> authenticationHandlers) { _authenticationHandlers = authenticationHandlers; } public IAuthenticationHandler Build(BindRequestAuthenticationChoices authChoice) { return _authenticationHandlers.FirstOrDefault(a => a.AuthChoice == authChoice); } } }
36.25
107
0.754023
[ "Apache-2.0" ]
simpleidserver/NETCore.Ldap
src/NETCore.Ldap/Authentication/AuthenticationHandlerFactory.cs
872
C#
// // ITrackerRequestFactory.cs // // Authors: // Alan McGovern alan.mcgovern@gmail.com // // Copyright (C) 2019 Alan McGovern // // 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 MonoTorrent.Client.Tracker { interface ITrackerRequestFactory { AnnounceParameters CreateAnnounce (TorrentEvent clientEvent); ScrapeParameters CreateScrape (); } }
37.289474
73
0.749471
[ "MIT" ]
OneFingerCodingWarrior/monotorrent
src/MonoTorrent/MonoTorrent.Client.Tracker/ITrackerRequestFactory.cs
1,419
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TensorFlowLite; public class JumpingSquatController : MonoBehaviour { public PoseNetSample poseNetSample; public Text counterText; bool counterable = false; int count = 0; public List<ProgressBarItem> progressBarItems = new List<ProgressBarItem>(); float hipPosY; float kneePosY; float initHipPosY; float jumpThreshold = 8f; GameMode gameMode = GameMode.Ready; public Text startButtonText; void Update() { if (gameMode != GameMode.Playing) return; var results = poseNetSample.results; hipPosY = -1f; kneePosY = -1f; foreach (PoseNet.Result result in results) { if (result.confidence > 0.5f) { if (result.part == PoseNet.Part.LEFT_HIP) { hipPosY = result.y; } else if (result.part == PoseNet.Part.RIGHT_HIP) { hipPosY = result.y; } else if (result.part == PoseNet.Part.LEFT_KNEE) { kneePosY = result.y; } else if (result.part == PoseNet.Part.RIGHT_KNEE) { kneePosY = result.y; } } } if (hipPosY < 0f || kneePosY < 0f) return; if (counterable == false) { if (hipPosY > kneePosY) { initHipPosY = hipPosY; counterable = true; } } else { if (kneePosY - hipPosY > 0.1f && hipPosY - initHipPosY < jumpThreshold) { count += 1; counterText.text = count.ToString(); counterable = false; UpdateProgressBar(); if (count == 10) { gameMode = GameMode.Finished; startButtonText.text = "Finish!"; foreach (ProgressBarItem item in progressBarItems) { item.ChangeColor(new Color(49 / 255f, 102 / 255f, 1f, 1f)); } } } } } void UpdateProgressBar() { foreach (ProgressBarItem item in progressBarItems) { item.ChangeColor(Color.white); } for (int i = 0; i < count; i++) { progressBarItems[i].ChangeColor(Color.green); } } public void OnClickStartButton() { if (gameMode == GameMode.Ready) { gameMode = GameMode.Playing; startButtonText.text = "Stop"; } else if (gameMode == GameMode.Playing) { gameMode = GameMode.Ready; startButtonText.text = "Start"; Reset(); } else if (gameMode == GameMode.Finished) { gameMode = GameMode.Ready; startButtonText.text = "Start"; Reset(); } } private void Reset() { count = 0; counterText.text = count.ToString(); UpdateProgressBar(); foreach (ProgressBarItem item in progressBarItems) { item.ChangeColor(Color.white); } } }
24.652482
83
0.474108
[ "Apache-2.0" ]
ethanscho/tensorflow-edge
unity/Assets/Scripts/Controllers/JumpingSquatController.cs
3,478
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ExemploControleNavegacao { public partial class Contact : Page { protected void Page_Load(object sender, EventArgs e) { } } }
18.411765
60
0.696486
[ "MIT" ]
JonatasAfonso/formacaoAspNetWebForms201903
Aulas/Aula 03/ExemploControleNavegacao/ExemploControleNavegacao/Contact.aspx.cs
315
C#
using System; using UnityEngine; namespace SA.Android.App { /// <summary> /// A representation of settings that apply to a collection of similarly themed notifications. /// </summary> [Serializable] public class AN_NotificationChannel { [SerializeField] string m_Id; [SerializeField] string m_Name; [SerializeField] string m_Description; [SerializeField] int m_Importance; [SerializeField] string m_Sound; [SerializeField] bool m_ShowBadge; /// <summary> /// The id of the default channel for an app. This id is reserved by the system. /// /// All notifications posted from apps targeting <see cref="OS.AN_Build.VERSION_CODES.N_MR1"/> or earlier /// without a notification channel specified are posted to this channel. /// </summary> public static string DEFAULT_CHANNEL_ID = "miscellaneous"; /// <summary> /// This channel id will be used by plugin in case you havne't spesifayed any channell id with your request. /// </summary> public static string ANDROID_NATIVE_DEFAULT_CHANNEL_ID = DEFAULT_CHANNEL_ID + "_android_native_pro"; /// <summary> /// Creates a notification channel. /// </summary> /// <param name="id"> /// The id of the channel. Must be unique per package. /// The value may be truncated if it is too long. /// </param> /// <param name="name"> /// The user visible name of the channel. /// You can rename this channel when the system locale changes /// by listening for the Intent.ACTION_LOCALE_CHANGED broadcast. /// The recommended maximum length is 40 characters; the value may be truncated if it is too long. /// </param> /// <param name="importance"> /// The importance of the channel. /// This controls how interruptive notifications posted to this channel are. /// </param> public AN_NotificationChannel(string id, string name, AN_NotificationManager.Importance importance) { m_Id = id; m_Name = name; m_ShowBadge = true; m_Importance = (int)importance; } /// <summary> /// Description of this channel. /// </summary> public string Description { get => m_Description; set => m_Description = value; } /// <summary> /// The id of this channel. /// </summary> public string Id => m_Id; /// <summary> /// The user visible name of this channel. /// </summary> public string Name { get => m_Name; set => m_Name = value; } /// <summary> /// Returns whether notifications posted to this channel can appear as badges in a Launcher application. /// </summary> public bool CanShowBadge => m_ShowBadge; public string Sound { //native part will have a sound URL so we need to only return it's name get => m_Sound.Substring(m_Sound.LastIndexOf('/') + 1); set => m_Sound = value; } /// <summary> /// The user specified importance /// </summary> public AN_NotificationManager.Importance Importance => (AN_NotificationManager.Importance)m_Importance; /// <summary> /// Sets whether notifications posted to this channel can appear as application icon badges in a Launcher. /// Only modifiable before the channel is submitted to <see cref="AN_NotificationManager.CreateNotificationChannel"/> /// </summary> /// <param name="showBadge">true if badges should be allowed to be shown.</param> public void SetShowBadge(bool showBadge) { m_ShowBadge = showBadge; } } }
34.643478
125
0.588353
[ "MIT" ]
Alnirel/com.stansassets.running-dinosaur-clone
Assets/Plugins/StansAssets/NativePlugins/AndroidNativePro/Runtime/API/App/Notifications/AN_NotificationChannel.cs
3,984
C#
using System; using System.Text; using System.Collections; using UnityEngine; using System.Runtime.InteropServices; public class WebSocket { private Uri mUrl; public WebSocket(Uri url) { mUrl = url; Debug.Log("WebSocket.Constructor WebGL: url: "+url); string protocol = mUrl.Scheme; if (!protocol.Equals("ws") && !protocol.Equals("wss")) throw new ArgumentException("Unsupported protocol: " + protocol); } public void SendString(string str) { Send(Encoding.UTF8.GetBytes(str)); } public string RecvString() { // Debug.Log("WebSocket.RecvString() WebGL: start"); byte[] retval = Recv(); // Debug.Log("WebSocket.RecvString() WebGL: received byte size " + (retval == null ? "null" : retval.Length + "")); if (retval == null) return null; return Encoding.UTF8.GetString(retval); } public string GetPlatform() { return "WEBGL"; } //#if UNITY_WEBGL && !UNITY_EDITOR [DllImport("__Internal")] private static extern int SocketCreate(string url); [DllImport("__Internal")] private static extern int SocketState(int socketInstance); [DllImport("__Internal")] private static extern void SocketSend(int socketInstance, byte[] ptr, int length); [DllImport("__Internal")] private static extern void SocketRecv(int socketInstance, byte[] ptr, int length); [DllImport("__Internal")] private static extern int SocketRecvLength(int socketInstance); [DllImport("__Internal")] private static extern void SocketClose(int socketInstance); [DllImport("__Internal")] private static extern int SocketError(int socketInstance, byte[] ptr, int length); int m_NativeRef = 0; public void Send(byte[] buffer) { SocketSend(m_NativeRef, buffer, buffer.Length); } public byte[] Recv() { int length = SocketRecvLength(m_NativeRef); if (length == 0) return null; byte[] buffer = new byte[length]; SocketRecv(m_NativeRef, buffer, length); return buffer; } public IEnumerator Connect() { Debug.Log("WebSocket.Connect() WebGL: start "); m_NativeRef = SocketCreate(mUrl.ToString()); while (SocketState(m_NativeRef) == 0) { yield return 0; } Debug.Log("WebSocket.Connect() WebGL: finished "); } public void Close() { SocketClose(m_NativeRef); } public string error { get { const int bufsize = 1024; byte[] buffer = new byte[bufsize]; int result = SocketError(m_NativeRef, buffer, bufsize); if (result == 0) return null; return Encoding.UTF8.GetString(buffer); } } }
26.009091
122
0.60713
[ "MIT" ]
IndieSquare/BtcpayUnitySDK
WebSocketUnityWebGL/WebSocketUnity.cs
2,863
C#
using DFC.Content.Pkg.Netcore.Data.Models; using System; using System.Collections.Generic; namespace DFC.Content.Pkg.Netcore.Data.Contracts { public interface IBaseContentItemModel : IApiDataModel { ContentLinksModel? ContentLinks { get; set; } IList<IBaseContentItemModel> ContentItems { get; set; } Guid? ItemId { get; set; } string? ContentType { get; set; } } }
23.055556
63
0.684337
[ "MIT" ]
SkillsFundingAgency/dfc-content-pkg-netcore
dfc-content-pkg-netcore/Data/Contracts/IBaseContentItemModel.cs
417
C#
using DSIS.Scheme.Impl; using DSIS.Scheme.Impl.Actions.Line; using DSIS.UI.Application.Progress; using DSIS.UI.UI; using DSIS.UI.Wizard; using EugenePetrenko.Shared.Core.Ioc.Api; namespace DSIS.UI.Application.Doc.Actions.Segments { [DocumentAction(Caption = "Create Segment")] public class CreateLineAction : IDocumentAction { [Autowire] private IApplicationDocument myDocument { get; set; } [Autowire] private ITypeInstantiator myFactory { get; set; } [Autowire] private IWizardFormPresenter myPresenter { get; set; } [Autowire] private IContextOperationExecution myExec { get; set; } public bool Compatible { get { return !myDocument.Content.ContainsKey(Keys.LineKey); } } public void Apply() { myExec.ExecuteAsync("Create Line", (op, pi) => { var space = myDocument.Space; var action = new LineInitialAction(1e-3, space.AreaLeftPoint, space.AreaRightPoint); op.ChangeDocument(action.Apply(myDocument.Content)); }); } } }
30.902439
130
0.566693
[ "Apache-2.0" ]
jonnyzzz/phd-project
dsis/src/UIs/UI.Application/src/Doc/Actions/Segments/CreateLineAction.cs
1,267
C#
// // Copyright (c) 2008-2011, Kenneth Bell // // 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 LineOS.NTFS.Compression { /// <summary> /// Possible results of attempting to compress data. /// </summary> /// <remarks> /// A compression routine <i>may</i> return <c>Compressed</c>, even if the data /// was 'all zeros' or increased in size. The <c>AllZeros</c> and <c>Incompressible</c> /// values are for algorithms that include special detection for these cases. /// </remarks> public enum CompressionResult { /// <summary> /// The data compressed succesfully. /// </summary> Compressed, /// <summary> /// The data was all-zero's. /// </summary> AllZeros, /// <summary> /// The data was incompressible (could not fit into destination buffer). /// </summary> Incompressible } }
37.692308
92
0.680612
[ "MIT" ]
Twometer/LineOS
LineOS/NTFS/Compression/CompressionResult.cs
1,962
C#
using System; using System.ComponentModel.DataAnnotations.Schema; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace bestdealpharma.com.Data.Models { public class OrderDetail { public int Id { get; set; } public string Title { get; set; } public string Manufacturer { get; set; } public string Strength { get; set; } public string Quantity { get; set; } public decimal Price { get; set; } public bool IsGeneric { get; set; } public bool OnlyRx { get; set; } public int Amount { get; set; } public decimal TotalPrice { get; set; } [ForeignKey("Order")] public int OrderId { get; set; } public int Status { get; set; } public string StatusText { get; set; } public Order Order { get; set; } } }
28.071429
58
0.667939
[ "MIT" ]
ersensari/bestdealpharma.com
Data/Models/OrderDetail.cs
786
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Windows; namespace SaveRestoreForWpf { /// <summary> /// App.xaml の相互作用ロジック /// </summary> public partial class App : Application { } }
17
42
0.692042
[ "MIT" ]
koichi210/CS_Wpf
SaveRestoreForWpf/SaveRestoreForWpf/App.xaml.cs
309
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; namespace KutuphaneOtomosyonu { public partial class PersonelDuzenlemeVeSilme : Form { public PersonelDuzenlemeVeSilme() { InitializeComponent(); } OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\bin\\Debug\\KutuphaneOtomasyonu.mdb"); int satir; string gonderilen; private void verigoster(string cumlecik) { listView1.Items.Clear(); OleDbCommand cmd = new OleDbCommand(cumlecik, conn); OleDbDataReader rd = cmd.ExecuteReader(); while (rd.Read()) { if(lwpasaport.Width>lwtc.Width) { if (rd["pasaportkimlik"].ToString().Length != 0) { ListViewItem ekle = new ListViewItem(); ekle.Text = rd["personelid"].ToString(); ekle.SubItems.Add(rd["tckimlik"].ToString()); ekle.SubItems.Add(rd["pasaportkimlik"].ToString()); ekle.SubItems.Add(rd["adi"].ToString()); ekle.SubItems.Add(rd["soyadi"].ToString()); ekle.SubItems.Add(rd["gorevi"].ToString()); ekle.SubItems.Add(rd["telefon"].ToString()); ekle.SubItems.Add(rd["mail"].ToString()); listView1.Items.Add(ekle); } } else { if (rd["tckimlik"].ToString().Length != 0) { ListViewItem ekle = new ListViewItem(); ekle.Text = rd["personelid"].ToString(); ekle.SubItems.Add(rd["tckimlik"].ToString()); ekle.SubItems.Add(rd["pasaportkimlik"].ToString()); ekle.SubItems.Add(rd["adi"].ToString()); ekle.SubItems.Add(rd["soyadi"].ToString()); ekle.SubItems.Add(rd["gorevi"].ToString()); ekle.SubItems.Add(rd["telefon"].ToString()); ekle.SubItems.Add(rd["mail"].ToString()); listView1.Items.Add(ekle); } } } } private void yabancimi_CheckedChanged(object sender, EventArgs e) { if (yabancimi.Checked) { label23.Text = "Pasaport Numarası:"; tbpasaport.Visible = true; tbtc.Visible = false; tbtc.Clear(); tbpasaport.Focus(); lwpasaport.Width = 80; lwtc.Width = 0; gonderilen = "select * from personel where pasaportkimlik like'" + tbpasaport.Text + "%'"; verigoster(gonderilen); } else { label23.Text = "TC Kimklik Numarası:"; tbtc.Visible = true; tbpasaport.Visible = false; tbpasaport.Clear(); tbtc.Focus(); lwpasaport.Width = 0; lwtc.Width = 80; gonderilen = "select * from personel where tckimlik like'" + tbtc.Text + "%'"; verigoster(gonderilen); } } private void btnislevler_Click(object sender, EventArgs e) { if (Ana_Sayfa.personelduzenlmemi == false) { DialogResult cevap = MessageBox.Show("Emin misiniz?", "", MessageBoxButtons.YesNo); if (cevap == DialogResult.Yes) { OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; cmd.CommandText = "delete from personel where personelid=@personelid"; cmd.Parameters.AddWithValue("@personelid", satir); cmd.ExecuteNonQuery(); tbpersonelid.Clear(); tbtel.Clear(); tbsoyisim.Clear(); tbtc.Clear(); tbpasaport.Clear(); tbmail.Clear(); tbisim.Clear(); tbadres.Clear(); sorumlu.Checked = memur.Checked = diger.Checked = false; fotografpersonelekleme.ImageLocation= ""; gonderilen = "select * from personel"; verigoster(gonderilen); MessageBox.Show("Kaydınız Silindi."); } } else { string gorevi1; if (sorumlu.Checked) gorevi1 = sorumlu.Text; else if (memur.Checked) gorevi1 = memur.Text; else gorevi1 = diger.Text; if (tbisim.Text.Length != 0 && tbsoyisim.Text.Length != 0 && tbadres.Text.Length != 0 && tbtel.Text.Length == 14 && tbpersonelid.Text.Length != 0 && (memur.Checked || diger.Checked || sorumlu.Checked) && fotografpersonelekleme.ImageLocation.ToString().Length != 0) { OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; cmd.CommandText = "update personel set adi=@adi,soyadi=@soyadi,mail=@mail,telefon=@telefon,adres=@adres,gorevi=@gorevi,fotograf=@fotograf where personelid=@personelid"; cmd.Parameters.AddWithValue("@adi", tbisim.Text); cmd.Parameters.AddWithValue("@soyadi", tbsoyisim.Text); cmd.Parameters.AddWithValue("@mail", tbmail.Text); cmd.Parameters.AddWithValue("@telefon", tbtel.Text); cmd.Parameters.AddWithValue("@adres", tbadres.Text); cmd.Parameters.AddWithValue("@gorevi", gorevi1); cmd.Parameters.AddWithValue("@fotograf", fotografpersonelekleme.ImageLocation.ToString()); cmd.Parameters.AddWithValue("@personelid", int.Parse(tbpersonelid.Text)); cmd.ExecuteNonQuery(); gonderilen = "select * from personel"; verigoster(gonderilen); MessageBox.Show("Kayıt Güncellenmiştir."); tbisim.Clear(); tbsoyisim.Clear(); tbmail.Clear(); tbadres.Clear(); tbtel.Clear(); sorumlu.Checked = memur.Checked = diger.Checked = false; tbpersonelid.Clear(); fotografpersonelekleme.ImageLocation = Application.StartupPath + "\\fotograflar\\personel\\man-user.png"; } else { gonderilen = "select * from personel"; verigoster(gonderilen); MessageBox.Show("Lütfen yıldızlı alanları doldurunuz.", "Dikkat!" + MessageBoxIcon.Warning); } } } private void btngazetefotograf_Click(object sender, EventArgs e) { openFileDialog1.InitialDirectory = Application.StartupPath + "\\fotograflar\\personel\\"; DialogResult konum = openFileDialog1.ShowDialog(); fotografpersonelekleme.ImageLocation = openFileDialog1.FileName; } private void PersonelDuzenlemeVeSilme_Load(object sender, EventArgs e) { if (conn.State == ConnectionState.Closed) conn.Open(); dtarihi.MaxDate = DateTime.Now.AddYears(-18); lwpasaport.Width = 0; gonderilen = "select * from personel"; verigoster(gonderilen); btnislevler.Enabled = false; fotografpersonelekleme.ImageLocation = Application.StartupPath + "\\fotograflar\\personel\\man-user.png"; if (Ana_Sayfa.personelduzenlmemi==false) { this.Text = "Personel Silme"; btnislevler.Text = "Sil"; } else { this.Text = "Personel Düzenleme"; btnislevler.Text = "Güncelle"; } } private void listView1_SelectedIndexChanged(object sender, EventArgs e) { btnislevler.Enabled = true; if (Ana_Sayfa.personelduzenlmemi) { tbisim.ReadOnly = tbsoyisim.ReadOnly=tbpersonelid.ReadOnly = tbmail.ReadOnly = tbadres.ReadOnly = false; tbpersonelid.ReadOnly = true; dtarihi.Enabled = tbtel.Enabled = sorumlu.Enabled = memur.Enabled = diger.Enabled = btnpersonelfotograf.Enabled = true; } try { satir = int.Parse(listView1.SelectedItems[0].SubItems[0].Text); OleDbCommand cmd = new OleDbCommand("select * from personel where personelid=" + satir, conn); OleDbDataReader rd = cmd.ExecuteReader(); while (rd.Read()) { tbisim.Text = rd["adi"].ToString(); tbsoyisim.Text = rd["soyadi"].ToString(); dtarihi.Text = rd["dtarihi"].ToString(); tbmail.Text = rd["mail"].ToString(); tbtel.Text = rd["telefon"].ToString(); tbadres.Text = rd["adres"].ToString(); tbpersonelid.Text = rd["personelid"].ToString(); if (rd["gorevi"].ToString() == sorumlu.Text) sorumlu.Checked = true; else if (rd["gorevi"].ToString() == memur.Text) memur.Checked = true; else diger.Checked = true; fotografpersonelekleme.ImageLocation = rd["fotograf"].ToString(); } } catch { } } private void tbpasaport_TextChanged(object sender, EventArgs e) { if (yabancimi.Checked) { if (tbpasaport.Text.Length != 0) { gonderilen = "select * from personel where pasaportkimlik like'" + tbpasaport.Text + "%'"; verigoster(gonderilen); } else { gonderilen = "select * from personel"; verigoster(gonderilen); } } else { gonderilen = "select * from personel where tckimlik like'" + tbtc.Text + "%'"; verigoster(gonderilen); } } private void tbtc_TextChanged(object sender, EventArgs e) { if (yabancimi.Checked==false) { if (tbtc.Text.Length != 0) { gonderilen= "select * from personel where tckimlik like'" + tbtc.Text + "%'"; verigoster(gonderilen); } else { gonderilen = "select * from personel"; verigoster(gonderilen); } } else { gonderilen = "select * from personel where pasaportkimlik like'" + tbpasaport.Text + "%'"; verigoster(gonderilen); } } private void tbpersonelid_TextChanged(object sender, EventArgs e) { //personelidi güncellettir ama aynı personelidlere izin verme } } }
41.546713
280
0.488881
[ "Apache-2.0" ]
receppolat/LibraryOtomation
KutuphaneOtomosyonu/PersonelDuzenlemeVeSilme.cs
12,025
C#
using System; using System.Collections.Generic; using System.Linq; public class Engine { private IInputReader reader; private IOutputWriter writer; private HeroManager heroManager; public Engine(IInputReader reader, IOutputWriter writer, HeroManager heroManager) { this.reader = reader; this.writer = writer; this.heroManager = heroManager; } public void Run() { bool isRunning = true; while (isRunning) { string inputLine = this.reader.ReadLine(); List<string> arguments = parseInput(inputLine); this.writer.WriteLine(processInput(arguments)); isRunning = !ShouldEnd(inputLine); } } private List<string> parseInput(string input) { return input.Split(new[] { ' ' },StringSplitOptions.RemoveEmptyEntries).ToList(); } private string processInput(List<string> arguments) { string command = arguments[0]; arguments.RemoveAt(0); Type commandType = Type.GetType(command + "Command"); var constructor = commandType.GetConstructor(new Type[] { typeof(IList<string>), typeof(IManager) }); ICommand cmd = (ICommand)constructor.Invoke(new object[] { arguments, this.heroManager }); return cmd.Execute(); } private bool ShouldEnd(string inputLine) { return inputLine.Equals("Quit"); } }
27.901961
109
0.638791
[ "MIT" ]
vasilchavdarov/SoftUniHomework
Hell-Skeleton/Hell/Core/Engine.cs
1,425
C#
using System; using System.Collections.Generic; using System.Text; using Utilities; namespace Model.Validation.Functions { internal sealed class FdaFunctionBaseValidator: IValidator<IFdaFunction> { public IMessageLevels IsValid(IFdaFunction obj, out IEnumerable<IMessage> msgs) { msgs = ReportErrors(obj); return msgs.Max(); } public IEnumerable<IMessage> ReportErrors(IFdaFunction obj) { List<IMessage> msgs = new List<IMessage>(); if (!obj.ParameterType.IsFunction() && !obj.IsMetricFunction()) msgs.Add(IMessageFactory.Factory( IMessageLevels.Error, $"The specified parameter: {obj.ParameterType.Print(true)} is not function.")); if (obj.XSeries.State > IMessageLevels.NoErrors) msgs.Add(IMessageFactory.Factory(obj.XSeries.State, $"The function domain contains {obj.XSeries.State.ToString()}s. Check details for more information.", $"The {obj.XSeries.Label} contains the following validation messages: \r\n{obj.XSeries.Messages.PrintTabbedListOfMessages()}")); if (obj.YSeries.State > IMessageLevels.NoErrors) msgs.Add(IMessageFactory.Factory(obj.YSeries.State, $"The function range contains {obj.YSeries.State.ToString()}s. Check details for more information.", $"The {obj.YSeries.Label} contains the following validation messages: \r\n{obj.YSeries.Messages.PrintTabbedListOfMessages()}")); return msgs; } } }
51.4
144
0.6738
[ "MIT" ]
HydrologicEngineeringCenter/HEC-FDA
Model/Validation/Functions/FdaFunctionBaseValidator.cs
1,544
C#
using System.Text; namespace System { public static partial class Extensions { public static StringBuilder ExtractOperator(this StringBuilder @this) { return @this.ExtractOperator(0); } public static StringBuilder ExtractOperator(this StringBuilder @this, out int endIndex) { return @this.ExtractOperator(0, out endIndex); } public static StringBuilder ExtractOperator(this StringBuilder @this, int startIndex) { int endIndex; return @this.ExtractOperator(startIndex, out endIndex); } public static StringBuilder ExtractOperator(this StringBuilder @this, int startIndex, out int endIndex) { // WARNING: This method support custom operator for .NET Runtime Compiler // An operator can be any sequence of supported operator character var sb = new StringBuilder(); var pos = startIndex; while(pos<@this.Length) { var ch = @this[pos]; pos++; switch(ch) { case '`': case '~': case '!': case '#': case '$': case '%': case '^': case '&': case '*': case '(': case ')': case '-': case '_': case '=': case '+': case '[': case ']': case '{': case '}': case '|': case ':': case ';': case ',': case '.': case '<': case '>': case '?': case '/': sb.Append(ch); break; default: if(sb.Length>0) { endIndex=pos-2; return sb; } endIndex=-1; return null; } } if(sb.Length>0) { endIndex=pos; return sb; } endIndex=-1; return null; } } }
18.011111
105
0.559531
[ "MIT" ]
Conscience-Information-Technologies/OpenApiValidator
Conscience.Extensions/System/System.Text.StringBuilder/Extract/ExtractOperator.cs
1,623
C#
namespace _4.Files { using System; using System.Collections.Generic; using System.Linq; public class Files { public static void Main() { Dictionary<string, Dictionary<string, long>> filesByRoot = new Dictionary<string, Dictionary<string, long>>(); int n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { string[] routeParams = Console.ReadLine().Split('\\'); string root = routeParams[0]; string[] fileWithSize = routeParams[routeParams.Length - 1].Split(';'); string fileNameWithExtensions = fileWithSize[0]; long fileSize = long.Parse(fileWithSize[1]); if (!filesByRoot.ContainsKey(root)) { filesByRoot.Add(root, new Dictionary<string, long>()); } if (!filesByRoot[root].ContainsKey(fileNameWithExtensions)) { filesByRoot[root].Add(fileNameWithExtensions, fileSize); } else { filesByRoot[root][fileNameWithExtensions] = fileSize; } } string[] queryParams = Console.ReadLine().Split(' '); string queryExtensions = queryParams[0]; string queryRoot = queryParams[2]; if (filesByRoot.ContainsKey(queryRoot)) { Dictionary<string, long> foundFiles = filesByRoot[queryRoot]; foreach (var file in foundFiles.OrderByDescending(x => x.Value).ThenBy(x => x.Key)) { if (file.Key.EndsWith(queryExtensions)) { Console.WriteLine("{0} - {1} KB", file.Key, file.Value); } } } else { Console.WriteLine("No"); } } } }
31.09375
122
0.484422
[ "MIT" ]
TsvetanNikolov123/CSharp---Programming-Fundamentals-Extended
37 Exam Preparation II/4.Files/Files.cs
1,992
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using Claim.Asserts; using Claim.Exceptions; namespace Claim { public abstract class Request<TRequest> where TRequest : Request<TRequest> { private readonly HttpClient _httpClient; private readonly HttpRequestMessage _httpRequest; protected ICollection<IAssert> Asserts = new List<IAssert>(); public TRequest AssertStatus(HttpStatusCode expectedStatusCode) { AddAssert(new StatusCodeAssert(expectedStatusCode)); return this as TRequest; } public TRequest AssertContainsHeader(string name, IEnumerable<string> values) { AddAssert(new ContainsHeaderAssert(name, values)); return this as TRequest; } public TRequest AssertContainsHeader(string name, string value) { AddAssert(new ContainsHeaderAssert(name, new []{ value })); return this as TRequest; } public TRequest AssertJson(object expectedResponseStructure, PropertyComparison? propertyComparison = null) { AddAssert(new JsonAssert(expectedResponseStructure, propertyComparison)); return this as TRequest; } public TRequest AssertJson(string expectedResponseStructure, PropertyComparison? propertyComparison = null) { AddAssert(new JsonAssert(expectedResponseStructure, propertyComparison)); return this as TRequest; } public TRequest AddAssert(IAssert assert) { Asserts.Add(assert); return this as TRequest; } public void Execute() { BeforeSend(_httpRequest); var response = Send(); var result = Asserts.Select(a => a.Assert(response)); var failedAsserts = result.Where(x => x.Status == ResultStatus.Failed).ToList(); if (failedAsserts.Any()) throw new AssertFailedException(failedAsserts); } protected virtual void BeforeSend(HttpRequestMessage httpRequest) { } protected Request(HttpMethod httpMethod, string uri, Func<HttpClient> httpClientFactory) { _httpClient = (httpClientFactory ?? DefaultHttpClientFactory)(); _httpRequest = new HttpRequestMessage(httpMethod, uri); } private Response Send() { // Use the CancellationToken override so we can mock the HttpClient by overriding SendAsync var response = _httpClient.SendAsync(_httpRequest, new CancellationToken()).Result; return new Response { ResponseMessage = response, ResponseContent = response?.Content?.ReadAsByteArrayAsync().Result }; } private static HttpClient DefaultHttpClientFactory() => new HttpClient(); } }
33.177778
115
0.641996
[ "MIT" ]
joakimthun/claim
src/Claim/Request.cs
2,988
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NUnit.Framework; namespace Azure.AI.TextAnalytics.Samples { public partial class TextAnalyticsSamples { [Test] public async Task AnalyzeSentimentWithOpinionMiningAsync() { string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; // Instantiate a client that will be used to call the service. var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey), CreateSampleOptions()); string reviewA = @"The food and service were unacceptable, but the concierge were nice. After talking to them about the quality of the food and the process to get room service they refunded the money we spent at the restaurant and gave us a voucher for nearby restaurants."; string reviewB = @"The rooms were beautiful. The AC was good and quiet, which was key for us as outside it was 100F and our baby was getting uncomfortable because of the heat. The breakfast was good too with good options and good servicing times. The thing we didn't like was that the toilet in our bathroom was smelly. It could have been that the toilet was not cleaned before we arrived. Either way it was very uncomfortable. Once we notified the staff, they came and cleaned it and left candles."; string reviewC = @"Nice rooms! I had a great unobstructed view of the Microsoft campus but bathrooms were old and the toilet was dirty when we arrived. It was close to bus stops and groceries stores. If you want to be close to campus I will recommend it, otherwise, might be better to stay in a cleaner one."; var documents = new List<string> { reviewA, reviewB, reviewC }; var options = new AnalyzeSentimentOptions() { IncludeOpinionMining = true }; Response<AnalyzeSentimentResultCollection> response = await client.AnalyzeSentimentBatchAsync(documents, options: options); AnalyzeSentimentResultCollection reviews = response.Value; Dictionary<string, int> complaints = GetComplaint(reviews); var negativeAspect = complaints.Aggregate((l, r) => l.Value > r.Value ? l : r).Key; Console.WriteLine($"Alert! major complaint is *{negativeAspect}*"); Console.WriteLine(); Console.WriteLine("---All complaints:"); foreach (KeyValuePair<string, int> complaint in complaints) { Console.WriteLine($" {complaint.Key}, {complaint.Value}"); } } private Dictionary<string, int> GetComplaint(AnalyzeSentimentResultCollection reviews) { var complaints = new Dictionary<string, int>(); foreach (AnalyzeSentimentResult review in reviews) { foreach (SentenceSentiment sentence in review.DocumentSentiment.Sentences) { foreach (SentenceOpinion opinion in sentence.Opinions) { if (opinion.Target.Sentiment == TextSentiment.Negative) { complaints.TryGetValue(opinion.Target.Text, out var value); complaints[opinion.Target.Text] = value + 1; } } } } return complaints; } } }
46.976471
135
0.584773
[ "MIT" ]
AikoBB/azure-sdk-for-net
sdk/textanalytics/Azure.AI.TextAnalytics/tests/samples/Sample2.1_AnalyzeSentimentWithOpinionMiningAsync.cs
3,995
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("RealEstateCRM.DataAccessLayer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RealEstateCRM.DataAccessLayer")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b235c579-33eb-42f1-ad45-5e13ebf49f6f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.540541
84
0.752454
[ "MIT" ]
1804-Apr-USFdotnet/Living-Social-Project2
RealEstateCRMAPI/RealEstateCRM.DataAccessLayer/Properties/AssemblyInfo.cs
1,429
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using UCDArch.Core.PersistanceSupport; namespace Catbert4.Tests.Core { public class QueryExtensionFakes : IQueryExtensionProvider { public IQueryable<T> Cache<T>(IQueryable<T> queryable, string region) { return queryable; } public IQueryable<TOriginal> Fetch<TOriginal, TRelated>(IQueryable<TOriginal> queryable, Expression<Func<TOriginal, TRelated>> relationshipProperty, params Expression<Func<TRelated, TRelated>>[] thenFetchRelationship) { return queryable; } public IQueryable<TOriginal> FetchMany<TOriginal, TRelated>(IQueryable<TOriginal> queryable, Expression<Func<TOriginal, IEnumerable<TRelated>>> relationshipCollection, params Expression<Func<TRelated, IEnumerable<TRelated>>>[] thenFetchManyRelationship) { return queryable; } public IEnumerable<T> ToFuture<T>(IQueryable<T> queryable) { return queryable; } } }
35.903226
262
0.677448
[ "MIT" ]
ucdavis/Catbert
Catbert4.Tests/Core/QueryExtensionFakes.cs
1,115
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tool.BLL; namespace Tool.Command { abstract class AbstractMoveToHomeScreenExecutorMFCTP : AbstractCommandExecutor { protected ScreenIdentify homeScreenIdentify; protected AbstractCommandExecutor keyClicker; protected AbstractCommandExecutor rawScreenLoader; public AbstractMoveToHomeScreenExecutorMFCTP(ScreenIdentify homeScreenIdentify) { this.homeScreenIdentify = homeScreenIdentify; this.rawScreenLoader = StaticCommandExecutorList.get(CommandList.list_r); this.keyClicker = StaticCommandExecutorList.get(CommandList.click_k); } public override void execute(object param) { try { cmdMutex.WaitOne(); StaticLog4NetLogger.commandExecutorLogger.Info("move ~ start."); backToHomeScreen(); StaticLog4NetLogger.commandExecutorLogger.Info("move ~ succeed."); cmdMutex.ReleaseMutex(); } catch (FTBAutoTestException excp) { StaticLog4NetLogger.commandExecutorLogger.Warn("move ~ failed.\nReason:" + excp.Message); cmdMutex.ReleaseMutex(); throw excp; } } protected abstract void waitForBackHome(); private void backToHomeScreen() { ////1step, check current screen //if (true == checkHome()) // return;//change Home over //2step, try to push home Key keyClicker.execute(Machine.MFCTPKeyCode.HOME_KEY); if (true == checkHome()) return;//change Home over //3step, try to wait for back home waitForBackHome(); if (true == checkHome()) return;//change Home over throw new FTBAutoTestException("Can't go to home screen."); } protected bool checkHome() { //Get current screen Screen currentScreen = new Screen(); rawScreenLoader.execute(currentScreen); //Check Screen return homeScreenIdentify.Equals(currentScreen.getIdentify()); } } }
32.150685
105
0.598637
[ "MIT" ]
LifeIsABoat/AutoTestV1
AutoTest/Command/AbstractMoveToHomeScreenExecutorMFCTP.cs
2,347
C#
using NAudio.CoreAudioApi; using NAudio.Wave; using SoundMap.NoteWaveProviders; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Xml.Serialization; namespace SoundMap.Settings { [Serializable] public class PreferencesSettings: Observable, ICloneable { private static AudioOutput[] FAudioOutputs = null; private static AudioOutput FDefaultAudioOutput = null; private static readonly Dictionary<string, Tuple<NoteWaveAttribute, Type>> FNoteProviders = new Dictionary<string, Tuple<NoteWaveAttribute, Type>>(); private MidiSettings FMidi = null; private OpenCLSettings FOpenCL = null; private string FNoteProviderName = null; [XmlIgnore] public AudioOutput[] AudioOutputs => FAudioOutputs; [XmlIgnore] public AudioOutput DefaultAudioOutput => FDefaultAudioOutput; public PreferencesSettings() { if (FAudioOutputs == null) InitAudio(); } private void InitAudio() { if (FAudioOutputs != null) foreach (var _ao in FAudioOutputs) _ao.Dispose(); List<AudioOutput> aos = new List<AudioOutput>(); FDefaultAudioOutput = null; using (var e = new MMDeviceEnumerator()) { string defaultId = e.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).ID; foreach (MMDevice d in e.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active)) { var ao = new AudioOutput(d); if (d.ID == defaultId) FDefaultAudioOutput = ao; aos.Add(ao); } } if (AsioOut.isSupported()) foreach (var n in AsioOut.GetDriverNames()) aos.Add(new AudioOutput(n)); FAudioOutputs = aos.ToArray(); if (FDefaultAudioOutput == null) FDefaultAudioOutput = FAudioOutputs.First(); } public string SelectedAudioOutputName { get; set; } private int? FLatency = null; private int? FSampleRate = null; private string FChannel = null; [XmlIgnore] public AudioOutput SelectedAudioOutput { get { var r = AudioOutputs.FirstOrDefault(ao => ao.Name == SelectedAudioOutputName); if (r == null) return DefaultAudioOutput; return r; } set { if (value == null) SelectedAudioOutputName = null; else SelectedAudioOutputName = value.Name; NotifyPropertyChanged(nameof(SampleRate)); NotifyPropertyChanged(nameof(Channel)); NotifyPropertyChanged(nameof(Latency)); NotifyPropertyChanged(nameof(LatencyEnabled)); NotifyPropertyChanged(nameof(SelectedAudioOutput)); } } public IWavePlayer CreateOutput() => SelectedAudioOutput.CreateOutput(this); public int Latency { get { if (FLatency.HasValue) return FLatency.Value; return SelectedAudioOutput.DefaultLatency; } set { if (value == 0) FLatency = SelectedAudioOutput.DefaultLatency; else FLatency = value; } } public bool LatencyEnabled { get => SelectedAudioOutput.LatencyEnbled; } public int Channels => 2; public int SampleRate { get { var sao = SelectedAudioOutput; if (FSampleRate.HasValue) { if (sao.SampleRates.Contains(FSampleRate.Value)) return FSampleRate.Value; } return sao.SampleRates.First(); } set => FSampleRate = value; } public string Channel { get { var ao = SelectedAudioOutput; if (ao.Channels.Contains(FChannel)) return FChannel; return ao.Channels.First(); } set => FChannel = value; } object ICloneable.Clone() { return Clone(); } public PreferencesSettings Clone() { var r = new PreferencesSettings(); r.SelectedAudioOutputName = this.SelectedAudioOutputName; r.FLatency = this.FLatency; r.FSampleRate = this.FSampleRate; r.FChannel = this.FChannel; r.Midi = this.Midi.Clone(); r.OpenCL = this.OpenCL.Clone(); r.NoteProviderName = this.NoteProviderName; return r; } public MidiSettings Midi { get { if (FMidi == null) FMidi = new MidiSettings(); return FMidi; } set => FMidi = value; } public OpenCLSettings OpenCL { get { if (FOpenCL == null) FOpenCL = new OpenCLSettings(); return FOpenCL; } set => FOpenCL = value; } public string NoteProviderName { get { if (FNoteProviderName == null) FNoteProviderName = NoteProviders.First().Key; return FNoteProviderName; } set => FNoteProviderName = value; } [XmlIgnore] public Type NoteProviderType { get { foreach (var kv in NoteProviders) if (kv.Key == NoteProviderName) return kv.Value.Item2; return null; } set { foreach (var kv in NoteProviders) if (kv.Value.Item2.Equals(value)) { NoteProviderName = kv.Key; break; } } } public static Dictionary<string, Tuple<NoteWaveAttribute, Type>> NoteProviders { get { if (FNoteProviders.Count == 0) { foreach (var t in new[] { typeof(MTNoteWaveProvider), typeof(STNoteWaveProvider), typeof(OpenCLWaveProvider) }) { var dAttr = t.GetCustomAttributes(typeof(NoteWaveAttribute), false).Cast<NoteWaveAttribute>().FirstOrDefault(); Debug.Assert(dAttr != null); FNoteProviders.Add(dAttr.Name, new Tuple<NoteWaveAttribute, Type>(dAttr, t)); } } return FNoteProviders; } } public NoteWaveProvider CreateNoteProvider() { if (!NoteProviders.TryGetValue(NoteProviderName, out var v)) v = NoteProviders.First().Value; return (NoteWaveProvider)Activator.CreateInstance(v.Item2); } /// <summary> /// Scan/update audio devices /// </summary> public void RescanDevices() { InitAudio(); MidiSettings.UpdateDevices(); } } }
22.425197
151
0.676088
[ "MIT" ]
Axaparta/SoundMap
Settings/PreferencesSettings.cs
5,698
C#
#region license // Copyright (c) 2021, andreakarasho // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. 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. // 3. All advertising materials mentioning features or use of this software // must display the following acknowledgement: // This product includes software developed by andreakarasho - https://github.com/andreakarasho // 4. Neither the name of the copyright holder 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 ''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 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. #endregion using System.Runtime.InteropServices; namespace StbTextEditSharp { [StructLayout(LayoutKind.Sequential)] public struct UndoRecord { public int where; public int insert_length; public int delete_length; public int char_storage; } }
46.022222
98
0.760502
[ "MIT" ]
DarkLotus/Mythik-UOSpawn-Editor
Assets/Scripts/ClassicUO/Utility/StbTextedit/UndoRecord.cs
2,071
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using FSS.Omnius.Modules.CORE; using FSS.Omnius.Modules.Entitron.Entity; using FSS.Omnius.Modules.Entitron.Entity.Persona; using FSS.Omnius.Modules.Nexus.Service; using Newtonsoft.Json.Linq; namespace FSS.Omnius.Modules.Persona { public class MasterWSO : MasterAuth, IMasterAuth { public override int Id => 3; public override string Name => "WSO"; public override bool AllowLogout => false; public override IPersonaAuth CreateAuth(User user) { return new AuthWSO(user); } public override void Refresh() { var users = GetUserList(); UpdateUsers(users); } public override void RedirectToLogin(HttpContext context) { context.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden; } private List<User> GetUserList() { /// INIT COREobject core = COREobject.i; DBEntities context = core.Context; // NexusWSService webService = new NexusWSService(); object[] parameters = new[] { "Auction_User" }; JToken results = webService.CallWebService("RWE_WSO_SOAP", "getUserListOfRole", parameters); var x = results.Children().First().Value<String>(); //get the list of users names and add it to the list. IEnumerable<String> usersNames = results.Children().Values().Select(y => y.Value<String>()); List<User> listUsers = new List<User>(); //iterate list of usersNames and make USerObject foreach (string userName in usersNames) { object[] param = new[] { userName, null }; JToken userClaim = webService.CallWebService("RWE_WSO_SOAP", "getUserClaimValues", param); User newUser = new User(); newUser.AuthTypeId = Id; newUser.localExpiresAt = DateTime.Today;//for test newUser.LastLogin = DateTime.Today; newUser.CurrentLogin = DateTime.Today; newUser.EmailConfirmed = false; newUser.PhoneNumberConfirmed = false; newUser.TwoFactorEnabled = false; newUser.LockoutEnabled = false; newUser.AccessFailedCount = 0; newUser.isActive = true; foreach (JToken property in userClaim.Children()) { var a = (property.Children().Single(c => (c as JProperty).Name == "claimUri") as JProperty).Value.ToString(); switch (a) { case "email": var email = (property.Children().Single(c => (c as JProperty).Name == "value") as JProperty).Value.ToString(); newUser.Email = email; newUser.UserName = email; break; case "http://wso2.org/claims/mobile": var mobile = (property.Children().Single(c => (c as JProperty).Name == "value") as JProperty).Value.ToString(); newUser.MobilPhone = mobile; break; case "http://wso2.org/claims/organization": var organization = (property.Children().Single(c => (c as JProperty).Name == "value") as JProperty).Value.ToString(); newUser.Company = organization; break; case "fullname": var fullname = (property.Children().Single(c => (c as JProperty).Name == "value") as JProperty).Value.ToString(); newUser.DisplayName = fullname; break; //SET ROLES FOR this newly created USER case "http://wso2.org/claims/role": var roles = (property.Children().Single(c => (c as JProperty).Name == "value") as JProperty).Value.ToString().Split(',').Where(r => r.Substring(0, 8) == "Auction_").Select(e => e.Remove(0, 8)); foreach (string role in roles) { PersonaAppRole approle = context.AppRoles.SingleOrDefault(r => r.Name == role && r.ApplicationId == core.Application.Id); if (approle == null) { context.AppRoles.Add(new PersonaAppRole() { Name = role, Application = core.Application, Priority = 0 }); context.SaveChanges(); } //User_Role userRole = newUser.Roles.SingleOrDefault(ur => ur.AppRole == approle && ur.User == newUser); if (approle != null && !newUser.Users_Roles.Contains(new User_Role { RoleName = approle.Name, Application = approle.Application, User = newUser })) { newUser.Users_Roles.Add(new User_Role { RoleName = approle.Name, Application = approle.Application, User = newUser }); } } break; } } listUsers.Add(newUser); } return listUsers; } private void UpdateUsers(List<User> users) { var db = COREobject.i.Context; //iterate all users from WSO foreach (User user in users) { //if theres already this user. we will update the db var databaseUser = db.Users.SingleOrDefault(u => u.AuthTypeId == Id && u.UserName == user.UserName); if (databaseUser != null) { databaseUser.UserName = user.UserName; databaseUser.Company = user.Company; databaseUser.MobilPhone = user.MobilPhone; databaseUser.DisplayName = user.DisplayName; databaseUser.Email = user.Email; //Refresh ROLES databaseUser.Roles.Clear(); foreach (User_Role role in user.Users_Roles) { databaseUser.Users_Roles.Add(new User_Role { RoleName = role.RoleName, Application = role.Application, User = databaseUser }); } //end refresh roles databaseUser.isActive = true; db.SaveChanges(); } //if the user is not in DB, we will add this user to DB else { db.Users.Add(user); } } //iterate the users in the DB foreach (User user in db.Users) { //if this user is in db but not in the WSO, set inactive if (!users.Any(u => u.UserName == user.UserName)) { user.isActive = false; } } db.SaveChanges(); } } }
44.763636
221
0.497834
[ "MIT" ]
simplifate/omnius
application/FSS.Omnius.Modules/Persona/MasterWSO.cs
7,388
C#
using System; using System.Collections; using System.Text; using NUnit.Framework; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Signers; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.X509.Tests { [TestFixture] public class TestCertificateGen: SimpleTest { public override string Name { get { return "X.509 Cert Gen"; } } public TestCertificateGen() { } [Test] public void TestRsaDigestSigner() { BigInteger rsaPubMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); BigInteger rsaPubExp = new BigInteger(Base64.Decode("EQ==")); BigInteger rsaPrivMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); BigInteger rsaPrivDP = new BigInteger(Base64.Decode("JXzfzG5v+HtLJIZqYMUefJfFLu8DPuJGaLD6lI3cZ0babWZ/oPGoJa5iHpX4Ul/7l3s1PFsuy1GhzCdOdlfRcQ==")); BigInteger rsaPrivDQ = new BigInteger(Base64.Decode("YNdJhw3cn0gBoVmMIFRZzflPDNthBiWy/dUMSRfJCxoZjSnr1gysZHK01HteV1YYNGcwPdr3j4FbOfri5c6DUQ==")); BigInteger rsaPrivExp = new BigInteger(Base64.Decode("DxFAOhDajr00rBjqX+7nyZ/9sHWRCCp9WEN5wCsFiWVRPtdB+NeLcou7mWXwf1Y+8xNgmmh//fPV45G2dsyBeZbXeJwB7bzx9NMEAfedchyOwjR8PYdjK3NpTLKtZlEJ6Jkh4QihrXpZMO4fKZWUm9bid3+lmiq43FwW+Hof8/E=")); BigInteger rsaPrivP = new BigInteger(Base64.Decode("AJ9StyTVW+AL/1s7RBtFwZGFBgd3zctBqzzwKPda6LbtIFDznmwDCqAlIQH9X14X7UPLokCDhuAa76OnDXb1OiE=")); BigInteger rsaPrivQ = new BigInteger(Base64.Decode("AM3JfD79dNJ5A3beScSzPtWxx/tSLi0QHFtkuhtSizeXdkv5FSba7lVzwEOGKHmW829bRoNxThDy4ds1IihW1w0=")); BigInteger rsaPrivQinv = new BigInteger(Base64.Decode("Lt0g7wrsNsQxuDdB8q/rH8fSFeBXMGLtCIqfOec1j7FEIuYA/ACiRDgXkHa0WgN7nLXSjHoy630wC5Toq8vvUg==")); RsaKeyParameters rsaPublic = new RsaKeyParameters(false, rsaPubMod, rsaPubExp); RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(rsaPrivMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv); byte[] msg = new byte[] { 1, 6, 3, 32, 7, 43, 2, 5, 7, 78, 4, 23 }; RsaDigestSigner signer = new RsaDigestSigner(new Sha1Digest()); signer.Init(true, rsaPrivate); signer.BlockUpdate(msg, 0, msg.Length); byte[] sig = signer.GenerateSignature(); signer.Init(false,rsaPublic); signer.BlockUpdate(msg, 0, msg.Length); Assert.IsTrue(signer.VerifySignature(sig), "RSA IDigest Signer failed."); } [Test] public void TestCreationRSA() { BigInteger rsaPubMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); BigInteger rsaPubExp = new BigInteger(Base64.Decode("EQ==")); BigInteger rsaPrivMod = new BigInteger(Base64.Decode("AIASoe2PQb1IP7bTyC9usjHP7FvnUMVpKW49iuFtrw/dMpYlsMMoIU2jupfifDpdFxIktSB4P+6Ymg5WjvHKTIrvQ7SR4zV4jaPTu56Ys0pZ9EDA6gb3HLjtU+8Bb1mfWM+yjKxcPDuFjwEtjGlPHg1Vq+CA9HNcMSKNn2+tW6qt")); BigInteger rsaPrivDP = new BigInteger(Base64.Decode("JXzfzG5v+HtLJIZqYMUefJfFLu8DPuJGaLD6lI3cZ0babWZ/oPGoJa5iHpX4Ul/7l3s1PFsuy1GhzCdOdlfRcQ==")); BigInteger rsaPrivDQ = new BigInteger(Base64.Decode("YNdJhw3cn0gBoVmMIFRZzflPDNthBiWy/dUMSRfJCxoZjSnr1gysZHK01HteV1YYNGcwPdr3j4FbOfri5c6DUQ==")); BigInteger rsaPrivExp = new BigInteger(Base64.Decode("DxFAOhDajr00rBjqX+7nyZ/9sHWRCCp9WEN5wCsFiWVRPtdB+NeLcou7mWXwf1Y+8xNgmmh//fPV45G2dsyBeZbXeJwB7bzx9NMEAfedchyOwjR8PYdjK3NpTLKtZlEJ6Jkh4QihrXpZMO4fKZWUm9bid3+lmiq43FwW+Hof8/E=")); BigInteger rsaPrivP = new BigInteger(Base64.Decode("AJ9StyTVW+AL/1s7RBtFwZGFBgd3zctBqzzwKPda6LbtIFDznmwDCqAlIQH9X14X7UPLokCDhuAa76OnDXb1OiE=")); BigInteger rsaPrivQ = new BigInteger(Base64.Decode("AM3JfD79dNJ5A3beScSzPtWxx/tSLi0QHFtkuhtSizeXdkv5FSba7lVzwEOGKHmW829bRoNxThDy4ds1IihW1w0=")); BigInteger rsaPrivQinv = new BigInteger(Base64.Decode("Lt0g7wrsNsQxuDdB8q/rH8fSFeBXMGLtCIqfOec1j7FEIuYA/ACiRDgXkHa0WgN7nLXSjHoy630wC5Toq8vvUg==")); RsaKeyParameters rsaPublic = new RsaKeyParameters(false, rsaPubMod, rsaPubExp); RsaPrivateCrtKeyParameters rsaPrivate = new RsaPrivateCrtKeyParameters(rsaPrivMod, rsaPubExp, rsaPrivExp, rsaPrivP, rsaPrivQ, rsaPrivDP, rsaPrivDQ, rsaPrivQinv); IDictionary attrs = new Hashtable(); attrs[X509Name.C] = "AU"; attrs[X509Name.O] = "The Legion of the Bouncy Castle"; attrs[X509Name.L] = "Melbourne"; attrs[X509Name.ST] = "Victoria"; attrs[X509Name.E] = "feedback-crypto@bouncycastle.org"; IList ord = new ArrayList(); ord.Add(X509Name.C); ord.Add(X509Name.O); ord.Add(X509Name.L); ord.Add(X509Name.ST); ord.Add(X509Name.E); IList values = new ArrayList(); values.Add("AU"); values.Add("The Legion of the Bouncy Castle"); values.Add("Melbourne"); values.Add("Victoria"); values.Add("feedback-crypto@bouncycastle.org"); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, attrs)); certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1)); certGen.SetNotAfter(DateTime.UtcNow.AddDays(1)); certGen.SetSubjectDN(new X509Name(ord, attrs)); certGen.SetPublicKey(rsaPublic); certGen.SetSignatureAlgorithm("MD5WithRSAEncryption"); X509Certificate cert = certGen.Generate(rsaPrivate); // Assert.IsTrue((cert.IsValidNow && cert.Verify(rsaPublic)),"Certificate failed to be valid (RSA)"); cert.CheckValidity(); cert.Verify(rsaPublic); //Console.WriteLine(ASN1Dump.DumpAsString(cert.ToAsn1Object())); //ISet dummySet = cert.GetNonCriticalExtensionOids(); //if (dummySet != null) //{ // foreach (string key in dummySet) // { // Console.WriteLine("\t{0}:\t{1}", key); // } //} //Console.WriteLine(); //dummySet = cert.GetNonCriticalExtensionOids(); //if (dummySet != null) //{ // foreach (string key in dummySet) // { // Console.WriteLine("\t{0}:\t{1}", key); // } //} //Console.WriteLine(); } [Test] public void TestCreationDSA() { BigInteger DSAParaG = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM=")); BigInteger DSAParaP = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs=")); BigInteger DSAParaQ = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx")); BigInteger DSAPublicY = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw==")); BigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A=")); DsaParameters para = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG); DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para); DsaPublicKeyParameters dsaPub = new DsaPublicKeyParameters(DSAPublicY, para); IDictionary attrs = new Hashtable(); attrs[X509Name.C] = "AU"; attrs[X509Name.O] = "The Legion of the Bouncy Castle"; attrs[X509Name.L] = "Melbourne"; attrs[X509Name.ST] = "Victoria"; attrs[X509Name.E] = "feedback-crypto@bouncycastle.org"; IList ord = new ArrayList(); ord.Add(X509Name.C); ord.Add(X509Name.O); ord.Add(X509Name.L); ord.Add(X509Name.ST); ord.Add(X509Name.E); IList values = new ArrayList(); values.Add("AU"); values.Add("The Legion of the Bouncy Castle"); values.Add("Melbourne"); values.Add("Victoria"); values.Add("feedback-crypto@bouncycastle.org"); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, attrs)); certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1)); certGen.SetNotAfter(DateTime.UtcNow.AddDays(1)); certGen.SetSubjectDN(new X509Name(ord, attrs)); certGen.SetPublicKey(dsaPub); certGen.SetSignatureAlgorithm("SHA1WITHDSA"); X509Certificate cert = certGen.Generate(dsaPriv); // Assert.IsTrue((cert.IsValidNow && cert.Verify(dsaPub)), "Certificate failed to be valid (DSA Test)"); cert.CheckValidity(); cert.Verify(dsaPub); //ISet dummySet = cert.GetNonCriticalExtensionOids(); //if (dummySet != null) //{ // foreach (string key in dummySet) // { // Console.WriteLine("\t{0}:\t{1}", key); // } //} //Console.WriteLine(); //dummySet = cert.GetNonCriticalExtensionOids(); //if (dummySet != null) //{ // foreach (string key in dummySet) // { // Console.WriteLine("\t{0}:\t{1}", key); // } //} //Console.WriteLine(); } [Test] public void TestCreationECDSA() { BigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv")); BigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R")); BigInteger ECParraH = new BigInteger(Base64.Decode("AQ==")); BigInteger ECParraN = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L")); BigInteger ECPubQX = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l")); BigInteger ECPubQY = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx")); BigInteger ECPrivD = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo")); X9ECParameters x9 = ECNamedCurveTable.GetByName("prime239v1"); ECCurve curve = x9.Curve; ECDomainParameters ecDomain = new ECDomainParameters(curve, curve.ValidatePoint(ECParraGX, ECParraGY), ECParraN, ECParraH); ECPublicKeyParameters ecPub = new ECPublicKeyParameters("ECDSA", curve.ValidatePoint(ECPubQX, ECPubQY), ecDomain); ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters("ECDSA", ECPrivD, ecDomain); IDictionary attrs = new Hashtable(); attrs[X509Name.C] = "AU"; attrs[X509Name.O] = "The Legion of the Bouncy Castle"; attrs[X509Name.L] = "Melbourne"; attrs[X509Name.ST] = "Victoria"; attrs[X509Name.E] = "feedback-crypto@bouncycastle.org"; IList ord = new ArrayList(); ord.Add(X509Name.C); ord.Add(X509Name.O); ord.Add(X509Name.L); ord.Add(X509Name.ST); ord.Add(X509Name.E); IList values = new ArrayList(); values.Add("AU"); values.Add("The Legion of the Bouncy Castle"); values.Add("Melbourne"); values.Add("Victoria"); values.Add("feedback-crypto@bouncycastle.org"); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.SetSerialNumber(BigInteger.One); certGen.SetIssuerDN(new X509Name(ord, attrs)); certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1)); certGen.SetNotAfter(DateTime.UtcNow.AddDays(1)); certGen.SetSubjectDN(new X509Name(ord, attrs)); certGen.SetPublicKey(ecPub); certGen.SetSignatureAlgorithm("SHA1WITHECDSA"); certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); X509Certificate cert = certGen.Generate(ecPriv); // Assert.IsTrue((cert.IsValidNow && cert.Verify(ecPub)), "Certificate failed to be valid (ECDSA)"); cert.CheckValidity(); cert.Verify(ecPub); ISet extOidSet = cert.GetCriticalExtensionOids(); if (extOidSet.Count != 1) { Fail("wrong number of oids"); } //if (dummySet != null) //{ // foreach (string key in dummySet) // { // Console.WriteLine("\t{0}:\t{1}", key); // } //} //Console.WriteLine(); //dummySet = cert.GetNonCriticalExtensionOids(); //if (dummySet != null) //{ // foreach (string key in dummySet) // { // Console.WriteLine("\t{0}:\t{1}", key); // } //} //Console.WriteLine(); } [Test] public void TestCertLoading() { byte[] cert1 = Base64.Decode( "MIIDXjCCAsegAwIBAgIBBzANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx" + "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY" + "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB" + "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ" + "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU2MjFaFw0wMTA2" + "MDIwNzU2MjFaMIG4MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW" + "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM" + "dGQxFzAVBgNVBAsTDldlYnNlcnZlciBUZWFtMR0wGwYDVQQDExR3d3cyLmNvbm5l" + "Y3Q0LmNvbS5hdTEoMCYGCSqGSIb3DQEJARYZd2VibWFzdGVyQGNvbm5lY3Q0LmNv" + "bS5hdTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArvDxclKAhyv7Q/Wmr2re" + "Gw4XL9Cnh9e+6VgWy2AWNy/MVeXdlxzd7QAuc1eOWQkGQEiLPy5XQtTY+sBUJ3AO" + "Rvd2fEVJIcjf29ey7bYua9J/vz5MG2KYo9/WCHIwqD9mmG9g0xLcfwq/s8ZJBswE" + "7sb85VU+h94PTvsWOsWuKaECAwEAAaN3MHUwJAYDVR0RBB0wG4EZd2VibWFzdGVy" + "QGNvbm5lY3Q0LmNvbS5hdTA6BglghkgBhvhCAQ0ELRYrbW9kX3NzbCBnZW5lcmF0" + "ZWQgY3VzdG9tIHNlcnZlciBjZXJ0aWZpY2F0ZTARBglghkgBhvhCAQEEBAMCBkAw" + "DQYJKoZIhvcNAQEEBQADgYEAotccfKpwSsIxM1Hae8DR7M/Rw8dg/RqOWx45HNVL" + "iBS4/3N/TO195yeQKbfmzbAA2jbPVvIvGgTxPgO1MP4ZgvgRhasaa0qCJCkWvpM4" + "yQf33vOiYQbpv4rTwzU8AmRlBG45WdjyNIigGV+oRc61aKCTnLq7zB8N3z1TF/bF" + "5/8="); try { Assert.IsNotNull(new X509CertificateParser().ReadCertificate(cert1)); } catch (Exception) { Assert.Fail("Reading first test certificate."); } // ca.crt // byte[] cert2 = Base64.Decode( "MIIDbDCCAtWgAwIBAgIBADANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx" + "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY" + "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB" + "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ" + "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU1MzNaFw0wMTA2" + "MDIwNzU1MzNaMIG3MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW" + "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM" + "dGQxHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhvcml0eTEVMBMGA1UEAxMMQ29u" + "bmVjdCA0IENBMSgwJgYJKoZIhvcNAQkBFhl3ZWJtYXN0ZXJAY29ubmVjdDQuY29t" + "LmF1MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgs5ptNG6Qv1ZpCDuUNGmv" + "rhjqMDPd3ri8JzZNRiiFlBA4e6/ReaO1U8ASewDeQMH6i9R6degFdQRLngbuJP0s" + "xcEE+SksEWNvygfzLwV9J/q+TQDyJYK52utb++lS0b48A1KPLwEsyL6kOAgelbur" + "ukwxowprKUIV7Knf1ajetQIDAQABo4GFMIGCMCQGA1UdEQQdMBuBGXdlYm1hc3Rl" + "ckBjb25uZWN0NC5jb20uYXUwDwYDVR0TBAgwBgEB/wIBADA2BglghkgBhvhCAQ0E" + "KRYnbW9kX3NzbCBnZW5lcmF0ZWQgY3VzdG9tIENBIGNlcnRpZmljYXRlMBEGCWCG" + "SAGG+EIBAQQEAwICBDANBgkqhkiG9w0BAQQFAAOBgQCsGvfdghH8pPhlwm1r3pQk" + "msnLAVIBb01EhbXm2861iXZfWqGQjrGAaA0ZpXNk9oo110yxoqEoSJSzniZa7Xtz" + "soTwNUpE0SLHvWf/SlKdFWlzXA+vOZbzEv4UmjeelekTm7lc01EEa5QRVzOxHFtQ" + "DhkaJ8VqOMajkQFma2r9iA=="); try { Assert.IsNotNull(new X509CertificateParser().ReadCertificate(cert2)); } catch (Exception) { Assert.Fail("Reading second test certificate."); } // // testx509.pem // byte[] cert3 = Base64.Decode( "MIIBWzCCAQYCARgwDQYJKoZIhvcNAQEEBQAwODELMAkGA1UEBhMCQVUxDDAKBgNV" + "BAgTA1FMRDEbMBkGA1UEAxMSU1NMZWF5L3JzYSB0ZXN0IENBMB4XDTk1MDYxOTIz" + "MzMxMloXDTk1MDcxNzIzMzMxMlowOjELMAkGA1UEBhMCQVUxDDAKBgNVBAgTA1FM" + "RDEdMBsGA1UEAxMUU1NMZWF5L3JzYSB0ZXN0IGNlcnQwXDANBgkqhkiG9w0BAQEF" + "AANLADBIAkEAqtt6qS5GTxVxGZYWa0/4u+IwHf7p2LNZbcPBp9/OfIcYAXBQn8hO" + "/Re1uwLKXdCjIoaGs4DLdG88rkzfyK5dPQIDAQABMAwGCCqGSIb3DQIFBQADQQAE" + "Wc7EcF8po2/ZO6kNCwK/ICH6DobgLekA5lSLr5EvuioZniZp5lFzAw4+YzPQ7XKJ" + "zl9HYIMxATFyqSiD9jsx"); try { Assert.IsNotNull(new X509CertificateParser().ReadCertificate(cert3)); } catch (Exception) { Assert.Fail("Reading third test certificate. (X509.pem)"); } // // v3-cert1.pem // byte[] cert4 = Base64.Decode( "MIICjTCCAfigAwIBAgIEMaYgRzALBgkqhkiG9w0BAQQwRTELMAkGA1UEBhMCVVMx" + "NjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFuZCBTcGFjZSBBZG1pbmlz" + "dHJhdGlvbjAmFxE5NjA1MjgxMzQ5MDUrMDgwMBcROTgwNTI4MTM0OTA1KzA4MDAw" + "ZzELMAkGA1UEBhMCVVMxNjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFu" + "ZCBTcGFjZSBBZG1pbmlzdHJhdGlvbjEgMAkGA1UEBRMCMTYwEwYDVQQDEwxTdGV2" + "ZSBTY2hvY2gwWDALBgkqhkiG9w0BAQEDSQAwRgJBALrAwyYdgxmzNP/ts0Uyf6Bp" + "miJYktU/w4NG67ULaN4B5CnEz7k57s9o3YY3LecETgQ5iQHmkwlYDTL2fTgVfw0C" + "AQOjgaswgagwZAYDVR0ZAQH/BFowWDBWMFQxCzAJBgNVBAYTAlVTMTYwNAYDVQQK" + "Ey1OYXRpb25hbCBBZXJvbmF1dGljcyBhbmQgU3BhY2UgQWRtaW5pc3RyYXRpb24x" + "DTALBgNVBAMTBENSTDEwFwYDVR0BAQH/BA0wC4AJODMyOTcwODEwMBgGA1UdAgQR" + "MA8ECTgzMjk3MDgyM4ACBSAwDQYDVR0KBAYwBAMCBkAwCwYJKoZIhvcNAQEEA4GB" + "AH2y1VCEw/A4zaXzSYZJTTUi3uawbbFiS2yxHvgf28+8Js0OHXk1H1w2d6qOHH21" + "X82tZXd/0JtG0g1T9usFFBDvYK8O0ebgz/P5ELJnBL2+atObEuJy1ZZ0pBDWINR3" + "WkDNLCGiTkCKp0F5EWIrVDwh54NNevkCQRZita+z4IBO"); try { Assert.IsNotNull(new X509CertificateParser().ReadCertificate(cert4)); } catch (Exception) { Assert.Fail("Reading fourth test certificate. (X509 V3 Pem)"); } // // v3-cert2.pem // byte[] cert5 = Base64.Decode( "MIICiTCCAfKgAwIBAgIEMeZfHzANBgkqhkiG9w0BAQQFADB9MQswCQYDVQQGEwJD" + "YTEPMA0GA1UEBxMGTmVwZWFuMR4wHAYDVQQLExVObyBMaWFiaWxpdHkgQWNjZXB0" + "ZWQxHzAdBgNVBAoTFkZvciBEZW1vIFB1cnBvc2VzIE9ubHkxHDAaBgNVBAMTE0Vu" + "dHJ1c3QgRGVtbyBXZWIgQ0EwHhcNOTYwNzEyMTQyMDE1WhcNOTYxMDEyMTQyMDE1" + "WjB0MSQwIgYJKoZIhvcNAQkBExVjb29rZUBpc3NsLmF0bC5ocC5jb20xCzAJBgNV" + "BAYTAlVTMScwJQYDVQQLEx5IZXdsZXR0IFBhY2thcmQgQ29tcGFueSAoSVNTTCkx" + "FjAUBgNVBAMTDVBhdWwgQS4gQ29va2UwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA" + "6ceSq9a9AU6g+zBwaL/yVmW1/9EE8s5you1mgjHnj0wAILuoB3L6rm6jmFRy7QZT" + "G43IhVZdDua4e+5/n1ZslwIDAQABo2MwYTARBglghkgBhvhCAQEEBAMCB4AwTAYJ" + "YIZIAYb4QgENBD8WPVRoaXMgY2VydGlmaWNhdGUgaXMgb25seSBpbnRlbmRlZCBm" + "b3IgZGVtb25zdHJhdGlvbiBwdXJwb3Nlcy4wDQYJKoZIhvcNAQEEBQADgYEAi8qc" + "F3zfFqy1sV8NhjwLVwOKuSfhR/Z8mbIEUeSTlnH3QbYt3HWZQ+vXI8mvtZoBc2Fz" + "lexKeIkAZXCesqGbs6z6nCt16P6tmdfbZF3I3AWzLquPcOXjPf4HgstkyvVBn0Ap" + "jAFN418KF/Cx4qyHB4cjdvLrRjjQLnb2+ibo7QU="); try { Assert.IsNotNull(new X509CertificateParser().ReadCertificate(cert5)); } catch (Exception) { Assert.Fail("Reading fifth test certificate. (X509 V3 Pem)"); } // // pem encoded pkcs7 // byte[] cert6 = Base64.Decode( "MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIJbzCCAj0w" + "ggGmAhEAzbp/VvDf5LxU/iKss3KqVTANBgkqhkiG9w0BAQIFADBfMQswCQYDVQQGEwJVUzEXMBUG" + "A1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVibGljIFByaW1hcnkgQ2Vy" + "dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNOTYwMTI5MDAwMDAwWhcNMjgwODAxMjM1OTU5WjBfMQsw" + "CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVi" + "bGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwgZ8wDQYJKoZIhvcNAQEBBQADgY0A" + "MIGJAoGBAOUZv22jVmEtmUhx9mfeuY3rt56GgAqRDvo4Ja9GiILlc6igmyRdDR/MZW4MsNBWhBiH" + "mgabEKFz37RYOWtuwfYV1aioP6oSBo0xrH+wNNePNGeICc0UEeJORVZpH3gCgNrcR5EpuzbJY1zF" + "4Ncth3uhtzKwezC6Ki8xqu6jZ9rbAgMBAAEwDQYJKoZIhvcNAQECBQADgYEATD+4i8Zo3+5DMw5d" + "6abLB4RNejP/khv0Nq3YlSI2aBFsfELM85wuxAc/FLAPT/+Qknb54rxK6Y/NoIAK98Up8YIiXbix" + "3YEjo3slFUYweRb46gVLlH8dwhzI47f0EEA8E8NfH1PoSOSGtHuhNbB7Jbq4046rPzidADQAmPPR" + "cZQwggMuMIICl6ADAgECAhEA0nYujRQMPX2yqCVdr+4NdTANBgkqhkiG9w0BAQIFADBfMQswCQYD" + "VQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVibGlj" + "IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNOTgwNTEyMDAwMDAwWhcNMDgwNTEy" + "MjM1OTU5WjCBzDEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy" + "dXN0IE5ldHdvcmsxRjBEBgNVBAsTPXd3dy52ZXJpc2lnbi5jb20vcmVwb3NpdG9yeS9SUEEgSW5j" + "b3JwLiBCeSBSZWYuLExJQUIuTFREKGMpOTgxSDBGBgNVBAMTP1ZlcmlTaWduIENsYXNzIDEgQ0Eg" + "SW5kaXZpZHVhbCBTdWJzY3JpYmVyLVBlcnNvbmEgTm90IFZhbGlkYXRlZDCBnzANBgkqhkiG9w0B" + "AQEFAAOBjQAwgYkCgYEAu1pEigQWu1X9A3qKLZRPFXg2uA1Ksm+cVL+86HcqnbnwaLuV2TFBcHqB" + "S7lIE1YtxwjhhEKrwKKSq0RcqkLwgg4C6S/7wju7vsknCl22sDZCM7VuVIhPh0q/Gdr5FegPh7Yc" + "48zGmo5/aiSS4/zgZbqnsX7vyds3ashKyAkG5JkCAwEAAaN8MHowEQYJYIZIAYb4QgEBBAQDAgEG" + "MEcGA1UdIARAMD4wPAYLYIZIAYb4RQEHAQEwLTArBggrBgEFBQcCARYfd3d3LnZlcmlzaWduLmNv" + "bS9yZXBvc2l0b3J5L1JQQTAPBgNVHRMECDAGAQH/AgEAMAsGA1UdDwQEAwIBBjANBgkqhkiG9w0B" + "AQIFAAOBgQCIuDc73dqUNwCtqp/hgQFxHpJqbS/28Z3TymQ43BuYDAeGW4UVag+5SYWklfEXfWe0" + "fy0s3ZpCnsM+tI6q5QsG3vJWKvozx74Z11NMw73I4xe1pElCY+zCphcPXVgaSTyQXFWjZSAA/Rgg" + "5V+CprGoksVYasGNAzzrw80FopCubjCCA/gwggNhoAMCAQICEBbbn/1G1zppD6KsP01bwywwDQYJ" + "KoZIhvcNAQEEBQAwgcwxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2ln" + "biBUcnVzdCBOZXR3b3JrMUYwRAYDVQQLEz13d3cudmVyaXNpZ24uY29tL3JlcG9zaXRvcnkvUlBB" + "IEluY29ycC4gQnkgUmVmLixMSUFCLkxURChjKTk4MUgwRgYDVQQDEz9WZXJpU2lnbiBDbGFzcyAx" + "IENBIEluZGl2aWR1YWwgU3Vic2NyaWJlci1QZXJzb25hIE5vdCBWYWxpZGF0ZWQwHhcNMDAxMDAy" + "MDAwMDAwWhcNMDAxMjAxMjM1OTU5WjCCAQcxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYD" + "VQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMUYwRAYDVQQLEz13d3cudmVyaXNpZ24uY29tL3Jl" + "cG9zaXRvcnkvUlBBIEluY29ycC4gYnkgUmVmLixMSUFCLkxURChjKTk4MR4wHAYDVQQLExVQZXJz" + "b25hIE5vdCBWYWxpZGF0ZWQxJzAlBgNVBAsTHkRpZ2l0YWwgSUQgQ2xhc3MgMSAtIE1pY3Jvc29m" + "dDETMBEGA1UEAxQKRGF2aWQgUnlhbjElMCMGCSqGSIb3DQEJARYWZGF2aWRAbGl2ZW1lZGlhLmNv" + "bS5hdTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqxBsdeNmSvFqhMNwhQgNzM8mdjX9eSXb" + "DawpHtQHjmh0AKJSa3IwUY0VIsyZHuXWktO/CgaMBVPt6OVf/n0R2sQigMP6Y+PhEiS0vCJBL9aK" + "0+pOo2qXrjVBmq+XuCyPTnc+BOSrU26tJsX0P9BYorwySiEGxGanBNATdVL4NdUCAwEAAaOBnDCB" + "mTAJBgNVHRMEAjAAMEQGA1UdIAQ9MDswOQYLYIZIAYb4RQEHAQgwKjAoBggrBgEFBQcCARYcaHR0" + "cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYTARBglghkgBhvhCAQEEBAMCB4AwMwYDVR0fBCwwKjAo" + "oCagJIYiaHR0cDovL2NybC52ZXJpc2lnbi5jb20vY2xhc3MxLmNybDANBgkqhkiG9w0BAQQFAAOB" + "gQBC8yIIdVGpFTf8/YiL14cMzcmL0nIRm4kGR3U59z7UtcXlfNXXJ8MyaeI/BnXwG/gD5OKYqW6R" + "yca9vZOxf1uoTBl82gInk865ED3Tej6msCqFzZffnSUQvOIeqLxxDlqYRQ6PmW2nAnZeyjcnbI5Y" + "syQSM2fmo7n6qJFP+GbFezGCAkUwggJBAgEBMIHhMIHMMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5j" + "LjEfMB0GA1UECxMWVmVyaVNpZ24gVHJ1c3QgTmV0d29yazFGMEQGA1UECxM9d3d3LnZlcmlzaWdu" + "LmNvbS9yZXBvc2l0b3J5L1JQQSBJbmNvcnAuIEJ5IFJlZi4sTElBQi5MVEQoYyk5ODFIMEYGA1UE" + "AxM/VmVyaVNpZ24gQ2xhc3MgMSBDQSBJbmRpdmlkdWFsIFN1YnNjcmliZXItUGVyc29uYSBOb3Qg" + "VmFsaWRhdGVkAhAW25/9Rtc6aQ+irD9NW8MsMAkGBSsOAwIaBQCggbowGAYJKoZIhvcNAQkDMQsG" + "CSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMDAxMDAyMTczNTE4WjAjBgkqhkiG9w0BCQQxFgQU" + "gZjSaBEY2oxGvlQUIMnxSXhivK8wWwYJKoZIhvcNAQkPMU4wTDAKBggqhkiG9w0DBzAOBggqhkiG" + "9w0DAgICAIAwDQYIKoZIhvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwBwYFKw4DAh0w" + "DQYJKoZIhvcNAQEBBQAEgYAzk+PU91/ZFfoiuKOECjxEh9fDYE2jfDCheBIgh5gdcCo+sS1WQs8O" + "HreQ9Nop/JdJv1DQMBK6weNBBDoP0EEkRm1XCC144XhXZC82jBZohYmi2WvDbbC//YN58kRMYMyy" + "srrfn4Z9I+6kTriGXkrpGk9Q0LSGjmG2BIsqiF0dvwAAAAAAAA=="); try { Assert.IsNotNull(new X509CertificateParser().ReadCertificate(cert6)); } catch (Exception) { Assert.Fail("Reading sixth test certificate. (Pkcs7)"); } // // dsaWithSHA1 cert // byte[] cert7 = Base64.Decode( "MIIEXAYJKoZIhvcNAQcCoIIETTCCBEkCAQExCzAJBgUrDgMCGgUAMAsGCSqG" + "SIb3DQEHAaCCAsMwggK/MIIB4AIBADCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7" + "d8miwTMN55CUSmo3TO8WGCxgY61TX5k+7NU4XPf1TULjw3GobwaJX13kquPh" + "fVXk+gVy46n4Iw3hAhUBSe/QF4BUj+pJOF9ROBM4u+FEWA8CQQD4mSJbrABj" + "TUWrlnAte8pS22Tq4/FPO7jHSqjijUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/z" + "m8Q12PFp/PjOhh+nMA4xDDAKBgNVBAMTA0lEMzAeFw05NzEwMDEwMDAwMDBa" + "Fw0zODAxMDEwMDAwMDBaMA4xDDAKBgNVBAMTA0lEMzCB8DCBpwYFKw4DAhsw" + "gZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxgY61TX5k+7NU4XPf1TULj" + "w3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/QF4BUj+pJOF9ROBM4u+FE" + "WA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jHSqjijUHfXKTrHL1OEqV3" + "SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nA0QAAkEAkYkXLYMtGVGWj9OnzjPn" + "sB9sefSRPrVegZJCZbpW+Iv0/1RP1u04pHG9vtRpIQLjzUiWvLMU9EKQTThc" + "eNMmWDCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxg" + "Y61TX5k+7NU4XPf1TULjw3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/Q" + "F4BUj+pJOF9ROBM4u+FEWA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jH" + "SqjijUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nAy8AMCwC" + "FBY3dBSdeprGcqpr6wr3xbG+6WW+AhRMm/facKJNxkT3iKgJbp7R8Xd3QTGC" + "AWEwggFdAgEBMBMwDjEMMAoGA1UEAxMDSUQzAgEAMAkGBSsOAwIaBQCgXTAY" + "BgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wMjA1" + "MjQyMzEzMDdaMCMGCSqGSIb3DQEJBDEWBBS4WMsoJhf7CVbZYCFcjoTRzPkJ" + "xjCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxgY61T" + "X5k+7NU4XPf1TULjw3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/QF4BU" + "j+pJOF9ROBM4u+FEWA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jHSqji" + "jUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nBC8wLQIVALID" + "dt+MHwawrDrwsO1Z6sXBaaJsAhRaKssrpevmLkbygKPV07XiAKBG02Zvb2Jh" + "cg=="); try { Assert.IsNotNull(new X509CertificateParser().ReadCertificate(cert7)); } catch (Exception) { Assert.Fail("Reading seventh test certificate. (DSAWITHSHA1)"); } // // ecdsa cert with extra octet string. // byte[] oldEcdsa = Base64.Decode( "MIICljCCAkCgAwIBAgIBATALBgcqhkjOPQQBBQAwgY8xCzAJBgNVBAYTAkFVMSgwJ" + "gYDVQQKEx9UaGUgTGVnaW9uIG9mIHRoZSBCb3VuY3kgQ2FzdGxlMRIwEAYDVQQHEw" + "lNZWxib3VybmUxETAPBgNVBAgTCFZpY3RvcmlhMS8wLQYJKoZIhvcNAQkBFiBmZWV" + "kYmFjay1jcnlwdG9AYm91bmN5Y2FzdGxlLm9yZzAeFw0wMTEyMDcwMTAwMDRaFw0w" + "MTEyMDcwMTAxNDRaMIGPMQswCQYDVQQGEwJBVTEoMCYGA1UEChMfVGhlIExlZ2lvb" + "iBvZiB0aGUgQm91bmN5IENhc3RsZTESMBAGA1UEBxMJTWVsYm91cm5lMREwDwYDVQ" + "QIEwhWaWN0b3JpYTEvMC0GCSqGSIb3DQEJARYgZmVlZGJhY2stY3J5cHRvQGJvdW5" + "jeWNhc3RsZS5vcmcwgeQwgb0GByqGSM49AgEwgbECAQEwKQYHKoZIzj0BAQIef///" + "////////////f///////gAAAAAAAf///////MEAEHn///////////////3///////" + "4AAAAAAAH///////AQeawFsO9zxiUHQ1lSSFHXKcanbL7J9HTd5YYXClCwKBB8CD/" + "qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqvAh5///////////////9///+eXpq" + "fXZBx+9FSJoiQnQsDIgAEHwJbbcU7xholSP+w9nFHLebJUhqdLSU05lq/y9X+DHAw" + "CwYHKoZIzj0EAQUAA0MAMEACHnz6t4UNoVROp74ma4XNDjjGcjaqiIWPZLK8Bdw3G" + "QIeLZ4j3a6ividZl344UH+UPUE7xJxlYGuy7ejTsqRR"); try { Assert.IsNotNull(new X509CertificateParser().ReadCertificate(oldEcdsa)); } catch (Exception) { Assert.Fail("Reading old ECDSA Certificate."); } byte[] uncompressedPtEC = Base64.Decode( "MIIDKzCCAsGgAwIBAgICA+kwCwYHKoZIzj0EAQUAMGYxCzAJBgNVBAYTAkpQ" + "MRUwEwYDVQQKEwxuaXRlY2guYWMuanAxDjAMBgNVBAsTBWFpbGFiMQ8wDQYD" + "VQQDEwZ0ZXN0Y2ExHzAdBgkqhkiG9w0BCQEWEHRlc3RjYUBsb2NhbGhvc3Qw" + "HhcNMDExMDEzMTE1MzE3WhcNMjAxMjEyMTE1MzE3WjBmMQswCQYDVQQGEwJK" + "UDEVMBMGA1UEChMMbml0ZWNoLmFjLmpwMQ4wDAYDVQQLEwVhaWxhYjEPMA0G" + "A1UEAxMGdGVzdGNhMR8wHQYJKoZIhvcNAQkBFhB0ZXN0Y2FAbG9jYWxob3N0" + "MIIBczCCARsGByqGSM49AgEwggEOAgEBMDMGByqGSM49AQECKEdYWnajFmnZ" + "tzrukK2XWdle2v+GsD9l1ZiR6g7ozQDbhFH/bBiMDQcwVAQoJ5EQKrI54/CT" + "xOQ2pMsd/fsXD+EX8YREd8bKHWiLz8lIVdD5cBNeVwQoMKSc6HfI7vKZp8Q2" + "zWgIFOarx1GQoWJbMcSt188xsl30ncJuJT2OoARRBAqJ4fD+q6hbqgNSjTQ7" + "htle1KO3eiaZgcJ8rrnyN8P+5A8+5K+H9aQ/NbBR4Gs7yto5PXIUZEUgodHA" + "TZMSAcSq5ZYt4KbnSYaLY0TtH9CqAigEwZ+hglbT21B7ZTzYX2xj0x+qooJD" + "hVTLtIPaYJK2HrMPxTw6/zfrAgEPA1IABAnvfFcFDgD/JicwBGn6vR3N8MIn" + "mptZf/mnJ1y649uCF60zOgdwIyI7pVSxBFsJ7ohqXEHW0x7LrGVkdSEiipiH" + "LYslqh3xrqbAgPbl93GUo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB" + "/wQEAwIBxjAdBgNVHQ4EFgQUAEo62Xm9H6DcsE0zUDTza4BRG90wCwYHKoZI" + "zj0EAQUAA1cAMFQCKAQsCHHSNOqfJXLgt3bg5+k49hIBGVr/bfG0B9JU3rNt" + "Ycl9Y2zfRPUCKAK2ccOQXByAWfsasDu8zKHxkZv7LVDTFjAIffz3HaCQeVhD" + "z+fauEg="); try { Assert.IsNotNull(new X509CertificateParser().ReadCertificate(uncompressedPtEC)); } catch (Exception) { Assert.Fail("Reading uncompressed ECPoint Certificate."); } byte[] keyUsage = Base64.Decode( "MIIE7TCCBFagAwIBAgIEOAOR7jANBgkqhkiG9w0BAQQFADCByTELMAkGA1UE" + "BhMCVVMxFDASBgNVBAoTC0VudHJ1c3QubmV0MUgwRgYDVQQLFD93d3cuZW50" + "cnVzdC5uZXQvQ2xpZW50X0NBX0luZm8vQ1BTIGluY29ycC4gYnkgcmVmLiBs" + "aW1pdHMgbGlhYi4xJTAjBgNVBAsTHChjKSAxOTk5IEVudHJ1c3QubmV0IExp" + "bWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENsaWVudCBDZXJ0aWZpY2F0" + "aW9uIEF1dGhvcml0eTAeFw05OTEwMTIxOTI0MzBaFw0xOTEwMTIxOTU0MzBa" + "MIHJMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxSDBGBgNV" + "BAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0FfSW5mby9DUFMgaW5jb3Jw" + "LiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UECxMcKGMpIDE5OTkgRW50" + "cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50cnVzdC5uZXQgQ2xpZW50" + "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUAA4GL" + "ADCBhwKBgQDIOpleMRffrCdvkHvkGf9FozTC28GoT/Bo6oT9n3V5z8GKUZSv" + "x1cDR2SerYIbWtp/N3hHuzeYEpbOxhN979IMMFGpOZ5V+Pux5zDeg7K6PvHV" + "iTs7hbqqdCz+PzFur5GVbgbUB01LLFZHGARS2g4Qk79jkJvh34zmAqTmT173" + "iwIBA6OCAeAwggHcMBEGCWCGSAGG+EIBAQQEAwIABzCCASIGA1UdHwSCARkw" + "ggEVMIHkoIHhoIHepIHbMIHYMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50" + "cnVzdC5uZXQxSDBGBgNVBAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0Ff" + "SW5mby9DUFMgaW5jb3JwLiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UE" + "CxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50" + "cnVzdC5uZXQgQ2xpZW50IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYD" + "VQQDEwRDUkwxMCygKqAohiZodHRwOi8vd3d3LmVudHJ1c3QubmV0L0NSTC9D" + "bGllbnQxLmNybDArBgNVHRAEJDAigA8xOTk5MTAxMjE5MjQzMFqBDzIwMTkx" + "MDEyMTkyNDMwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUxPucKXuXzUyW" + "/O5bs8qZdIuV6kwwHQYDVR0OBBYEFMT7nCl7l81MlvzuW7PKmXSLlepMMAwG" + "A1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EABAwwChsEVjQuMAMCBJAwDQYJKoZI" + "hvcNAQEEBQADgYEAP66K8ddmAwWePvrqHEa7pFuPeJoSSJn59DXeDDYHAmsQ" + "OokUgZwxpnyyQbJq5wcBoUv5nyU7lsqZwz6hURzzwy5E97BnRqqS5TvaHBkU" + "ODDV4qIxJS7x7EU47fgGWANzYrAQMY9Av2TgXD7FTx/aEkP/TOYGJqibGapE" + "PHayXOw="); try { Assert.IsNotNull(new X509CertificateParser().ReadCertificate(keyUsage)); } catch (Exception) { Assert.Fail("Reading Cert with Key Usage."); } byte[] nameCert = Base64.Decode( "MIIEFjCCA3+gAwIBAgIEdS8BozANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQGEwJE" + "RTERMA8GA1UEChQIREFURVYgZUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRQ0Eg" + "REFURVYgRDAzIDE6UE4wIhgPMjAwMTA1MTAxMDIyNDhaGA8yMDA0MDUwOTEwMjI0" + "OFowgYQxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIFAZCYXllcm4xEjAQBgNVBAcUCU7I" + "dXJuYmVyZzERMA8GA1UEChQIREFURVYgZUcxHTAbBgNVBAUTFDAwMDAwMDAwMDA4" + "OTU3NDM2MDAxMR4wHAYDVQQDFBVEaWV0bWFyIFNlbmdlbmxlaXRuZXIwgaEwDQYJ" + "KoZIhvcNAQEBBQADgY8AMIGLAoGBAJLI/LJLKaHoMk8fBECW/od8u5erZi6jI8Ug" + "C0a/LZyQUO/R20vWJs6GrClQtXB+AtfiBSnyZOSYzOdfDI8yEKPEv8qSuUPpOHps" + "uNCFdLZF1vavVYGEEWs2+y+uuPmg8q1oPRyRmUZ+x9HrDvCXJraaDfTEd9olmB/Z" + "AuC/PqpjAgUAwAAAAaOCAcYwggHCMAwGA1UdEwEB/wQCMAAwDwYDVR0PAQH/BAUD" + "AwdAADAxBgNVHSAEKjAoMCYGBSskCAEBMB0wGwYIKwYBBQUHAgEWD3d3dy56cy5k" + "YXRldi5kZTApBgNVHREEIjAggR5kaWV0bWFyLnNlbmdlbmxlaXRuZXJAZGF0ZXYu" + "ZGUwgYQGA1UdIwR9MHuhc6RxMG8xCzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1" + "bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0" + "MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjVSLUNBIDE6UE6CBACm8LkwDgYHAoIG" + "AQoMAAQDAQEAMEcGA1UdHwRAMD4wPKAUoBKGEHd3dy5jcmwuZGF0ZXYuZGWiJKQi" + "MCAxCzAJBgNVBAYTAkRFMREwDwYDVQQKFAhEQVRFViBlRzAWBgUrJAgDBAQNMAsT" + "A0VVUgIBBQIBATAdBgNVHQ4EFgQUfv6xFP0xk7027folhy+ziZvBJiwwLAYIKwYB" + "BQUHAQEEIDAeMBwGCCsGAQUFBzABhhB3d3cuZGlyLmRhdGV2LmRlMA0GCSqGSIb3" + "DQEBBQUAA4GBAEOVX6uQxbgtKzdgbTi6YLffMftFr2mmNwch7qzpM5gxcynzgVkg" + "pnQcDNlm5AIbS6pO8jTCLfCd5TZ5biQksBErqmesIl3QD+VqtB+RNghxectZ3VEs" + "nCUtcE7tJ8O14qwCb3TxS9dvIUFiVi4DjbxX46TdcTbTaK8/qr6AIf+l"); try { Assert.IsNotNull(new X509CertificateParser().ReadCertificate(nameCert)); } catch (Exception) { Assert.Fail("Reading Named Certificate."); } byte[] probSelfSignedCert = Base64.Decode( "MIICxTCCAi6gAwIBAgIQAQAAAAAAAAAAAAAAAAAAATANBgkqhkiG9w0BAQUFADBF" + "MScwJQYDVQQKEx4gRElSRUNUSU9OIEdFTkVSQUxFIERFUyBJTVBPVFMxGjAYBgNV" + "BAMTESBBQyBNSU5FRkkgQiBURVNUMB4XDTA0MDUwNzEyMDAwMFoXDTE0MDUwNzEy" + "MDAwMFowRTEnMCUGA1UEChMeIERJUkVDVElPTiBHRU5FUkFMRSBERVMgSU1QT1RT" + "MRowGAYDVQQDExEgQUMgTUlORUZJIEIgVEVTVDCBnzANBgkqhkiG9w0BAQEFAAOB" + "jQAwgYkCgYEAveoCUOAukZdcFCs2qJk76vSqEX0ZFzHqQ6faBPZWjwkgUNwZ6m6m" + "qWvvyq1cuxhoDvpfC6NXILETawYc6MNwwxsOtVVIjuXlcF17NMejljJafbPximEt" + "DQ4LcQeSp4K7FyFlIAMLyt3BQ77emGzU5fjFTvHSUNb3jblx0sV28c0CAwEAAaOB" + "tTCBsjAfBgNVHSMEGDAWgBSEJ4bLbvEQY8cYMAFKPFD1/fFXlzAdBgNVHQ4EFgQU" + "hCeGy27xEGPHGDABSjxQ9f3xV5cwDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIB" + "AQQEAwIBBjA8BgNVHR8ENTAzMDGgL6AthitodHRwOi8vYWRvbmlzLnBrNy5jZXJ0" + "cGx1cy5uZXQvZGdpLXRlc3QuY3JsMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN" + "AQEFBQADgYEAmToHJWjd3+4zknfsP09H6uMbolHNGG0zTS2lrLKpzcmkQfjhQpT9" + "LUTBvfs1jdjo9fGmQLvOG+Sm51Rbjglb8bcikVI5gLbclOlvqLkm77otjl4U4Z2/" + "Y0vP14Aov3Sn3k+17EfReYUZI4liuB95ncobC4e8ZM++LjQcIM0s+Vs="); try { Assert.IsNotNull(new X509CertificateParser().ReadCertificate(probSelfSignedCert)); } catch (Exception) { Assert.Fail("Reading busted Certificate."); } } public static void Main(string[] args) { RunTest(new TestCertificateGen()); } public override void PerformTest() { TestCreationRSA(); TestCreationDSA(); TestCreationECDSA(); } } }
53.002714
242
0.688734
[ "MIT" ]
63l06ri5/bc-csharp
crypto/test/src/x509/test/TestCertificateGen.cs
39,065
C#
using Storage.Classes.Models.TumOnline; using UI_Context.Classes.Context.Dialogs; using Windows.UI.Xaml.Controls; namespace UI.Dialogs { public sealed partial class LectureInfoDialog: ContentDialog { //--------------------------------------------------------Attributes:-----------------------------------------------------------------\\ #region --Attributes-- public readonly LectureInfoDialogContext VIEW_MODEL = new LectureInfoDialogContext(); #endregion //--------------------------------------------------------Constructor:----------------------------------------------------------------\\ #region --Constructors-- public LectureInfoDialog(Lecture lecture) { VIEW_MODEL.MODEL.Lecture = lecture; InitializeComponent(); } #endregion //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\ #region --Set-, Get- Methods-- #endregion //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- #endregion #region --Misc Methods (Private)-- #endregion #region --Misc Methods (Protected)-- #endregion //--------------------------------------------------------Events:---------------------------------------------------------------------\\ #region --Events-- #endregion } }
31.94
144
0.363181
[ "MIT" ]
COM8/TUM_Campus_App_UWP
UI/Dialogs/LectureInfoDialog.xaml.cs
1,599
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IEntityWithReferenceRequest.cs.tt namespace Microsoft.Graph { using System; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IClaimsMappingPolicyWithReferenceRequest. /// </summary> public partial interface IClaimsMappingPolicyWithReferenceRequest : IBaseRequest { /// <summary> /// Gets the specified ClaimsMappingPolicy. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The ClaimsMappingPolicy.</returns> System.Threading.Tasks.Task<ClaimsMappingPolicy> GetAsync(CancellationToken cancellationToken = default); /// <summary> /// Gets the specified ClaimsMappingPolicy and returns a <see cref="GraphResponse{ClaimsMappingPolicy}"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{ClaimsMappingPolicy}"/> object of the request.</returns> System.Threading.Tasks.Task<GraphResponse<ClaimsMappingPolicy>> GetResponseAsync(CancellationToken cancellationToken = default); /// <summary> /// Creates the specified ClaimsMappingPolicy using POST. /// </summary> /// <param name="claimsMappingPolicyToCreate">The ClaimsMappingPolicy to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created ClaimsMappingPolicy.</returns> System.Threading.Tasks.Task<ClaimsMappingPolicy> CreateAsync(ClaimsMappingPolicy claimsMappingPolicyToCreate, CancellationToken cancellationToken = default); /// <summary> /// Creates the specified ClaimsMappingPolicy using POST and returns a <see cref="GraphResponse{ClaimsMappingPolicy}"/> object. /// </summary> /// <param name="claimsMappingPolicyToCreate">The ClaimsMappingPolicy to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{ClaimsMappingPolicy}"/> object of the request.</returns> System.Threading.Tasks.Task<GraphResponse<ClaimsMappingPolicy>> CreateResponseAsync(ClaimsMappingPolicy claimsMappingPolicyToCreate, CancellationToken cancellationToken = default); /// <summary> /// Updates the specified ClaimsMappingPolicy using PATCH. /// </summary> /// <param name="claimsMappingPolicyToUpdate">The ClaimsMappingPolicy to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated ClaimsMappingPolicy.</returns> System.Threading.Tasks.Task<ClaimsMappingPolicy> UpdateAsync(ClaimsMappingPolicy claimsMappingPolicyToUpdate, CancellationToken cancellationToken = default); /// <summary> /// Updates the specified ClaimsMappingPolicy using PATCH and returns a <see cref="GraphResponse{ClaimsMappingPolicy}"/> object. /// </summary> /// <param name="claimsMappingPolicyToUpdate">The ClaimsMappingPolicy to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The <see cref="GraphResponse{ClaimsMappingPolicy}"/> object of the request.</returns> System.Threading.Tasks.Task<GraphResponse<ClaimsMappingPolicy>> UpdateResponseAsync(ClaimsMappingPolicy claimsMappingPolicyToUpdate, CancellationToken cancellationToken = default); /// <summary> /// Deletes the specified ClaimsMappingPolicy. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken = default); /// <summary> /// Deletes the specified ClaimsMappingPolicy and returns a <see cref="GraphResponse"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task of <see cref="GraphResponse"/> to await.</returns> System.Threading.Tasks.Task<GraphResponse> DeleteResponseAsync(CancellationToken cancellationToken = default); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IClaimsMappingPolicyWithReferenceRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> IClaimsMappingPolicyWithReferenceRequest Expand(Expression<Func<ClaimsMappingPolicy, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IClaimsMappingPolicyWithReferenceRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> IClaimsMappingPolicyWithReferenceRequest Select(Expression<Func<ClaimsMappingPolicy, object>> selectExpression); } }
57.669565
188
0.681996
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IClaimsMappingPolicyWithReferenceRequest.cs
6,632
C#
using System; using System.Threading; using System.Threading.Tasks; using ElmSharp; using ElmSharp.Wearable; using EButton = ElmSharp.Button; using EColor = ElmSharp.Color; using EImage = ElmSharp.Image; using ELayout = ElmSharp.Layout; using EWidget = ElmSharp.Widget; namespace Xamarin.Forms.Platform.Tizen.Watch { public class NavigationDrawer : ELayout, IAnimatable { static readonly int TouchWidth = 50; static readonly int IconSize = 40; static readonly string DefaultIcon = "Xamarin.Forms.Platform.Tizen.Resource.wc_visual_cue.png"; Box _mainLayout; Box _contentGestureBox; Box _contentBox; Box _drawerBox; Box _drawerContentBox; Box _drawerIconBox; EvasObject _content; EvasObject _drawerContent; EImage _drawerIcon; EButton _touchArea; GestureLayer _gestureOnContent; GestureLayer _gestureOnDrawer; ImageSource _drawerIconSource; bool _isOpen; bool _isDefaultIcon; CancellationTokenSource _fadeInCancelTokenSource = null; bool HasDrawer => _drawerBox != null; public NavigationDrawer(EvasObject parent) : base(parent) { Initialize(); } public int HandlerHeight { get; set; } = 40; public bool IsOpen { get { return _isOpen; } set { if (_isOpen != value) { if (value) { Open(); } else { Close(); } } } } EColor _handlerBackgroundColor = EColor.Transparent; public EColor HandlerBackgroundColor { get => _handlerBackgroundColor; set { _handlerBackgroundColor = value; UpdateHandlerBackgroundColor(); } } public event EventHandler Toggled; public void SetMainContent(EvasObject content) { if (content == null) { UnsetMainContent(); return; } _content = content; _content.Show(); _contentBox.PackEnd(_content); _content.Geometry = _contentBox.Geometry; } public void SetDrawerContent(EvasObject content) { InitializeDrawerBox(); if (content == null) { UnsetDrawerContent(); return; } _drawerContent = content; _drawerContent.Show(); _drawerContentBox.PackEnd(_drawerContent); _drawerContentBox.Show(); _drawerIconBox.Show(); if (_drawerContent is NavigationView nv) { nv.Dragged += (s, e) => { if (e.State == DraggedState.EdgeTop) { Close(); } }; } } public void UpdateDrawerIcon(ImageSource source) { _drawerIconSource = source; if (HasDrawer) { SetDrawerIcon(_drawerIconSource); } } public async void Open(uint length = 300) { if (!HasDrawer) return; var toMove = _drawerBox.Geometry; toMove.Y = 0; await RunMoveAnimation(_drawerBox, toMove, length); if (!_isOpen) { _isOpen = true; Toggled?.Invoke(this, EventArgs.Empty); } OnLayout(); OnDrawerLayout(); FlipIcon(); } public async void Close(uint length = 300) { if (!HasDrawer) return; var toMove = _drawerBox.Geometry; toMove.Y = Geometry.Height - HandlerHeight; await RunMoveAnimation(_drawerBox, toMove, length); if (_isOpen) { _isOpen = false; Toggled?.Invoke(this, EventArgs.Empty); } OnLayout(); OnDrawerLayout(); ResetIcon(); StartHighlightAnimation(_drawerIcon); } void IAnimatable.BatchBegin() { } void IAnimatable.BatchCommit() { } protected override IntPtr CreateHandle(EvasObject parent) { _mainLayout = new Box(parent); return _mainLayout.Handle; } void Initialize() { _mainLayout.SetLayoutCallback(OnLayout); _contentGestureBox = new Box(_mainLayout); _contentGestureBox.Show(); _mainLayout.PackEnd(_contentGestureBox); _contentBox = new Box(_mainLayout); _contentBox.SetLayoutCallback(OnContentLayout); _contentBox.Show(); _mainLayout.PackEnd(_contentBox); } void InitializeDrawerBox() { if (_drawerBox != null) return; _drawerBox = new Box(_mainLayout); _drawerBox.SetLayoutCallback(OnDrawerLayout); _drawerBox.Show(); _mainLayout.PackEnd(_drawerBox); _drawerContentBox = new Box(_drawerBox); _drawerBox.PackEnd(_drawerContentBox); _drawerIconBox = new Box(_drawerBox) { BackgroundColor = _handlerBackgroundColor }; _drawerBox.PackEnd(_drawerIconBox); _drawerIcon = new EImage(_drawerIconBox) { AlignmentY = 0.5, AlignmentX = 0.5, MinimumHeight = IconSize, MinimumWidth = IconSize, }; _drawerIcon.Show(); _drawerIconBox.PackEnd(_drawerIcon); SetDrawerIcon(_drawerIconSource); _touchArea = new EButton(_drawerBox) { Color = EColor.Transparent, BackgroundColor = EColor.Transparent, }; _touchArea.SetPartColor("effect", EColor.Transparent); _touchArea.Show(); _touchArea.RepeatEvents = true; _touchArea.Clicked += OnIconClicked; _drawerBox.PackEnd(_touchArea); _gestureOnContent = new GestureLayer(_contentGestureBox); _gestureOnContent.SetMomentumCallback(GestureLayer.GestureState.Start, OnContentDragStarted); _gestureOnContent.SetMomentumCallback(GestureLayer.GestureState.End, OnContentDragEnded); _gestureOnContent.SetMomentumCallback(GestureLayer.GestureState.Abort, OnContentDragEnded); _gestureOnContent.Attach(_contentGestureBox); _contentBox.RepeatEvents = true; _gestureOnDrawer = new GestureLayer(_drawerIconBox); _gestureOnDrawer.SetMomentumCallback(GestureLayer.GestureState.Move, OnDrawerDragged); _gestureOnDrawer.SetMomentumCallback(GestureLayer.GestureState.End, OnDrawerDragEnded); _gestureOnDrawer.SetMomentumCallback(GestureLayer.GestureState.Abort, OnDrawerDragEnded); _gestureOnDrawer.Attach(_drawerIconBox); RotaryEventManager.Rotated += OnRotateEventReceived; } void SetDrawerIcon(ImageSource source) { if (source == null) { _ = _drawerIcon.LoadFromImageSourceAsync(ImageSource.FromResource(DefaultIcon, GetType().Assembly)); _isDefaultIcon = true; } else { _isDefaultIcon = false; if (source is FileImageSource fsource) { _drawerIcon.Load(fsource.ToAbsPath()); } else { _ = _drawerIcon.LoadFromImageSourceAsync(source); } } } void UpdateHandlerBackgroundColor() { if (_drawerIconBox != null) { _drawerIconBox.BackgroundColor = _handlerBackgroundColor; } } void OnIconClicked(object sender, EventArgs e) { if (IsOpen) Close(); else Open(); } async Task<bool> ShowAsync(EWidget target, Easing easing = null, uint length = 300, CancellationToken cancelltaionToken = default(CancellationToken)) { var tcs = new TaskCompletionSource<bool>(); await Task.Delay(1000); if (cancelltaionToken.IsCancellationRequested) { cancelltaionToken.ThrowIfCancellationRequested(); } target.Show(); var opacity = target.Opacity; if (opacity == 255 || opacity == -1) return true; new Animation((progress) => { target.Opacity = opacity + (int)((255 - opacity) * progress); }).Commit(this, "FadeIn", length: length, finished: (p, e) => { target.Opacity = 255; tcs.SetResult(true); StartHighlightAnimation(_drawerIcon); }); return await tcs.Task; } void OnLayout() { var bound = Geometry; _contentGestureBox.Geometry = bound; _contentBox.Geometry = bound; if (_drawerBox != null) { bound.Y = _isOpen ? 0 : (bound.Height - HandlerHeight); _drawerBox.Geometry = bound; } } void OnContentLayout() { if (_content != null) { _content.Geometry = _contentBox.Geometry; } } void OnDrawerLayout() { this.AbortAnimation("HighlightAnimation"); var bound = _drawerBox.Geometry; var currentY = bound.Y; var ratio = currentY / (double)(Geometry.Height - HandlerHeight); var contentBound = bound; contentBound.Y += (int)(HandlerHeight * ratio); _drawerContentBox.Geometry = contentBound; var drawerHandleBound = bound; drawerHandleBound.Height = HandlerHeight; _drawerIconBox.Geometry = drawerHandleBound; var drawerTouchBound = drawerHandleBound; drawerTouchBound.Width = TouchWidth; drawerTouchBound.X = drawerHandleBound.X + (drawerHandleBound.Width - TouchWidth) / 2; _touchArea.Geometry = drawerTouchBound; } async Task<bool> HideAsync(EWidget target, Easing easing = null, uint length = 300) { var tcs = new TaskCompletionSource<bool>(); var opacity = target.Opacity; if (opacity == -1) opacity = 255; new Animation((progress) => { target.Opacity = opacity - (int)(progress * opacity); }).Commit(this, "FadeOut", length: length, finished: (p, e) => { target.Opacity = 0; target.Hide(); tcs.SetResult(true); }); return await tcs.Task; } void StartHighlightAnimation(EWidget target) { if (!_isDefaultIcon || this.AnimationIsRunning("HighlightAnimation")) return; int count = 2; var bound = target.Geometry; var y = bound.Y; var dy = bound.Y - bound.Height / 3; var anim = new Animation(); var transfAnim = new Animation((f) => { bound.Y = (int)f; var map = new EvasMap(4); map.PopulatePoints(bound, 0); target.IsMapEnabled = true; target.EvasMap = map; }, y, dy); var opacityAnim = new Animation(f => target.Opacity = (int)f, 255, 40); anim.Add(0, 1, opacityAnim); anim.Add(0, 1, transfAnim); anim.Commit(this, "HighlightAnimation", 16, 800, finished: (f, b) => { target.Opacity = 255; target.IsMapEnabled = false; }, repeat: () => --count > 0); } async void OnRotateEventReceived(EventArgs args) { _fadeInCancelTokenSource?.Cancel(); _fadeInCancelTokenSource = new CancellationTokenSource(); if (!_isOpen) { var token = _fadeInCancelTokenSource.Token; await HideAsync(_drawerBox); _ = ShowAsync(_drawerBox, cancelltaionToken: token); } } void OnContentDragStarted(GestureLayer.MomentumData moment) { _fadeInCancelTokenSource?.Cancel(); _fadeInCancelTokenSource = null; if (!_isOpen) { _ = HideAsync(_drawerBox); } } void OnContentDragEnded(GestureLayer.MomentumData moment) { _fadeInCancelTokenSource = new CancellationTokenSource(); _ = ShowAsync(_drawerBox, cancelltaionToken: _fadeInCancelTokenSource.Token); } void OnDrawerDragged(GestureLayer.MomentumData moment) { var toMove = _drawerBox.Geometry; toMove.Y = (moment.Y2 < 0) ? 0 : moment.Y2; _drawerBox.Geometry = toMove; OnDrawerLayout(); } void OnDrawerDragEnded(GestureLayer.MomentumData moment) { if (_drawerBox.Geometry.Y < (_mainLayout.Geometry.Height / 2)) { Open(); } else { Close(); } } void FlipIcon() { if (_isDefaultIcon) { _drawerIcon.Orientation = ImageOrientation.FlipVertical; } } void ResetIcon() { _drawerIcon.Orientation = ImageOrientation.None; } Task RunMoveAnimation(EvasObject target, Rect dest, uint length, Easing easing = null) { var tcs = new TaskCompletionSource<bool>(); var dx = target.Geometry.X - dest.X; var dy = target.Geometry.Y - dest.Y; new Animation((progress) => { var toMove = dest; toMove.X += (int)(dx * (1 - progress)); toMove.Y += (int)(dy * (1 - progress)); target.Geometry = toMove; OnDrawerLayout(); }).Commit(this, "Move", length: length, finished: (s, e) => { target.Geometry = dest; tcs.SetResult(true); }); return tcs.Task; } void UnsetMainContent() { if (_content != null) { _contentBox.UnPack(_content); _content.Hide(); _content = null; } } void UnsetDrawerContent() { if (_drawerContent != null) { _drawerContentBox.UnPack(_drawerContent); _drawerContent.Hide(); _drawerContent = null; _drawerContentBox.Hide(); _drawerIconBox.Hide(); } } } }
21.862963
151
0.680586
[ "MIT" ]
Ezeji/Xamarin.Forms
Xamarin.Forms.Platform.Tizen/Shell/Watch/NavigationDrawer.cs
11,808
C#
using System; namespace VertSoft.Peppol.Common.Lang { public class PeppolRuntimeExceptionTest { public virtual void simpleConstructors() { new PeppolRuntimeException("Message", new Exception("innerdummy")); } } }
16.214286
70
0.748899
[ "MIT" ]
BartVertongen/Peppol.NETCoreLib
PeppolNETCoreTest/Common/lang/PeppolRuntimeExceptionTest.cs
227
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MS-PL license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using MvvmCross.Exceptions; using Nivaes.App.Cross.Logging; namespace MvvmCross.IoC { [Obsolete("Sustituir por Autofac")] public class MvxTypeCache<TType> : IMvxTypeCache<TType> { public Dictionary<string, Type> LowerCaseFullNameCache { get; } = new Dictionary<string, Type>(); public Dictionary<string, Type> FullNameCache { get; } = new Dictionary<string, Type>(); public Dictionary<string, Type> NameCache { get; } = new Dictionary<string, Type>(); public Dictionary<Assembly, bool> CachedAssemblies { get; } = new Dictionary<Assembly, bool>(); public void AddAssembly(Assembly assembly) { if (assembly == null) throw new ArgumentNullException(nameof(assembly)); try { if (CachedAssemblies.ContainsKey(assembly)) return; var viewType = typeof(TType); var query = assembly.DefinedTypes.Where(ti => ti.IsSubclassOf(viewType)).Select(ti => ti.AsType()); foreach (var type in query) { var fullName = type.FullName; if (!string.IsNullOrEmpty(fullName)) { FullNameCache[fullName] = type; LowerCaseFullNameCache[fullName.ToLowerInvariant()] = type; } var name = type.Name; if (!string.IsNullOrEmpty(name)) NameCache[name] = type; } CachedAssemblies[assembly] = true; } catch (ReflectionTypeLoadException e) { MvxLog.Instance?.Warn("ReflectionTypeLoadException masked during loading of {0} - error {1}", assembly.FullName, e.ToLongString()); } } } }
36.79661
115
0.576693
[ "MIT" ]
Nivaes/Nivaes.App.Cross
Nivaes.App.Cross/Components/IoC.Old/MvxTypeCache.cs
2,173
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.WebJobs.Protocols; namespace Dashboard.Data { /// <summary>Defines a monitor for valid running host heartbeats.</summary> /// <remarks> /// Differs from <see cref="IHeartbeatMonitor"/> in that it is simpler and only returns <see cref="bool"/> /// indicating validity rather than an expiration time. /// </remarks> public interface IHeartbeatValidityMonitor { /// <summary>Determines if at least one instance heartbeat is valid for a host.</summary> /// <param name="sharedContainerName"> /// The name of the heartbeat container shared by all instances of the host. /// </param> /// <param name="sharedDirectoryName"> /// The name of the directory in <paramref name="sharedContainerName"/> shared by all instances of the host. /// </param> /// <param name="expirationInSeconds">The number of seconds after the heartbeat that it expires.</param> /// <returns> /// <see langword="true"/> if at least one instance heartbeat is valid for the host; otherwise, /// <see langword="false"/>. /// </returns> bool IsSharedHeartbeatValid(string sharedContainerName, string sharedDirectoryName, int expirationInSeconds); /// <summary>Determines if a host instance has a valid heartbeat.</summary> /// <param name="sharedContainerName"> /// The name of the heartbeat container shared by all instances of the host. /// </param> /// <param name="sharedDirectoryName"> /// The name of the directory in <paramref name="sharedContainerName"/> shared by all instances of the host. /// </param> /// <param name="instanceBlobName"> /// The name of the host instance heartbeat blob in <paramref name="sharedDirectoryName"/>. /// </param> /// <param name="expirationInSeconds">The number of seconds after the heartbeat that it expires.</param> /// <returns> /// <see langword="true"/> if the host instance has a valid heartbeat; otherwise, <see langword="false"/>. /// </returns> bool IsInstanceHeartbeatValid(string sharedContainerName, string sharedDirectoryName, string instanceBlobName, int expirationInSeconds); } }
51.957447
118
0.662572
[ "MIT" ]
Bjakes1950/azure-webjobs-sdk
src/Dashboard/Data/IHeartbeatValidityMonitor.cs
2,444
C#
using System; namespace TaLib { public partial class Core { public static RetCode MacdExt(int startIdx, int endIdx, double[] inReal, int optInFastPeriod, MAType optInFastMAType, int optInSlowPeriod, MAType optInSlowMAType, int optInSignalPeriod, MAType optInSignalMAType, ref int outBegIdx, ref int outNBElement, double[] outMACD, double[] outMACDSignal, double[] outMACDHist) { int i; int tempInteger = 0; int outNbElement1 = 0; int outNbElement2 = 0; int outBegIdx2 = 0; int outBegIdx1 = 0; if (startIdx < 0) { return RetCode.OutOfRangeStartIndex; } if ((endIdx < 0) || (endIdx < startIdx)) { return RetCode.OutOfRangeEndIndex; } if (inReal == null) { return RetCode.BadParam; } if (optInFastPeriod == -2147483648) { optInFastPeriod = 12; } else if ((optInFastPeriod < 2) || (optInFastPeriod > 0x186a0)) { return RetCode.BadParam; } if (optInSlowPeriod == -2147483648) { optInSlowPeriod = 0x1a; } else if ((optInSlowPeriod < 2) || (optInSlowPeriod > 0x186a0)) { return RetCode.BadParam; } if (optInSignalPeriod == -2147483648) { optInSignalPeriod = 9; } else if ((optInSignalPeriod < 1) || (optInSignalPeriod > 0x186a0)) { return RetCode.BadParam; } if (outMACD == null) { return RetCode.BadParam; } if (outMACDSignal == null) { return RetCode.BadParam; } if (outMACDHist == null) { return RetCode.BadParam; } if (optInSlowPeriod < optInFastPeriod) { tempInteger = optInSlowPeriod; optInSlowPeriod = optInFastPeriod; optInFastPeriod = tempInteger; MAType tempMAType = optInSlowMAType; optInSlowMAType = optInFastMAType; optInFastMAType = tempMAType; } int lookbackLargest = MovingAverageLookback(optInFastPeriod, optInFastMAType); tempInteger = MovingAverageLookback(optInSlowPeriod, optInSlowMAType); if (tempInteger > lookbackLargest) { lookbackLargest = tempInteger; } int lookbackSignal = MovingAverageLookback(optInSignalPeriod, optInSignalMAType); int lookbackTotal = lookbackSignal + lookbackLargest; if (startIdx < lookbackTotal) { startIdx = lookbackTotal; } if (startIdx > endIdx) { outBegIdx = 0; outNBElement = 0; return RetCode.Success; } tempInteger = ((endIdx - startIdx) + 1) + lookbackSignal; double[] fastMABuffer = new double[tempInteger]; if (fastMABuffer == null) { outBegIdx = 0; outNBElement = 0; return RetCode.AllocErr; } double[] slowMABuffer = new double[tempInteger]; if (slowMABuffer == null) { outBegIdx = 0; outNBElement = 0; return RetCode.AllocErr; } tempInteger = startIdx - lookbackSignal; RetCode retCode = MovingAverage(tempInteger, endIdx, inReal, optInSlowPeriod, optInSlowMAType, ref outBegIdx1, ref outNbElement1, slowMABuffer); if (retCode != RetCode.Success) { outBegIdx = 0; outNBElement = 0; return retCode; } retCode = MovingAverage(tempInteger, endIdx, inReal, optInFastPeriod, optInFastMAType, ref outBegIdx2, ref outNbElement2, fastMABuffer); if (retCode != RetCode.Success) { outBegIdx = 0; outNBElement = 0; return retCode; } if (((outBegIdx1 != tempInteger) || (outBegIdx2 != tempInteger)) || ((outNbElement1 != outNbElement2) || (outNbElement1 != (((endIdx - startIdx) + 1) + lookbackSignal)))) { outBegIdx = 0; outNBElement = 0; return RetCode.InternalError; } for (i = 0; i < outNbElement1; i++) { fastMABuffer[i] -= slowMABuffer[i]; } Array.Copy(fastMABuffer, lookbackSignal, outMACD, 0, (endIdx - startIdx) + 1); retCode = MovingAverage(0, outNbElement1 - 1, fastMABuffer, optInSignalPeriod, optInSignalMAType, ref outBegIdx2, ref outNbElement2, outMACDSignal); if (retCode != RetCode.Success) { outBegIdx = 0; outNBElement = 0; return retCode; } for (i = 0; i < outNbElement2; i++) { outMACDHist[i] = outMACD[i] - outMACDSignal[i]; } outBegIdx = startIdx; outNBElement = outNbElement2; return RetCode.Success; } public static RetCode MacdExt(int startIdx, int endIdx, float[] inReal, int optInFastPeriod, MAType optInFastMAType, int optInSlowPeriod, MAType optInSlowMAType, int optInSignalPeriod, MAType optInSignalMAType, ref int outBegIdx, ref int outNBElement, double[] outMACD, double[] outMACDSignal, double[] outMACDHist) { int i; int tempInteger = 0; int outNbElement1 = 0; int outNbElement2 = 0; int outBegIdx2 = 0; int outBegIdx1 = 0; if (startIdx < 0) { return RetCode.OutOfRangeStartIndex; } if ((endIdx < 0) || (endIdx < startIdx)) { return RetCode.OutOfRangeEndIndex; } if (inReal == null) { return RetCode.BadParam; } if (optInFastPeriod == -2147483648) { optInFastPeriod = 12; } else if ((optInFastPeriod < 2) || (optInFastPeriod > 0x186a0)) { return RetCode.BadParam; } if (optInSlowPeriod == -2147483648) { optInSlowPeriod = 0x1a; } else if ((optInSlowPeriod < 2) || (optInSlowPeriod > 0x186a0)) { return RetCode.BadParam; } if (optInSignalPeriod == -2147483648) { optInSignalPeriod = 9; } else if ((optInSignalPeriod < 1) || (optInSignalPeriod > 0x186a0)) { return RetCode.BadParam; } if (outMACD == null) { return RetCode.BadParam; } if (outMACDSignal == null) { return RetCode.BadParam; } if (outMACDHist == null) { return RetCode.BadParam; } if (optInSlowPeriod < optInFastPeriod) { tempInteger = optInSlowPeriod; optInSlowPeriod = optInFastPeriod; optInFastPeriod = tempInteger; MAType tempMAType = optInSlowMAType; optInSlowMAType = optInFastMAType; optInFastMAType = tempMAType; } int lookbackLargest = MovingAverageLookback(optInFastPeriod, optInFastMAType); tempInteger = MovingAverageLookback(optInSlowPeriod, optInSlowMAType); if (tempInteger > lookbackLargest) { lookbackLargest = tempInteger; } int lookbackSignal = MovingAverageLookback(optInSignalPeriod, optInSignalMAType); int lookbackTotal = lookbackSignal + lookbackLargest; if (startIdx < lookbackTotal) { startIdx = lookbackTotal; } if (startIdx > endIdx) { outBegIdx = 0; outNBElement = 0; return RetCode.Success; } tempInteger = ((endIdx - startIdx) + 1) + lookbackSignal; double[] fastMABuffer = new double[tempInteger]; if (fastMABuffer == null) { outBegIdx = 0; outNBElement = 0; return RetCode.AllocErr; } double[] slowMABuffer = new double[tempInteger]; if (slowMABuffer == null) { outBegIdx = 0; outNBElement = 0; return RetCode.AllocErr; } tempInteger = startIdx - lookbackSignal; RetCode retCode = MovingAverage(tempInteger, endIdx, inReal, optInSlowPeriod, optInSlowMAType, ref outBegIdx1, ref outNbElement1, slowMABuffer); if (retCode != RetCode.Success) { outBegIdx = 0; outNBElement = 0; return retCode; } retCode = MovingAverage(tempInteger, endIdx, inReal, optInFastPeriod, optInFastMAType, ref outBegIdx2, ref outNbElement2, fastMABuffer); if (retCode != RetCode.Success) { outBegIdx = 0; outNBElement = 0; return retCode; } if (((outBegIdx1 != tempInteger) || (outBegIdx2 != tempInteger)) || ((outNbElement1 != outNbElement2) || (outNbElement1 != (((endIdx - startIdx) + 1) + lookbackSignal)))) { outBegIdx = 0; outNBElement = 0; return RetCode.InternalError; } for (i = 0; i < outNbElement1; i++) { fastMABuffer[i] -= slowMABuffer[i]; } Array.Copy(fastMABuffer, lookbackSignal, outMACD, 0, (endIdx - startIdx) + 1); retCode = MovingAverage(0, outNbElement1 - 1, fastMABuffer, optInSignalPeriod, optInSignalMAType, ref outBegIdx2, ref outNbElement2, outMACDSignal); if (retCode != RetCode.Success) { outBegIdx = 0; outNBElement = 0; return retCode; } for (i = 0; i < outNbElement2; i++) { outMACDHist[i] = outMACD[i] - outMACDSignal[i]; } outBegIdx = startIdx; outNBElement = outNbElement2; return RetCode.Success; } public static int MacdExtLookback(int optInFastPeriod, MAType optInFastMAType, int optInSlowPeriod, MAType optInSlowMAType, int optInSignalPeriod, MAType optInSignalMAType) { if (optInFastPeriod == -2147483648) { optInFastPeriod = 12; } else if ((optInFastPeriod < 2) || (optInFastPeriod > 0x186a0)) { return -1; } if (optInSlowPeriod == -2147483648) { optInSlowPeriod = 0x1a; } else if ((optInSlowPeriod < 2) || (optInSlowPeriod > 0x186a0)) { return -1; } if (optInSignalPeriod == -2147483648) { optInSignalPeriod = 9; } else if ((optInSignalPeriod < 1) || (optInSignalPeriod > 0x186a0)) { return -1; } int lookbackLargest = MovingAverageLookback(optInFastPeriod, optInFastMAType); int tempInteger = MovingAverageLookback(optInSlowPeriod, optInSlowMAType); if (tempInteger > lookbackLargest) { lookbackLargest = tempInteger; } return (lookbackLargest + MovingAverageLookback(optInSignalPeriod, optInSignalMAType)); } } }
43.913208
324
0.531494
[ "Apache-2.0" ]
QuantBox/QuantBoxXProvider
TALib/TAFunc/TA_MacdExt.cs
11,637
C#
namespace BuildingDrainageConsultant.Data.Seeding.ExcelSeeders { public static class ExcelSeedingConstants { public class Drains { public const int NameColumn = 0; public const int DescriptionColumn = 1; public const int FlowRateColumn = 2; public const int DrainageAreaColumn = 3; public const int DepthColumn = 4; public const int DirectionColumn = 5; public const int DiameterColumn = 6; public const int VisiblePartColumn = 7; public const int WaterproofingColumn = 8; public const int HeatingColumn = 9; public const int RenovationColumn = 10; public const int FlapSealColumn = 11; public const int LoadClassColumn = 12; public const int ImageColumn = 13; public const int WaterproofingKitColumn = 14; public const int AccessoriesColumn = 15; } public class SafeDrains { public const int NameColumn = 0; public const int DescriptionColumn = 1; public const int FlowRateFreeColumn = 2; public const int FlowRate3mVerticalColumn = 3; public const int DrainageAreaFreeColumn = 4; public const int DrainageArea3mVerticalColumn = 5; public const int DepthColumn = 6; public const int DirectionColumn = 7; public const int DiameterColumn = 8; public const int WaterproofingColumn = 9; public const int HeatingColumn = 10; public const int ImageColumn = 11; } public class Attica { public const int NameColumn = 0; public const int DescriptionColumn = 1; public const int AtticaPartsColumn = 0; public const int AtticaPartImageNameColumn = 2; public const int AtticaDetailIdColumn = 1; public const int WalkableColumn = 2; public const int RoofTypeColumn = 3; public const int ScreedWaterproofingColumn = 4; public const int ConcreteWaterproofingColumn = 5; public const int DiameterColumn = 6; public const int VisiblePartColumn = 7; public const int FlowRate35mmColumn = 8; public const int FlowRate100mmColumn = 9; public const int DrainageArea35mmColumn = 10; public const int DrainageArea100mmColumn = 11; } public class Merchants { public const int NameColumn = 0; public const int CityColumn = 1; public const int AddressColumn = 2; public const int EmailColumn = 3; public const int PhoneColumn = 4; public const int WebsiteColumn = 5; public const int LatitudeColumn = 6; public const int LongitudeColumn = 7; } } }
39.837838
63
0.600407
[ "MIT" ]
AlShandor/ASP.NET-Core-Project-Building-Drainage-Consultant
BuildingDrainageConsultant/Data/Seeding/ExcelSeeders/ExcelSeedingConstants.cs
2,950
C#
using System; using System.Collections.Generic; using NHapi.Base.Log; using NHapi.Model.V24.Group; using NHapi.Model.V24.Segment; using NHapi.Model.V24.Datatype; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; namespace NHapi.Model.V24.Message { ///<summary> /// Represents a RPI_I01 message structure (see chapter 11). This structure contains the /// following elements: ///<ol> ///<li>0: MSH (Message Header) </li> ///<li>1: MSA (Message Acknowledgment) </li> ///<li>2: RPI_I01_PROVIDER (a Group object) repeating</li> ///<li>3: PID (Patient identification) </li> ///<li>4: NK1 (Next of kin / associated parties) optional repeating</li> ///<li>5: RPI_I01_GUARANTOR_INSURANCE (a Group object) optional </li> ///<li>6: NTE (Notes and Comments) optional repeating</li> ///</ol> ///</summary> [Serializable] public class RPI_I01 : AbstractMessage { ///<summary> /// Creates a new RPI_I01 Group with custom IModelClassFactory. ///</summary> public RPI_I01(IModelClassFactory factory) : base(factory){ init(factory); } ///<summary> /// Creates a new RPI_I01 Group with DefaultModelClassFactory. ///</summary> public RPI_I01() : base(new DefaultModelClassFactory()) { init(new DefaultModelClassFactory()); } ///<summary> /// initalize method for RPI_I01. This does the segment setup for the message. ///</summary> private void init(IModelClassFactory factory) { try { this.add(typeof(MSH), true, false); this.add(typeof(MSA), true, false); this.add(typeof(RPI_I01_PROVIDER), true, true); this.add(typeof(PID), true, false); this.add(typeof(NK1), false, true); this.add(typeof(RPI_I01_GUARANTOR_INSURANCE), false, false); this.add(typeof(NTE), false, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating RPI_I01 - this is probably a bug in the source code generator.", e); } } public override string Version { get{ return Constants.VERSION; } } ///<summary> /// Returns MSH (Message Header) - creates it if necessary ///</summary> public MSH MSH { get{ MSH ret = null; try { ret = (MSH)this.GetStructure("MSH"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns MSA (Message Acknowledgment) - creates it if necessary ///</summary> public MSA MSA { get{ MSA ret = null; try { ret = (MSA)this.GetStructure("MSA"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of RPI_I01_PROVIDER (a Group object) - creates it if necessary ///</summary> public RPI_I01_PROVIDER GetPROVIDER() { RPI_I01_PROVIDER ret = null; try { ret = (RPI_I01_PROVIDER)this.GetStructure("PROVIDER"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of RPI_I01_PROVIDER /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public RPI_I01_PROVIDER GetPROVIDER(int rep) { return (RPI_I01_PROVIDER)this.GetStructure("PROVIDER", rep); } /** * Returns the number of existing repetitions of RPI_I01_PROVIDER */ public int PROVIDERRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("PROVIDER").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the RPI_I01_PROVIDER results */ public IEnumerable<RPI_I01_PROVIDER> PROVIDERs { get { for (int rep = 0; rep < PROVIDERRepetitionsUsed; rep++) { yield return (RPI_I01_PROVIDER)this.GetStructure("PROVIDER", rep); } } } ///<summary> ///Adds a new RPI_I01_PROVIDER ///</summary> public RPI_I01_PROVIDER AddPROVIDER() { return this.AddStructure("PROVIDER") as RPI_I01_PROVIDER; } ///<summary> ///Removes the given RPI_I01_PROVIDER ///</summary> public void RemovePROVIDER(RPI_I01_PROVIDER toRemove) { this.RemoveStructure("PROVIDER", toRemove); } ///<summary> ///Removes the RPI_I01_PROVIDER at the given index ///</summary> public void RemovePROVIDERAt(int index) { this.RemoveRepetition("PROVIDER", index); } ///<summary> /// Returns PID (Patient identification) - creates it if necessary ///</summary> public PID PID { get{ PID ret = null; try { ret = (PID)this.GetStructure("PID"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of NK1 (Next of kin / associated parties) - creates it if necessary ///</summary> public NK1 GetNK1() { NK1 ret = null; try { ret = (NK1)this.GetStructure("NK1"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of NK1 /// * (Next of kin / associated parties) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public NK1 GetNK1(int rep) { return (NK1)this.GetStructure("NK1", rep); } /** * Returns the number of existing repetitions of NK1 */ public int NK1RepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("NK1").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the NK1 results */ public IEnumerable<NK1> NK1s { get { for (int rep = 0; rep < NK1RepetitionsUsed; rep++) { yield return (NK1)this.GetStructure("NK1", rep); } } } ///<summary> ///Adds a new NK1 ///</summary> public NK1 AddNK1() { return this.AddStructure("NK1") as NK1; } ///<summary> ///Removes the given NK1 ///</summary> public void RemoveNK1(NK1 toRemove) { this.RemoveStructure("NK1", toRemove); } ///<summary> ///Removes the NK1 at the given index ///</summary> public void RemoveNK1At(int index) { this.RemoveRepetition("NK1", index); } ///<summary> /// Returns RPI_I01_GUARANTOR_INSURANCE (a Group object) - creates it if necessary ///</summary> public RPI_I01_GUARANTOR_INSURANCE GUARANTOR_INSURANCE { get{ RPI_I01_GUARANTOR_INSURANCE ret = null; try { ret = (RPI_I01_GUARANTOR_INSURANCE)this.GetStructure("GUARANTOR_INSURANCE"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of NTE (Notes and Comments) - creates it if necessary ///</summary> public NTE GetNTE() { NTE ret = null; try { ret = (NTE)this.GetStructure("NTE"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of NTE /// * (Notes and Comments) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public NTE GetNTE(int rep) { return (NTE)this.GetStructure("NTE", rep); } /** * Returns the number of existing repetitions of NTE */ public int NTERepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("NTE").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the NTE results */ public IEnumerable<NTE> NTEs { get { for (int rep = 0; rep < NTERepetitionsUsed; rep++) { yield return (NTE)this.GetStructure("NTE", rep); } } } ///<summary> ///Adds a new NTE ///</summary> public NTE AddNTE() { return this.AddStructure("NTE") as NTE; } ///<summary> ///Removes the given NTE ///</summary> public void RemoveNTE(NTE toRemove) { this.RemoveStructure("NTE", toRemove); } ///<summary> ///Removes the NTE at the given index ///</summary> public void RemoveNTEAt(int index) { this.RemoveRepetition("NTE", index); } } }
28.180593
146
0.637877
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
afaonline/nHapi
src/NHapi.Model.V24/Message/RPI_I01.cs
10,455
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("NeighboursCommunitySystem.Data")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NeighboursCommunitySystem.Data")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("47c20bdb-92f3-4b97-8950-e984b5526faa")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.72973
84
0.750174
[ "MIT" ]
Community-Manager/NCS-Server
Source/Data/NeighboursCommunitySystem.Data/Properties/AssemblyInfo.cs
1,436
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text.RegularExpressions; using Flantter.MilkyWay.Common; using Flantter.MilkyWay.Models.Apis.Objects; using Flantter.MilkyWay.Models.Exceptions; namespace Flantter.MilkyWay.Models.Filter { public static class FilterFunctions { public static Dictionary<string, Function> Functions = new Dictionary<string, Function>(); public static void Register(string functionName, int argumentCount, Delegate dele) { if (Functions.ContainsKey(functionName)) return; var function = new Function(functionName, argumentCount, dele); Functions.Add(functionName, function); } public static void Unregister(string functionName) { if (!Functions.ContainsKey(functionName)) return; Functions.Remove(functionName); } public static bool Invoke(string functionName, bool defaultValue, params object[] param) { if (!Functions.ContainsKey(functionName)) return defaultValue; return defaultValue; } public struct Function { public string Name; public int ArgumentCount; public Delegate Delegate; public Function(string name, int nrgumentCount, Delegate dele) : this() { Name = name; ArgumentCount = nrgumentCount; Delegate = dele; } } } public struct Token { #region Priority List public static readonly List<TokenId> Priority1 = new List<TokenId> { TokenId.Multiplication, // * TokenId.Division, // / TokenId.Modulo // % }; public static readonly List<TokenId> Priority2 = new List<TokenId> { TokenId.Plus, // + TokenId.Minus // - }; public static readonly List<TokenId> Priority3 = new List<TokenId> { TokenId.Function, // 関数 TokenId.Equal, // == TokenId.NotEqual, // != TokenId.LessThanEqual, // <= TokenId.GreaterThanEqual, // >= TokenId.LessThan, // < TokenId.GreaterThan, // > TokenId.Contains, // Contains TokenId.StartsWith, // StartsWith TokenId.EndsWith, // EndsWith TokenId.RegexMatch, // RegexMatch TokenId.In, // In TokenId.NotContains, // !Contains TokenId.NotStartsWith, // !StartsWith TokenId.NotEndsWith, // !EndsWith TokenId.NotRegexMatch, // !RegexMatch TokenId.NotIn // !In }; public static readonly List<TokenId> Priority4 = new List<TokenId> { TokenId.And, // && TokenId.Or, // || TokenId.Exclamation // ! }; public static readonly List<TokenId> PriorityOther = new List<TokenId> { TokenId.String, // "こ↑こ↓のぶぶん" TokenId.Numeric, // 数字(整数) TokenId.Space, // 空白 TokenId.Boolean, // ブール代数 TokenId.Literal, // いろいろ TokenId.Null, // Null TokenId.Function, // 関数 TokenId.LiteralExpression, // いろいろ変換した後のリテラル TokenId.NumericArrayExpression, // 数字配列のリテラル TokenId.StringArrayExpression, // 文字列配列のリテラル TokenId.ExpressionParam // Expressionのパラメータ }; #endregion public enum TokenId { // 優先度 0 Period, // . OpenBracket, // ( CloseBracket, // ) OpenSquareBracket, // [ CloseSquareBracket, // ] Comma, // , // 優先度 1 Multiplication, // * Division, // / Modulo, // % // 優先度 2 Plus, // + Minus, // - // 優先度 3 Equal, // == NotEqual, // != LessThanEqual, // <= GreaterThanEqual, // >= LessThan, // < GreaterThan, // > Contains, // Contains StartsWith, // StartsWith EndsWith, // EndsWith RegexMatch, // RegexMatch In, // In NotContains, // !Contains NotStartsWith, // !StartsWith NotEndsWith, // !EndsWith NotRegexMatch, // !RegexMatch NotIn, // !In // 優先度 4 And, // && Or, // || Exclamation, // ! // いろいろ String, // "こ↑こ↓のぶぶん" Numeric, // 数字(整数) Space, // 空白 Boolean, // ブール代数 Literal, // いろいろ Null, // Null Function, // 関数 // ??? LiteralExpression, // いろいろ変換した後のリテラル NumericArrayExpression, // 数字配列のリテラル StringArrayExpression, // 文字列配列のリテラル ExpressionParam // Expressionのパラメータ } public TokenId Type; public object Value; public int Pos; public Token(TokenId type, int pos) : this() { Type = type; Value = null; Pos = pos; } public Token(TokenId type, object value, int pos) : this() { Type = type; Value = value; Pos = pos; } } public static class Compiler { public static Delegate Compile(string filterString, bool defaultValue = true) { Debug.WriteLine("\n-- Compile Filter --\n"); var paramExpr = Expression.Parameter(typeof(Status)); #region Check FilterString Debug.WriteLine("\n-- String Check --\n"); if (!filterString.StartsWith("(")) filterString = "(" + filterString + ")"; #endregion #region Tokenize Debug.WriteLine("\n-- Tokenize --\n"); var tokenQueue = new List<Token>(Tokenizer.Tokenize(filterString)); foreach (var t in tokenQueue) if (t.Value != null) Debug.WriteLine(t.Type + " : " + t.Value); else Debug.WriteLine(t.Type); #endregion #region TokenAnalyze Debug.WriteLine("\n-- Token Analyze --\n"); var tokenAnalyzer = new TokenAnalyzer(tokenQueue, paramExpr); tokenAnalyzer.TokenAnalyze(); foreach (var t in tokenAnalyzer.PolandQueue) if (t.Value != null) Debug.WriteLine(t.Type + " : " + t.Value); else Debug.WriteLine(t.Type); #endregion #region PolandTokenCompile Debug.WriteLine("\n-- Poland Token Compile --\n"); var polandTokenCompile = new PolandTokenCompiler(tokenAnalyzer.PolandQueue); polandTokenCompile.PolandTokenCompile(defaultValue); var filter = Expression.Lambda<Func<Status, bool>>(polandTokenCompile.CompiledExpression, paramExpr); Debug.WriteLine("\n-- Poland Token Compile --\n"); Debug.WriteLine(polandTokenCompile.CompiledExpression.ToString()); return filter.Compile(); #endregion } internal static class Tokenizer { private const string ContainsString = "Contains"; private const string StartsWithString = "StartsWith"; private const string EndsWithString = "EndsWith"; private const string RegexMatchString = "RegexMatch"; private const string BooleanTrueString = "True"; private const string BooleanFalseString = "False"; private const string NullString = "Null"; private const string InString = "In"; private const string Tokens = ".,[]=<>!&|()\" \t\r\n+-*/"; private const string NumericToken = "1234567890"; public static IEnumerable<Token> Tokenize(string filter) { var strPos = 0; var keywordToken = Token.TokenId.And; object value = null; do { int begin; switch (filter[strPos]) { case '.': yield return new Token(Token.TokenId.Period, strPos++); break; case ',': yield return new Token(Token.TokenId.Comma, strPos++); break; case '=': if (++strPos >= filter.Length || filter[strPos] != '=') throw new FilterCompileException( FilterCompileException.ErrorCode.EqualMustUseWithOtherTokens, "'=' must use with other tokens", null); yield return new Token(Token.TokenId.Equal, strPos++ - 1); break; case '<': if (++strPos < filter.Length && filter[strPos] == '=') yield return new Token(Token.TokenId.LessThanEqual, strPos++ - 1); else yield return new Token(Token.TokenId.LessThan, strPos - 1); break; case '>': if (++strPos < filter.Length && filter[strPos] == '=') yield return new Token(Token.TokenId.GreaterThanEqual, strPos++ - 1); else yield return new Token(Token.TokenId.GreaterThan, strPos - 1); break; case '!': begin = strPos; if (++strPos < filter.Length && filter[strPos] == '=') { yield return new Token(Token.TokenId.NotEqual, begin); strPos++; } else if (TryGetKeyword(filter, ref strPos, ref keywordToken, ref value) && keywordToken != Token.TokenId.Null && keywordToken != Token.TokenId.Boolean) { yield return new Token(keywordToken + 5, begin); strPos++; } else { yield return new Token(Token.TokenId.Exclamation, begin); strPos = ++begin; } break; case 'C': case 'S': case 'E': case 'R': case 'F': case 'T': case 'N': case 'I': begin = strPos; if (TryGetKeyword(filter, ref strPos, ref keywordToken, ref value)) { yield return new Token(keywordToken, value, begin); strPos++; } else { strPos = begin; goto default; } break; case '&': if (++strPos >= filter.Length || filter[strPos] != '&') throw new FilterCompileException( FilterCompileException.ErrorCode.AndMustUseWithOtherTokens, "'&' must use with other tokens", null); else yield return new Token(Token.TokenId.And, strPos++ - 1); break; case '|': if (++strPos >= filter.Length || filter[strPos] != '|') throw new FilterCompileException( FilterCompileException.ErrorCode.VerticalBarMustUseWithOtherTokens, "'|' must use with other tokens", null); else yield return new Token(Token.TokenId.Or, strPos++ - 1); break; case '(': yield return new Token(Token.TokenId.OpenBracket, strPos++); break; case ')': yield return new Token(Token.TokenId.CloseBracket, strPos++); break; case '"': begin = strPos; yield return new Token(Token.TokenId.String, GetFilterString(filter, ref strPos), begin); strPos++; break; case '[': yield return new Token(Token.TokenId.OpenSquareBracket, strPos++); break; case ']': yield return new Token(Token.TokenId.CloseSquareBracket, strPos++); break; case '+': yield return new Token(Token.TokenId.Plus, strPos++); break; case '-': yield return new Token(Token.TokenId.Minus, strPos++); break; case '*': yield return new Token(Token.TokenId.Multiplication, strPos++); break; case '/': yield return new Token(Token.TokenId.Division, strPos++); break; case '%': yield return new Token(Token.TokenId.Modulo, strPos++); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0': begin = strPos; yield return new Token(Token.TokenId.Numeric, long.Parse(GetFilterNumeric(filter, ref strPos)), begin); strPos++; break; case ' ': case '\t': case '\r': case '\n': yield return new Token(Token.TokenId.Space, strPos++); break; default: begin = strPos; if (TryGetFunction(filter, ref strPos, ref keywordToken, ref value)) yield return new Token(keywordToken, value, begin); else do { if (Tokens.Contains(filter[strPos].ToString())) { yield return new Token(Token.TokenId.Literal, filter.Substring(begin, strPos - begin), begin); break; } if (strPos + 1 >= filter.Length) { strPos++; yield return new Token(Token.TokenId.Literal, filter.Substring(begin, strPos - begin), begin); break; } strPos++; } while (strPos < filter.Length); break; } } while (strPos < filter.Length); } private static string GetFilterString(string filter, ref int cursor) { var begin = cursor++; while (cursor < filter.Length) { if (filter[cursor] == '\\') { if (cursor + 1 == filter.Length) throw new FilterCompileException(FilterCompileException.ErrorCode.FilterEndWithBacksrash, "Filter ends with backsrash", null); if (filter[cursor + 1] == '"' || filter[cursor + 1] == '\\') cursor++; } else if (filter[cursor] == '"') { return filter.Substring(begin + 1, cursor - begin - 1) .Replace("\\\"", "\"") .Replace("\\\\", "\\"); } cursor++; } throw new FilterCompileException(FilterCompileException.ErrorCode.StringTokenIncomplete, "string token is incomplete", null); } private static string GetFilterNumeric(string filter, ref int cursor) { var begin = cursor; while (cursor < filter.Length) { if (NumericToken.Contains(filter[cursor].ToString())) { cursor++; continue; } return filter.Substring(begin, cursor-- - begin); } return filter.Substring(begin, cursor-- - begin); } private static bool TryGetFunction(string filter, ref int cursor, ref Token.TokenId token, ref object value) { var strPos = cursor; var begin = strPos; do { if (Tokens.Contains(filter[strPos].ToString())) if (filter[strPos].ToString() == "(") { var commaCount = 0; var tempStrPos = strPos + 1; var existLiteral = false; do { if (filter[tempStrPos].ToString() == " " || filter[tempStrPos].ToString() == "\n" || filter[tempStrPos].ToString() == "\r" || filter[tempStrPos].ToString() == "\t") { tempStrPos++; continue; } if (filter[tempStrPos].ToString() == ",") commaCount++; else if (filter[tempStrPos].ToString() == ")") break; else existLiteral = true; tempStrPos++; } while (tempStrPos < filter.Length); cursor = strPos; token = Token.TokenId.Function; value = filter.Substring(begin, strPos - begin) + "," + (commaCount + (existLiteral ? 1 : 0)); return true; } else { return false; } strPos++; } while (strPos < filter.Length); return false; } private static bool TryGetKeyword(string filter, ref int cursor, ref Token.TokenId token, ref object value) { if (cursor + ContainsString.Length < filter.Length && filter.Substring(cursor, ContainsString.Length) .Contains(ContainsString)) { token = Token.TokenId.Contains; cursor += ContainsString.Length - 1; return true; } if (cursor + StartsWithString.Length < filter.Length && filter.Substring(cursor, StartsWithString.Length).Contains(StartsWithString)) { token = Token.TokenId.StartsWith; cursor += StartsWithString.Length - 1; return true; } if (cursor + EndsWithString.Length < filter.Length && filter.Substring(cursor, EndsWithString.Length) .Contains(EndsWithString)) { token = Token.TokenId.EndsWith; cursor += EndsWithString.Length - 1; return true; } if (cursor + RegexMatchString.Length < filter.Length && filter.Substring(cursor, RegexMatchString.Length).Contains(RegexMatchString)) { token = Token.TokenId.RegexMatch; cursor += RegexMatchString.Length - 1; return true; } if (cursor + BooleanTrueString.Length < filter.Length && filter .Substring(cursor, BooleanTrueString.Length) .Contains(BooleanTrueString)) { token = Token.TokenId.Boolean; value = true; cursor += BooleanTrueString.Length - 1; return true; } if (cursor + BooleanFalseString.Length < filter.Length && filter .Substring(cursor, BooleanFalseString.Length) .Contains(BooleanFalseString)) { token = Token.TokenId.Boolean; value = false; cursor += BooleanFalseString.Length - 1; return true; } if (cursor + NullString.Length < filter.Length && filter.Substring(cursor, NullString.Length).Contains(NullString)) { token = Token.TokenId.Null; value = null; cursor += NullString.Length - 1; return true; } if (cursor + InString.Length < filter.Length && filter.Substring(cursor, InString.Length).Contains(InString)) { token = Token.TokenId.In; value = null; cursor += InString.Length - 1; return true; } return false; } } internal class TokenAnalyzer { private readonly ParameterExpression _paramExpr; private readonly List<Token> _tempQueue; private readonly List<Token> _tokenQueue; private int _closeBracketCount; private int _openBracketCount; public TokenAnalyzer(IEnumerable<Token> tokens, ParameterExpression paramExpr) { _paramExpr = paramExpr; PolandQueue = new List<Token>(); _tokenQueue = new List<Token>(); _tempQueue = new List<Token>(); _openBracketCount = 0; _closeBracketCount = 0; foreach (var token in tokens) { if (token.Type == Token.TokenId.Space) continue; _tokenQueue.Add(token); } } public List<Token> PolandQueue { get; set; } public void TokenAnalyze() { int cursor; for (cursor = 0; cursor < _tokenQueue.Count; cursor++) { var cursorToken = _tokenQueue[cursor]; switch (cursorToken.Type) { case Token.TokenId.Numeric: case Token.TokenId.String: case Token.TokenId.Boolean: case Token.TokenId.Null: PolandQueue.Add(cursorToken); break; case Token.TokenId.Literal: PolandQueue.Add(new Token { Type = Token.TokenId.LiteralExpression, Pos = -1, Value = LiteralExpression(ref cursor) }); break; case Token.TokenId.OpenSquareBracket: var type = string.Empty; var value = ArrayExpression(ref cursor, ref type); if (type == "Numeric") PolandQueue.Add(new Token { Type = Token.TokenId.NumericArrayExpression, Pos = -1, Value = value }); else if (type == "String") PolandQueue.Add(new Token { Type = Token.TokenId.StringArrayExpression, Pos = -1, Value = value }); break; case Token.TokenId.Plus: case Token.TokenId.Minus: case Token.TokenId.Multiplication: case Token.TokenId.Division: case Token.TokenId.Modulo: case Token.TokenId.Equal: case Token.TokenId.NotEqual: case Token.TokenId.LessThanEqual: case Token.TokenId.GreaterThanEqual: case Token.TokenId.LessThan: case Token.TokenId.GreaterThan: case Token.TokenId.Contains: case Token.TokenId.StartsWith: case Token.TokenId.EndsWith: case Token.TokenId.RegexMatch: case Token.TokenId.In: case Token.TokenId.NotContains: case Token.TokenId.NotStartsWith: case Token.TokenId.NotEndsWith: case Token.TokenId.NotRegexMatch: case Token.TokenId.NotIn: case Token.TokenId.And: case Token.TokenId.Or: case Token.TokenId.Exclamation: case Token.TokenId.Function: _tempQueue.Add(cursorToken); TempQueueCheckPriority(); break; case Token.TokenId.OpenBracket: _tempQueue.Add(cursorToken); _openBracketCount++; break; case Token.TokenId.CloseBracket: _tempQueue.Add(cursorToken); _closeBracketCount++; if (_closeBracketCount > _openBracketCount) throw new FilterCompileException( FilterCompileException.ErrorCode.CloseBracketPositionIsWrong, "Close backet position is wrong", null); else TempQueueAnnihilationBracket(); break; case Token.TokenId.Comma: case Token.TokenId.Period: case Token.TokenId.CloseSquareBracket: case Token.TokenId.Space: case Token.TokenId.LiteralExpression: case Token.TokenId.NumericArrayExpression: case Token.TokenId.StringArrayExpression: case Token.TokenId.ExpressionParam: break; default: throw new ArgumentOutOfRangeException(); } } if (_openBracketCount != _closeBracketCount) throw new FilterCompileException( FilterCompileException.ErrorCode.CloseBracketCountAndOpenBracketCountDiffer, "Close bracket count and open bracket count differ", null); for (var tempQueueCursor = _tempQueue.Count - 1; tempQueueCursor >= 0; tempQueueCursor--) { if (_tempQueue[tempQueueCursor].Type == Token.TokenId.OpenBracket || _tempQueue[tempQueueCursor].Type == Token.TokenId.CloseBracket) throw new FilterCompileException( FilterCompileException.ErrorCode.CloseBracketCountAndOpenBracketCountDiffer, "Close bracket count and open bracket count differ", null); PolandQueue.Add(_tempQueue[tempQueueCursor]); } _tempQueue.Clear(); } private void TempQueueCheckPriority() { if (_tempQueue.Count < 2) return; var cursor = _tempQueue.Count - 2; var previousPriority = SearchPriority(_tempQueue[cursor].Type); var nextPriority = SearchPriority(_tempQueue[cursor + 1].Type); if (previousPriority == 0) return; if (previousPriority > nextPriority) return; PolandQueue.Add(_tempQueue[cursor]); _tempQueue.RemoveAt(cursor); } private int SearchPriority(Token.TokenId token) { if (token == Token.TokenId.OpenBracket || token == Token.TokenId.CloseBracket) return 0; if (Token.Priority1.Contains(token)) return 1; if (Token.Priority2.Contains(token)) return 2; if (Token.Priority3.Contains(token)) return 3; if (Token.Priority4.Contains(token)) return 4; throw new FilterCompileException(FilterCompileException.ErrorCode.InternalError, "Internal error", null); } private void TempQueueAnnihilationBracket() { if (_tempQueue.Count <= 1) throw new FilterCompileException(FilterCompileException.ErrorCode.InternalError, "Internal error", null); if (_tempQueue[_tempQueue.Count - 1].Type != Token.TokenId.CloseBracket) throw new FilterCompileException(FilterCompileException.ErrorCode.CloseBracketNotExist, "Close bracket doesnt exist", null); var existOpenBracket = false; int cursor; for (cursor = _tempQueue.Count - 2; cursor >= 0; cursor--) if (_tempQueue[cursor].Type == Token.TokenId.OpenBracket) { existOpenBracket = true; break; } else if (_tempQueue[cursor].Type == Token.TokenId.CloseBracket) { throw new FilterCompileException(FilterCompileException.ErrorCode.CloseBracketPositionIsWrong, "Close backet position is wrong", null); } /*else if (Token.Priority_Other.Contains(tempQueue[cursor].Type)) { throw new FilterCompileException(FilterCompileException.ErrorCode.InternalError, "Internal error", null); }*/ else { PolandQueue.Add(_tempQueue[cursor]); _tempQueue.Remove(_tempQueue[cursor]); } if (existOpenBracket == false) throw new FilterCompileException(FilterCompileException.ErrorCode.OpenBracketNotExist, "Open bracket doesnt exist", null); var openBracketPosition = cursor; var closeBracketPosition = _tempQueue.Count - 1; _tempQueue.RemoveAt(closeBracketPosition); _tempQueue.RemoveAt(openBracketPosition); } private object LiteralExpression(ref int cursor) { Expression literal = _paramExpr; do { var literalString = _tokenQueue[cursor].Value as string; if (literalString == "CreateAt") literal = Expression.Convert(Expression.Property(literal, literalString), typeof(string)); else if (literalString == "Count") literal = Expression.Convert(Expression.Property(literal, literalString), typeof(long)); else if (literalString == "FavoriteCount") literal = Expression.Convert(Expression.Property(literal, literalString), typeof(long)); else if (literalString == "RetweetCount") literal = Expression.Convert(Expression.Property(literal, literalString), typeof(long)); else if (literalString == "FavouritesCount") literal = Expression.Convert(Expression.Property(literal, literalString), typeof(long)); else if (literalString == "FollowersCount") literal = Expression.Convert(Expression.Property(literal, literalString), typeof(long)); else if (literalString == "FriendsCount") literal = Expression.Convert(Expression.Property(literal, literalString), typeof(long)); else if (literalString == "ListedCount") literal = Expression.Convert(Expression.Property(literal, literalString), typeof(long)); else if (literalString == "StatusesCount") literal = Expression.Convert(Expression.Property(literal, literalString), typeof(long)); else literal = Expression.Property(literal, literalString); if (_tokenQueue.Count > cursor + 2 && _tokenQueue[cursor + 1].Type == Token.TokenId.Period && _tokenQueue[cursor + 2].Type == Token.TokenId.Literal) cursor += 2; else break; } while (true); return literal; } private object ArrayExpression(ref int cursor, ref string type) { var arrayType = string.Empty; if (_tokenQueue.Count <= cursor + 1) throw new FilterCompileException(FilterCompileException.ErrorCode.ArrayIncomplete, "Array token is incomplete", null); cursor++; if (_tokenQueue[cursor].Type == Token.TokenId.Numeric) arrayType = "Numeric"; else if (_tokenQueue[cursor].Type == Token.TokenId.String) arrayType = "String"; var arrayExpressionList = new List<Expression>(); do { if (arrayType == "Numeric" && _tokenQueue[cursor].Type == Token.TokenId.Numeric) arrayExpressionList.Add(Expression.Constant(_tokenQueue[cursor].Value)); else if (arrayType == "String" && _tokenQueue[cursor].Type == Token.TokenId.String) arrayExpressionList.Add(Expression.Constant(_tokenQueue[cursor].Value)); else throw new FilterCompileException(FilterCompileException.ErrorCode.WrongArray, "Wrong array", null); if (_tokenQueue.Count <= cursor + 1) throw new FilterCompileException(FilterCompileException.ErrorCode.ArrayIncomplete, "Array token is incomplete", null); if (_tokenQueue[cursor + 1].Type == Token.TokenId.CloseSquareBracket) { cursor++; break; } if (_tokenQueue.Count > cursor + 2 && _tokenQueue[cursor + 1].Type == Token.TokenId.Comma) cursor += 2; else throw new FilterCompileException(FilterCompileException.ErrorCode.WrongArray, "Wrong array", null); } while (true); type = arrayType; if (arrayType == "Numeric") return Expression.NewArrayInit(typeof(long), arrayExpressionList); if (arrayType == "String") return Expression.NewArrayInit(typeof(string), arrayExpressionList); throw new FilterCompileException(FilterCompileException.ErrorCode.InternalError, "Internal error", null); } } internal class PolandTokenCompiler { private static readonly MethodInfo ContainsMethod = typeof(string).GetMethods("Contains").First(); private static readonly MethodInfo StartsWithMethod = typeof(string).GetMethods("StartsWith").First(); private static readonly MethodInfo EndsWithMethod = typeof(string).GetMethods("EndsWith").First(); private readonly List<Token> _polandQueue; private readonly List<Token> _tempQueue; public Expression CompiledExpression; public PolandTokenCompiler(IEnumerable<Token> tokens) { _polandQueue = new List<Token>(); _tempQueue = new List<Token>(); foreach (var t in tokens) _polandQueue.Add(t); } public void PolandTokenCompile(bool defaultValue = true) { foreach (var token in _polandQueue) switch (token.Type) { case Token.TokenId.Numeric: case Token.TokenId.String: case Token.TokenId.Boolean: case Token.TokenId.LiteralExpression: case Token.TokenId.NumericArrayExpression: case Token.TokenId.StringArrayExpression: case Token.TokenId.ExpressionParam: case Token.TokenId.Null: _tempQueue.Add(token); break; case Token.TokenId.Plus: case Token.TokenId.Minus: case Token.TokenId.Multiplication: case Token.TokenId.Division: case Token.TokenId.Modulo: case Token.TokenId.Equal: case Token.TokenId.NotEqual: case Token.TokenId.LessThanEqual: case Token.TokenId.GreaterThanEqual: case Token.TokenId.LessThan: case Token.TokenId.GreaterThan: case Token.TokenId.Contains: case Token.TokenId.StartsWith: case Token.TokenId.EndsWith: case Token.TokenId.RegexMatch: case Token.TokenId.In: case Token.TokenId.NotContains: case Token.TokenId.NotStartsWith: case Token.TokenId.NotEndsWith: case Token.TokenId.NotRegexMatch: case Token.TokenId.NotIn: case Token.TokenId.And: case Token.TokenId.Or: PolandTokenOperate(token.Type); break; case Token.TokenId.Exclamation: PolandTokenOperateExclamation(); break; case Token.TokenId.Function: PolandTokenOperateFunction(token, defaultValue); break; default: throw new FilterCompileException(FilterCompileException.ErrorCode.InternalError, "Internal error", null); } if (_tempQueue.Count == 0) { CompiledExpression = Expression.Constant(true); } else if (_tempQueue.Count > 1) { throw new FilterCompileException(FilterCompileException.ErrorCode.InternalError, "Internal error", null); } else { if (_tempQueue[_tempQueue.Count - 1].Type == Token.TokenId.Boolean) CompiledExpression = Expression.Constant((bool) _tempQueue[_tempQueue.Count - 1].Value); else CompiledExpression = _tempQueue[_tempQueue.Count - 1].Value as Expression; if (CompiledExpression == null) CompiledExpression = Expression.Constant(defaultValue); } } private void PolandTokenOperateFunction(Token token, bool defaultValue) { var data = ((string) token.Value).Split(','); var functionName = data.ElementAt(0); var functionArgCount = int.Parse(data.ElementAt(1)); if (_tempQueue.Count < functionArgCount) throw new FilterCompileException(FilterCompileException.ErrorCode.InternalError, "Argument count is wrong", null); var param = new Expression[functionArgCount]; for (var i = 0; i < functionArgCount; i++) switch (_tempQueue[i].Type) { case Token.TokenId.Boolean: param[i] = Expression.Constant((bool) _tempQueue[i].Value, typeof(object)); break; case Token.TokenId.Numeric: param[i] = Expression.Constant((long) _tempQueue[i].Value, typeof(object)); break; case Token.TokenId.String: param[i] = Expression.Constant((string) _tempQueue[i].Value, typeof(object)); break; case Token.TokenId.LiteralExpression: case Token.TokenId.ExpressionParam: case Token.TokenId.NumericArrayExpression: case Token.TokenId.StringArrayExpression: param[i] = Expression.Convert(_tempQueue[i].Value as Expression, typeof(object)); break; case Token.TokenId.Null: param[i] = Expression.Constant(null, typeof(object)); break; default: throw new FilterCompileException(FilterCompileException.ErrorCode.WrongOperation, "Wrong operation", null); } var expressionResult = Expression.Call(typeof(FilterFunctions), "Invoke", null, Expression.Constant(functionName), Expression.Constant(defaultValue), Expression.NewArrayInit(typeof(object), param)); _tempQueue.RemoveRange(_tempQueue.Count - functionArgCount, functionArgCount); _tempQueue.Add(new Token {Pos = -1, Type = Token.TokenId.ExpressionParam, Value = expressionResult}); } public void PolandTokenOperateExclamation() { if (_tempQueue.Count < 1) throw new FilterCompileException(FilterCompileException.ErrorCode.WrongOperation, "Wrong operation", null); var frontToken = _tempQueue[_tempQueue.Count - 1]; if (!Token.PriorityOther.Contains(frontToken.Type)) throw new FilterCompileException(FilterCompileException.ErrorCode.WrongOperation, "Wrong operation", null); Expression frontExpression; switch (frontToken.Type) { case Token.TokenId.Boolean: frontExpression = Expression.Constant((bool) frontToken.Value); break; case Token.TokenId.LiteralExpression: frontExpression = frontToken.Value as MemberExpression; break; case Token.TokenId.ExpressionParam: frontExpression = frontToken.Value as Expression; break; default: throw new FilterCompileException(FilterCompileException.ErrorCode.WrongOperation, "Wrong operation", null); } Expression expressionResult = Expression.Equal(frontExpression, Expression.Constant(false, typeof(bool))); _tempQueue.Remove(frontToken); _tempQueue.Add(new Token {Pos = -1, Type = Token.TokenId.ExpressionParam, Value = expressionResult}); } public void PolandTokenOperate(Token.TokenId tokenId) { if (_tempQueue.Count < 2) throw new FilterCompileException(FilterCompileException.ErrorCode.WrongOperation, "Wrong operation", null); var backToken = _tempQueue[_tempQueue.Count - 2]; var frontToken = _tempQueue[_tempQueue.Count - 1]; if (!Token.PriorityOther.Contains(backToken.Type)) throw new FilterCompileException(FilterCompileException.ErrorCode.WrongOperation, "Wrong operation", null); if (!Token.PriorityOther.Contains(frontToken.Type)) throw new FilterCompileException(FilterCompileException.ErrorCode.WrongOperation, "Wrong operation", null); Expression expressionResult = null; Expression backExpression; Expression frontExpression; switch (backToken.Type) { case Token.TokenId.Boolean: backExpression = Expression.Constant((bool) backToken.Value); break; case Token.TokenId.Numeric: backExpression = Expression.Constant((long) backToken.Value); break; case Token.TokenId.String: backExpression = Expression.Constant((string) backToken.Value); break; case Token.TokenId.LiteralExpression: case Token.TokenId.ExpressionParam: backExpression = backToken.Value as Expression; break; case Token.TokenId.Null: backExpression = Expression.Constant(null, typeof(object)); break; case Token.TokenId.StringArrayExpression: case Token.TokenId.NumericArrayExpression: throw new FilterCompileException(FilterCompileException.ErrorCode.ArrayPositionIsWrong, "Array position is wrong", null); default: throw new FilterCompileException(FilterCompileException.ErrorCode.WrongOperation, "Wrong operation", null); } switch (frontToken.Type) { case Token.TokenId.Boolean: frontExpression = Expression.Constant((bool) frontToken.Value); break; case Token.TokenId.Numeric: frontExpression = Expression.Constant((long) frontToken.Value); break; case Token.TokenId.String: frontExpression = Expression.Constant((string) frontToken.Value); break; case Token.TokenId.LiteralExpression: case Token.TokenId.ExpressionParam: case Token.TokenId.NumericArrayExpression: case Token.TokenId.StringArrayExpression: frontExpression = frontToken.Value as Expression; break; case Token.TokenId.Null: frontExpression = Expression.Constant(null, typeof(object)); break; default: throw new FilterCompileException(FilterCompileException.ErrorCode.WrongOperation, "Wrong operation", null); } switch (tokenId) { case Token.TokenId.Plus: expressionResult = Expression.Add(backExpression, frontExpression); break; case Token.TokenId.Minus: expressionResult = Expression.Subtract(backExpression, frontExpression); break; case Token.TokenId.Multiplication: expressionResult = Expression.Multiply(backExpression, frontExpression); break; case Token.TokenId.Division: expressionResult = Expression.Divide(backExpression, frontExpression); break; case Token.TokenId.Modulo: expressionResult = Expression.Modulo(backExpression, frontExpression); break; case Token.TokenId.Equal: expressionResult = Expression.Equal(backExpression, frontExpression); break; case Token.TokenId.NotEqual: expressionResult = Expression.NotEqual(backExpression, frontExpression); break; case Token.TokenId.LessThanEqual: expressionResult = Expression.LessThanOrEqual(backExpression, frontExpression); break; case Token.TokenId.GreaterThanEqual: expressionResult = Expression.GreaterThanOrEqual(backExpression, frontExpression); break; case Token.TokenId.LessThan: expressionResult = Expression.LessThan(backExpression, frontExpression); break; case Token.TokenId.GreaterThan: expressionResult = Expression.GreaterThan(backExpression, frontExpression); break; case Token.TokenId.Contains: expressionResult = Expression.Call(backExpression, ContainsMethod, frontExpression); break; case Token.TokenId.StartsWith: expressionResult = Expression.Call(backExpression, StartsWithMethod, frontExpression); break; case Token.TokenId.EndsWith: expressionResult = Expression.Call(backExpression, EndsWithMethod, frontExpression); break; case Token.TokenId.RegexMatch: expressionResult = Expression.Call(typeof(Regex), "IsMatch", null, backExpression, frontExpression); break; case Token.TokenId.In: if (frontToken.Type == Token.TokenId.NumericArrayExpression) expressionResult = Expression.Call(typeof(Enumerable), "Contains", new[] {typeof(long)}, frontExpression, backExpression); else if (frontToken.Type == Token.TokenId.StringArrayExpression) expressionResult = Expression.Call(typeof(Enumerable), "Contains", new[] {typeof(string)}, frontExpression, backExpression); break; case Token.TokenId.NotContains: expressionResult = Expression.Equal( Expression.Call(backExpression, ContainsMethod, frontExpression), Expression.Constant(false)); break; case Token.TokenId.NotStartsWith: expressionResult = Expression.Equal( Expression.Call(backExpression, StartsWithMethod, frontExpression), Expression.Constant(false)); break; case Token.TokenId.NotEndsWith: expressionResult = Expression.Equal( Expression.Call(backExpression, EndsWithMethod, frontExpression), Expression.Constant(false)); break; case Token.TokenId.NotRegexMatch: expressionResult = Expression.Equal( Expression.Call(typeof(Regex), "IsMatch", null, backExpression, frontExpression), Expression.Constant(false)); break; case Token.TokenId.NotIn: if (frontToken.Type == Token.TokenId.NumericArrayExpression) expressionResult = Expression.Equal( Expression.Call(typeof(Enumerable), "Contains", new[] {typeof(long)}, frontExpression, backExpression), Expression.Constant(false)); else if (frontToken.Type == Token.TokenId.StringArrayExpression) expressionResult = Expression.Equal( Expression.Call(typeof(Enumerable), "Contains", new[] {typeof(string)}, frontExpression, backExpression), Expression.Constant(false)); break; case Token.TokenId.And: expressionResult = Expression.AndAlso(backExpression, frontExpression); break; case Token.TokenId.Or: expressionResult = Expression.OrElse(backExpression, frontExpression); break; default: throw new FilterCompileException(FilterCompileException.ErrorCode.WrongOperation, "Wrong operation", null); } _tempQueue.Remove(frontToken); _tempQueue.Remove(backToken); _tempQueue.Add(new Token {Pos = -1, Type = Token.TokenId.ExpressionParam, Value = expressionResult}); } } } }
44.42272
129
0.462867
[ "MIT" ]
cucmberium/Flantter
Flantter.MilkyWay/Models/Filter/Compiler.cs
57,783
C#
using System.Collections.Generic; using TaleWorlds.InputSystem; using TaleWorlds.MountAndBlade; #pragma warning disable 1591 namespace BannerLib.Input { public class InputSubModule : MBSubModuleBase { // TODO: Expand the system and make it more resistant to mod collisions. // TODO: Support the full suite of binding abilities. // TODO: Support localisation. internal static InputSubModule Instance { get; private set; } private readonly List<HotKeyBase> m_hotKeys = new List<HotKeyBase>(); protected override void OnSubModuleLoad() { if (Instance == null) Instance = this; } internal void AddHotkeys(IEnumerable<HotKeyBase> hotKeys) { m_hotKeys.AddRange(hotKeys); } protected override void OnApplicationTick(float dt) { foreach (var hotkey in m_hotKeys) { if (!hotkey.ShouldExecute()) continue; if (hotkey.GameKey.PrimaryKey.InputKey.IsDown()) hotkey.IsDownInternal(); if (hotkey.GameKey.PrimaryKey.InputKey.IsPressed()) hotkey.OnPressedInternal(); if (hotkey.GameKey.PrimaryKey.InputKey.IsReleased()) hotkey.OnReleasedInternal(); } } } }
33.365854
80
0.600877
[ "Unlicense" ]
sirdoombox/BannerLib
BannerLib.Input/InputSubModule.cs
1,368
C#
namespace Homework.Pages { public partial class HomePage : BasePage { public void NavigateToLoginPage(HomePage homePage) { homePage.Navigate("http://automationpractice.com/index.php"); SignInButton.Click(); } } }
22.75
73
0.611722
[ "MIT" ]
studware/My-QA-Automation
QA-Automation-September2019/HW_SeleniumPOM_GRID/Homework/AutomationPractice/Pages/HomePage/HomePage.Methods.cs
275
C#
using MTGAHelper.Lib.OutputLogParser.Models.UnityCrossThreadLogger; namespace MTGAHelper.Lib.OutputLogParser.Readers.UnityCrossThreadLogger { public class StateChangedConverter : GenericConverter<StateChangedResult, StateChangedRaw>, IMessageReaderUnityCrossThreadLogger { public override string LogTextKey => "STATE CHANGED"; } }
39.111111
132
0.8125
[ "MIT" ]
robaxelsen/MTGAHelper-Windows-Client
MTGAHelper.Lib.OutputLogParser/Readers/UnityCrossThreadLogger/StateChangedConverter.cs
354
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace AlibabaCloud.SDK.ROS.CDK.Vpc { /// <summary>A ROS template type: `ALIYUN::VPC::NatGateway`.</summary> [JsiiClass(nativeType: typeof(AlibabaCloud.SDK.ROS.CDK.Vpc.RosNatGateway), fullyQualifiedName: "@alicloud/ros-cdk-vpc.RosNatGateway", parametersJson: "[{\"docs\":{\"summary\":\"- scope in which this resource is defined.\"},\"name\":\"scope\",\"type\":{\"fqn\":\"@alicloud/ros-cdk-core.Construct\"}},{\"docs\":{\"summary\":\"- scoped id of the resource.\"},\"name\":\"id\",\"type\":{\"primitive\":\"string\"}},{\"docs\":{\"summary\":\"- resource properties.\"},\"name\":\"props\",\"type\":{\"fqn\":\"@alicloud/ros-cdk-vpc.RosNatGatewayProps\"}},{\"name\":\"enableResourcePropertyConstraint\",\"type\":{\"primitive\":\"boolean\"}}]")] public class RosNatGateway : AlibabaCloud.SDK.ROS.CDK.Core.RosResource { /// <summary>Create a new `ALIYUN::VPC::NatGateway`.</summary> /// <param name="scope">- scope in which this resource is defined.</param> /// <param name="id">- scoped id of the resource.</param> /// <param name="props">- resource properties.</param> public RosNatGateway(AlibabaCloud.SDK.ROS.CDK.Core.Construct scope, string id, AlibabaCloud.SDK.ROS.CDK.Vpc.IRosNatGatewayProps props, bool enableResourcePropertyConstraint): base(new DeputyProps(new object?[]{scope, id, props, enableResourcePropertyConstraint})) { } /// <summary>Used by jsii to construct an instance of this class from a Javascript-owned object reference</summary> /// <param name="reference">The Javascript-owned object reference</param> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] protected RosNatGateway(ByRefValue reference): base(reference) { } /// <summary>Used by jsii to construct an instance of this class from DeputyProps</summary> /// <param name="props">The deputy props</param> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] protected RosNatGateway(DeputyProps props): base(props) { } [JsiiMethod(name: "renderProperties", returnsJson: "{\"type\":{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"map\"}}}", parametersJson: "[{\"name\":\"props\",\"type\":{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"map\"}}}]", isOverride: true)] protected override System.Collections.Generic.IDictionary<string, object> RenderProperties(System.Collections.Generic.IDictionary<string, object> props) { return InvokeInstanceMethod<System.Collections.Generic.IDictionary<string, object>>(new System.Type[]{typeof(System.Collections.Generic.IDictionary<string, object>)}, new object[]{props})!; } /// <summary>The resource type name for this resource class.</summary> [JsiiProperty(name: "ROS_RESOURCE_TYPE_NAME", typeJson: "{\"primitive\":\"string\"}")] public static string ROS_RESOURCE_TYPE_NAME { get; } = GetStaticProperty<string>(typeof(AlibabaCloud.SDK.ROS.CDK.Vpc.RosNatGateway))!; /// <remarks> /// <strong>Attribute</strong>: ForwardTableId: The forward table id. /// </remarks> [JsiiProperty(name: "attrForwardTableId", typeJson: "{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}")] public virtual AlibabaCloud.SDK.ROS.CDK.Core.IResolvable AttrForwardTableId { get => GetInstanceProperty<AlibabaCloud.SDK.ROS.CDK.Core.IResolvable>()!; } /// <remarks> /// <strong>Attribute</strong>: NatGatewayId: The Id of created NAT gateway. /// </remarks> [JsiiProperty(name: "attrNatGatewayId", typeJson: "{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}")] public virtual AlibabaCloud.SDK.ROS.CDK.Core.IResolvable AttrNatGatewayId { get => GetInstanceProperty<AlibabaCloud.SDK.ROS.CDK.Core.IResolvable>()!; } /// <remarks> /// <strong>Attribute</strong>: SNatTableId: The SNAT table id. /// </remarks> [JsiiProperty(name: "attrSNatTableId", typeJson: "{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}")] public virtual AlibabaCloud.SDK.ROS.CDK.Core.IResolvable AttrSNatTableId { get => GetInstanceProperty<AlibabaCloud.SDK.ROS.CDK.Core.IResolvable>()!; } [JsiiProperty(name: "rosProperties", typeJson: "{\"collection\":{\"elementtype\":{\"primitive\":\"any\"},\"kind\":\"map\"}}")] protected override System.Collections.Generic.IDictionary<string, object> RosProperties { get => GetInstanceProperty<System.Collections.Generic.IDictionary<string, object>>()!; } [JsiiProperty(name: "enableResourcePropertyConstraint", typeJson: "{\"primitive\":\"boolean\"}")] public virtual bool EnableResourcePropertyConstraint { get => GetInstanceProperty<bool>()!; set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: vpcId: The VPC id to create NAT gateway. /// </remarks> [JsiiProperty(name: "vpcId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")] public virtual object VpcId { get => GetInstanceProperty<object>()!; set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: vSwitchId: The VSwitch id to create NAT gateway. /// </remarks> [JsiiProperty(name: "vSwitchId", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")] public virtual object VSwitchId { get => GetInstanceProperty<object>()!; set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: autoPay: Specifies whether to enable automatic payment. Default is false. /// </remarks> [JsiiOptional] [JsiiProperty(name: "autoPay", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] public virtual object? AutoPay { get => GetInstanceProperty<object?>(); set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: deletionForce: Whether force delete the relative snat and dnat entries in the net gateway and unbind eips. Default value is false. /// </remarks> [JsiiOptional] [JsiiProperty(name: "deletionForce", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] public virtual object? DeletionForce { get => GetInstanceProperty<object?>(); set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: deletionProtection: Whether to enable deletion protection. /// Default to False. /// </remarks> [JsiiOptional] [JsiiProperty(name: "deletionProtection", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"boolean\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] public virtual object? DeletionProtection { get => GetInstanceProperty<object?>(); set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: description: Description of the NAT gateway, [2, 256] characters. Do not fill or empty, the default is empty. /// </remarks> [JsiiOptional] [JsiiProperty(name: "description", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] public virtual object? Description { get => GetInstanceProperty<object?>(); set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: duration: The subscription duration. While choose by pay by month, it could be from 1 to 9 or 12, 24, 36. While choose pay by year, it could be from 1 to 3. /// </remarks> [JsiiOptional] [JsiiProperty(name: "duration", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"number\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] public virtual object? Duration { get => GetInstanceProperty<object?>(); set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: instanceChargeType: The billing method. The default value is PostPaid (which means pay-as-you-go). /// </remarks> [JsiiOptional] [JsiiProperty(name: "instanceChargeType", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] public virtual object? InstanceChargeType { get => GetInstanceProperty<object?>(); set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: internetChargeType: The billing method for the NAT gateway. Valid values: /// PayBySpec: billed on a pay-by-specification basis. /// PayByLcu: billed on a pay-by-LCU basis. /// </remarks> [JsiiOptional] [JsiiProperty(name: "internetChargeType", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] public virtual object? InternetChargeType { get => GetInstanceProperty<object?>(); set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: natGatewayName: Display name of the NAT gateway, [2, 128] English or Chinese characters, must start with a letter or Chinese in size, can contain numbers, '_' or '.', '-' /// </remarks> [JsiiOptional] [JsiiProperty(name: "natGatewayName", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] public virtual object? NatGatewayName { get => GetInstanceProperty<object?>(); set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: natType: The type of the NAT gateway. Valid values: /// - Enhanced: enhanced NAT gateway. /// </remarks> [JsiiOptional] [JsiiProperty(name: "natType", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] public virtual object? NatType { get => GetInstanceProperty<object?>(); set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: networkType: The type of the created NAT gateway. /// Internet: public network NAT gateway. /// Intranet: VPC NAT gateway. /// </remarks> [JsiiOptional] [JsiiProperty(name: "networkType", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] public virtual object? NetworkType { get => GetInstanceProperty<object?>(); set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: pricingCycle: Price cycle of the resource. This property has no default value. /// </remarks> [JsiiOptional] [JsiiProperty(name: "pricingCycle", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] public virtual object? PricingCycle { get => GetInstanceProperty<object?>(); set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: spec: NAT gateway specification. Now support 'Small|Middle|Large|XLarge.1' /// </remarks> [JsiiOptional] [JsiiProperty(name: "spec", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] public virtual object? Spec { get => GetInstanceProperty<object?>(); set => SetInstanceProperty(value); } /// <remarks> /// <strong>Property</strong>: tags: Tags to attach to natgateway. Max support 20 tags to add during create natgateway. Each tag with two properties Key and Value, and Key is required. /// </remarks> [JsiiOptional] [JsiiProperty(name: "tags", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"@alicloud/ros-cdk-vpc.RosNatGateway.TagsProperty\"},\"kind\":\"array\"}}", isOptional: true)] public virtual AlibabaCloud.SDK.ROS.CDK.Vpc.RosNatGateway.ITagsProperty[]? Tags { get => GetInstanceProperty<AlibabaCloud.SDK.ROS.CDK.Vpc.RosNatGateway.ITagsProperty[]?>(); set => SetInstanceProperty(value); } [JsiiInterface(nativeType: typeof(ITagsProperty), fullyQualifiedName: "@alicloud/ros-cdk-vpc.RosNatGateway.TagsProperty")] public interface ITagsProperty { /// <remarks> /// <strong>Property</strong>: key: undefined /// </remarks> [JsiiProperty(name: "key", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")] object Key { get; } /// <remarks> /// <strong>Property</strong>: value: undefined /// </remarks> [JsiiProperty(name: "value", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] [Amazon.JSII.Runtime.Deputy.JsiiOptional] object? Value { get { return null; } } [JsiiTypeProxy(nativeType: typeof(ITagsProperty), fullyQualifiedName: "@alicloud/ros-cdk-vpc.RosNatGateway.TagsProperty")] internal sealed class _Proxy : DeputyBase, AlibabaCloud.SDK.ROS.CDK.Vpc.RosNatGateway.ITagsProperty { private _Proxy(ByRefValue reference): base(reference) { } /// <remarks> /// <strong>Property</strong>: key: undefined /// </remarks> [JsiiProperty(name: "key", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}")] public object Key { get => GetInstanceProperty<object>()!; } /// <remarks> /// <strong>Property</strong>: value: undefined /// </remarks> [JsiiOptional] [JsiiProperty(name: "value", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true)] public object? Value { get => GetInstanceProperty<object?>(); } } } #pragma warning disable CS8618 [JsiiByValue(fqn: "@alicloud/ros-cdk-vpc.RosNatGateway.TagsProperty")] public class TagsProperty : AlibabaCloud.SDK.ROS.CDK.Vpc.RosNatGateway.ITagsProperty { /// <remarks> /// <strong>Property</strong>: key: undefined /// </remarks> [JsiiProperty(name: "key", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOverride: true)] public object Key { get; set; } /// <remarks> /// <strong>Property</strong>: value: undefined /// </remarks> [JsiiOptional] [JsiiProperty(name: "value", typeJson: "{\"union\":{\"types\":[{\"primitive\":\"string\"},{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}]}}", isOptional: true, isOverride: true)] public object? Value { get; set; } } } }
50.373134
636
0.581807
[ "Apache-2.0" ]
aliyun/Resource-Orchestration-Service-Cloud-Development-K
multiple-languages/dotnet/AlibabaCloud.SDK.ROS.CDK.Vpc/AlibabaCloud/SDK/ROS/CDK/Vpc/RosNatGateway.cs
16,875
C#
namespace QFramework.GraphDesigner { public interface ISlotContextCommand { } }
14.285714
40
0.66
[ "MIT" ]
SkyAbyss/QFramework
Assets/QFramework/Framework/0.Core/Editor/0.EditorKit/uFrame.Editor/Systems/GraphUI/Drawers/impl/ISlotContextCommand.cs
100
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ODataValidator.Rule { #region Namespaces using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Xml.Linq; using System.Xml.XPath; using Newtonsoft.Json.Linq; using ODataValidator.Rule.Helper; using ODataValidator.RuleEngine; using ODataValidator.RuleEngine.Common; #endregion /// <summary> /// Class of extension rule for Entry.Core.4107 /// </summary> [Export(typeof(ExtensionRule))] public class EntryCore4107 : ExtensionRule { /// <summary> /// Gets Category property /// </summary> public override string Category { get { return "core"; } } /// <summary> /// Gets rule name /// </summary> public override string Name { get { return "Entry.Core.4107"; } } /// <summary> /// Gets rule description /// </summary> public override string Description { get { return "For expanded navigation property, if no entity is currently related, the value is null."; } } /// <summary> /// Gets rule specification in OData document /// </summary> public override string V4SpecificationSection { get { return "8.3"; } } /// <summary> /// Gets the version. /// </summary> public override ODataVersion? Version { get { return ODataVersion.V3_V4; } } /// <summary> /// Gets location of help information of the rule /// </summary> public override string HelpLink { get { return null; } } /// <summary> /// Gets the error message for validation failure /// </summary> public override string ErrorMessage { get { return this.Description; } } /// <summary> /// Gets the requirement level. /// </summary> public override RequirementLevel RequirementLevel { get { return RequirementLevel.Must; } } /// <summary> /// Gets the payload type to which the rule applies. /// </summary> public override PayloadType? PayloadType { get { return RuleEngine.PayloadType.Entry; } } /// <summary> /// Gets the payload format to which the rule applies. /// </summary> public override PayloadFormat? PayloadFormat { get { return RuleEngine.PayloadFormat.JsonLight; } } /// <summary> /// Gets the RequireMetadata property to which the rule applies. /// </summary> public override bool? RequireMetadata { get { return null; } } /// <summary> /// Gets the IsOfflineContext property to which the rule applies. /// </summary> public override bool? IsOfflineContext { get { return false; } } /// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool? passed = null; info = null; JObject entry; context.ResponsePayload.TryToJObject(out entry); XElement metadata = XElement.Parse(context.MetadataDocument); // Use the XPath query language to access the metadata document and get the node which will be used. string xpath = string.Format(@"//*[local-name()='EntityType' and @Name='{0}']/*[local-name()='NavigationProperty']", context.EntityTypeShortName); IEnumerable<XElement> props = metadata.XPathSelectElements(xpath, ODataNamespaceManager.Instance); List<string> propNames = new List<string>(); foreach (var prop in props) { propNames.Add(prop.Attribute("Name").Value); } List<string> queryOptionVals = ODataUriAnalyzer.GetQueryOptionValsFromUrl(context.Destination.ToString(), "expand"); if (entry != null && entry.Type == JTokenType.Object && queryOptionVals.Count != 0) { // Get all the properties in current entry. var jProps = entry.Children(); foreach (JProperty jProp in jProps) { bool mark = false; if (propNames.Contains(jProp.Name) && queryOptionVals.Contains(jProp.Name)) { passed = null; if (jProp.Value.Type == JTokenType.Object) { passed = null; mark = true; } else if (jProp.Value.Type == JTokenType.Array) { passed = null; mark = true; } else if (jProp.Value.Type == JTokenType.Null) { passed = true; } if (passed == null && !mark) { passed = false; info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload); break; } } } } return passed; } } }
30.04329
159
0.46268
[ "MIT" ]
OData/ValidationTool
src/CodeRules/Entry/EntryCore4107.cs
6,942
C#
using System; namespace CK.Entities { public sealed class Result<T> { #region Public Constructors public Result(T value) { Value = value; } public Result(Exception exception) { Exception = exception; } #endregion Public Constructors #region Public Properties public Exception Exception { get; } public bool IsValid => Exception is null; public T Value { get; } #endregion Public Properties } }
17.516129
49
0.556169
[ "MIT" ]
mvelasquez10/ck-backend
CK.Repository/Result.cs
545
C#
namespace Baseline.Validate { /// <summary> /// Base synchronous validation class which provides validation helper methods. /// </summary> /// <typeparam name="TToValidate">The type that is being validated.</typeparam> public abstract class SyncValidator<TToValidate> : BaseValidator<TToValidate>, ISyncValidator<TToValidate> { /// <summary> /// Validates the object of type <see cref="TToValidate" /> and returns a validation result. /// </summary> /// <param name="toValidate">The object to validate.</param> public abstract ValidationResult Validate(TToValidate toValidate); /// <summary> /// Validates the object of type <see cref="TToValidate" /> and throws an exception if the validation fails. /// </summary> /// <param name="toValidate">The object to validate.</param> public void ValidateAndThrow(TToValidate toValidate) { Validate(toValidate).ThrowIfValidationFailed(); } } }
42.583333
116
0.654599
[ "MIT" ]
getbaseline/Baseline.Validate
src/Baseline.Validate/Validators/SyncValidator.cs
1,022
C#
[TaskCategoryAttribute] // RVA: 0x1552C0 Offset: 0x1553C1 VA: 0x1552C0 [TaskDescriptionAttribute] // RVA: 0x1552C0 Offset: 0x1553C1 VA: 0x1552C0 public class GetSpread : Action // TypeDefIndex: 11356 { // Fields [TooltipAttribute] // RVA: 0x191F20 Offset: 0x192021 VA: 0x191F20 public SharedGameObject targetGameObject; // 0x50 [TooltipAttribute] // RVA: 0x191F60 Offset: 0x192061 VA: 0x191F60 [RequiredFieldAttribute] // RVA: 0x191F60 Offset: 0x192061 VA: 0x191F60 public SharedFloat storeValue; // 0x58 private AudioSource audioSource; // 0x60 private GameObject prevGameObject; // 0x68 // Methods // RVA: 0x2796EA0 Offset: 0x2796FA1 VA: 0x2796EA0 Slot: 5 public override void OnStart() { } // RVA: 0x2796FA0 Offset: 0x27970A1 VA: 0x2796FA0 Slot: 6 public override TaskStatus OnUpdate() { } // RVA: 0x2797090 Offset: 0x2797191 VA: 0x2797090 Slot: 16 public override void OnReset() { } // RVA: 0x27970E0 Offset: 0x27971E1 VA: 0x27970E0 public void .ctor() { } }
34
73
0.745436
[ "MIT" ]
SinsofSloth/RF5-global-metadata
BehaviorDesigner/Runtime/Tasks/Unity/UnityAudioSource/GetSpread.cs
986
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; namespace System { // This file collects the longer methods of Type to make the main Type class more readable. public abstract partial class Type : MemberInfo, IReflect { public virtual bool IsSerializable { get { if ((GetAttributeFlagsImpl() & TypeAttributes.Serializable) != 0) return true; Type? underlyingType = UnderlyingSystemType; if (underlyingType.IsRuntimeImplemented()) { do { // In all sane cases we only need to compare the direct level base type with // System.Enum and System.MulticastDelegate. However, a generic parameter can // have a base type constraint that is Delegate or even a real delegate type. // Let's maintain compatibility and return true for them. if (underlyingType == typeof(Delegate) || underlyingType == typeof(Enum)) return true; underlyingType = underlyingType.BaseType; } while (underlyingType != null); } return false; } } public virtual bool ContainsGenericParameters { get { if (HasElementType) return GetRootElementType().ContainsGenericParameters; if (IsGenericParameter) return true; if (!IsGenericType) return false; Type[] genericArguments = GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (genericArguments[i].ContainsGenericParameters) return true; } return false; } } internal Type GetRootElementType() { Type rootElementType = this; while (rootElementType.HasElementType) rootElementType = rootElementType.GetElementType()!; return rootElementType; } public bool IsVisible { get { #if CORECLR if (this is RuntimeType rt) return RuntimeTypeHandle.IsVisible(rt); #endif //CORECLR if (IsGenericParameter) return true; if (HasElementType) return GetElementType()!.IsVisible; Type type = this; while (type.IsNested) { if (!type.IsNestedPublic) return false; // this should be null for non-nested types. type = type.DeclaringType!; } // Now "type" should be a top level type if (!type.IsPublic) return false; if (IsGenericType && !IsGenericTypeDefinition) { foreach (Type t in GetGenericArguments()) { if (!t.IsVisible) return false; } } return true; } } public virtual Type[] FindInterfaces(TypeFilter filter, object? filterCriteria) { if (filter == null) throw new ArgumentNullException(nameof(filter)); Type?[] c = GetInterfaces(); int cnt = 0; for (int i = 0; i < c.Length; i++) { if (!filter(c[i]!, filterCriteria)) c[i] = null; else cnt++; } if (cnt == c.Length) return c!; Type[] ret = new Type[cnt]; cnt = 0; for (int i = 0; i < c.Length; i++) { if (c[i] != null) ret[cnt++] = c[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } return ret; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter? filter, object? filterCriteria) { // Define the work arrays MethodInfo?[]? m = null; ConstructorInfo?[]? c = null; FieldInfo?[]? f = null; PropertyInfo?[]? p = null; EventInfo?[]? e = null; Type?[]? t = null; int i; int cnt = 0; // Total Matchs // Check the methods if ((memberType & MemberTypes.Method) != 0) { m = GetMethods(bindingAttr); if (filter != null) { for (i = 0; i < m.Length; i++) if (!filter(m[i]!, filterCriteria)) m[i] = null; else cnt++; } else { cnt += m.Length; } } // Check the constructors if ((memberType & MemberTypes.Constructor) != 0) { c = GetConstructors(bindingAttr); if (filter != null) { for (i = 0; i < c.Length; i++) if (!filter(c[i]!, filterCriteria)) c[i] = null; else cnt++; } else { cnt += c.Length; } } // Check the fields if ((memberType & MemberTypes.Field) != 0) { f = GetFields(bindingAttr); if (filter != null) { for (i = 0; i < f.Length; i++) if (!filter(f[i]!, filterCriteria)) f[i] = null; else cnt++; } else { cnt += f.Length; } } // Check the Properties if ((memberType & MemberTypes.Property) != 0) { p = GetProperties(bindingAttr); if (filter != null) { for (i = 0; i < p.Length; i++) if (!filter(p[i]!, filterCriteria)) p[i] = null; else cnt++; } else { cnt += p.Length; } } // Check the Events if ((memberType & MemberTypes.Event) != 0) { e = GetEvents(bindingAttr); if (filter != null) { for (i = 0; i < e.Length; i++) if (!filter(e[i]!, filterCriteria)) e[i] = null; else cnt++; } else { cnt += e.Length; } } // Check the Types if ((memberType & MemberTypes.NestedType) != 0) { t = GetNestedTypes(bindingAttr); if (filter != null) { for (i = 0; i < t.Length; i++) if (!filter(t[i]!, filterCriteria)) t[i] = null; else cnt++; } else { cnt += t.Length; } } // Allocate the Member Info MemberInfo[] ret = new MemberInfo[cnt]; // Copy the Methods cnt = 0; if (m != null) { for (i = 0; i < m.Length; i++) if (m[i] != null) ret[cnt++] = m[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } // Copy the Constructors if (c != null) { for (i = 0; i < c.Length; i++) if (c[i] != null) ret[cnt++] = c[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } // Copy the Fields if (f != null) { for (i = 0; i < f.Length; i++) if (f[i] != null) ret[cnt++] = f[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } // Copy the Properties if (p != null) { for (i = 0; i < p.Length; i++) if (p[i] != null) ret[cnt++] = p[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } // Copy the Events if (e != null) { for (i = 0; i < e.Length; i++) if (e[i] != null) ret[cnt++] = e[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } // Copy the Types if (t != null) { for (i = 0; i < t.Length; i++) if (t[i] != null) ret[cnt++] = t[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644) } return ret; } public virtual bool IsSubclassOf(Type c) { Type? p = this; if (p == c) return false; while (p != null) { if (p == c) return true; p = p.BaseType; } return false; } [Intrinsic] public virtual bool IsAssignableFrom([NotNullWhen(true)] Type? c) { if (c == null) return false; if (this == c) return true; // For backward-compatibility, we need to special case for the types // whose UnderlyingSystemType are runtime implemented. Type toType = this.UnderlyingSystemType; if (toType?.IsRuntimeImplemented() == true) return toType.IsAssignableFrom(c); // If c is a subclass of this class, then c can be cast to this type. if (c.IsSubclassOf(this)) return true; if (this.IsInterface) { return c.ImplementInterface(this); } else if (IsGenericParameter) { Type[] constraints = GetGenericParameterConstraints(); for (int i = 0; i < constraints.Length; i++) if (!constraints[i].IsAssignableFrom(c)) return false; return true; } return false; } internal bool ImplementInterface(Type ifaceType) { Type? t = this; while (t != null) { Type[] interfaces = t.GetInterfaces(); if (interfaces != null) { for (int i = 0; i < interfaces.Length; i++) { // Interfaces don't derive from other interfaces, they implement them. // So instead of IsSubclassOf, we should use ImplementInterface instead. if (interfaces[i] == ifaceType || (interfaces[i] != null && interfaces[i].ImplementInterface(ifaceType))) return true; } } t = t.BaseType; } return false; } // FilterAttribute // This method will search for a member based upon the attribute passed in. // filterCriteria -- an Int32 representing the attribute private static bool FilterAttributeImpl(MemberInfo m, object filterCriteria) { // Check that the criteria object is an Integer object if (filterCriteria == null) throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritInt); switch (m.MemberType) { case MemberTypes.Constructor: case MemberTypes.Method: { MethodAttributes criteria; try { int i = (int)filterCriteria; criteria = (MethodAttributes)i; } catch { throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritInt); } MethodAttributes attr; if (m.MemberType == MemberTypes.Method) attr = ((MethodInfo)m).Attributes; else attr = ((ConstructorInfo)m).Attributes; if (((criteria & MethodAttributes.MemberAccessMask) != 0) && (attr & MethodAttributes.MemberAccessMask) != (criteria & MethodAttributes.MemberAccessMask)) return false; if (((criteria & MethodAttributes.Static) != 0) && (attr & MethodAttributes.Static) == 0) return false; if (((criteria & MethodAttributes.Final) != 0) && (attr & MethodAttributes.Final) == 0) return false; if (((criteria & MethodAttributes.Virtual) != 0) && (attr & MethodAttributes.Virtual) == 0) return false; if (((criteria & MethodAttributes.Abstract) != 0) && (attr & MethodAttributes.Abstract) == 0) return false; if (((criteria & MethodAttributes.SpecialName) != 0) && (attr & MethodAttributes.SpecialName) == 0) return false; return true; } case MemberTypes.Field: { FieldAttributes criteria; try { int i = (int)filterCriteria; criteria = (FieldAttributes)i; } catch { throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritInt); } FieldAttributes attr = ((FieldInfo)m).Attributes; if (((criteria & FieldAttributes.FieldAccessMask) != 0) && (attr & FieldAttributes.FieldAccessMask) != (criteria & FieldAttributes.FieldAccessMask)) return false; if (((criteria & FieldAttributes.Static) != 0) && (attr & FieldAttributes.Static) == 0) return false; if (((criteria & FieldAttributes.InitOnly) != 0) && (attr & FieldAttributes.InitOnly) == 0) return false; if (((criteria & FieldAttributes.Literal) != 0) && (attr & FieldAttributes.Literal) == 0) return false; if (((criteria & FieldAttributes.NotSerialized) != 0) && (attr & FieldAttributes.NotSerialized) == 0) return false; if (((criteria & FieldAttributes.PinvokeImpl) != 0) && (attr & FieldAttributes.PinvokeImpl) == 0) return false; return true; } } return false; } // FilterName // This method will filter based upon the name. A partial wildcard // at the end of the string is supported. // filterCriteria -- This is the string name private static bool FilterNameImpl(MemberInfo m, object filterCriteria, StringComparison comparison) { // Check that the criteria object is a String object if (!(filterCriteria is string filterCriteriaString)) { throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritString); } ReadOnlySpan<char> str = filterCriteriaString.AsSpan().Trim(); ReadOnlySpan<char> name = m.Name; // Get the nested class name only, as opposed to the mangled one if (m.MemberType == MemberTypes.NestedType) { name = name.Slice(name.LastIndexOf('+') + 1); } // Check to see if this is a prefix or exact match requirement if (str.Length > 0 && str[str.Length - 1] == '*') { str = str.Slice(0, str.Length - 1); return name.StartsWith(str, comparison); } return name.Equals(str, comparison); } } }
35.847826
178
0.428524
[ "MIT" ]
71221-maker/runtime
src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs
18,139
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Wavelength.Api.Dtos; using Wavelength.Api.Models; namespace Wavelength.Api.Controllers { [Route("api/bars")] public class BarsController : WavelengthController { public BarsController(WavelengthDbContext context, FacebookApi api) : base(context, api) { } [HttpGet] [Route("")] public async Task<IActionResult> GetBars() { var bars = await DbContext.Bars.ToListAsync(); return Ok(bars.Select(b => b.ToDto())); } #region Reports [HttpGet] [Route("reports")] public async Task<IActionResult> GetReports() { var bars = await DbContext.Bars.ToListAsync(); var reportStart = DateTime.UtcNow - TimeSpan.FromHours(2); return Ok(bars.Select(b => b.ReportSince(reportStart).ToDto())); } [HttpGet] [Route("{id}/report")] public async Task<IActionResult> GetReport(int id) { Bar bar; if ((bar = await DbContext.Bars.FindAsync(id)) == null) { return NotFound(); } var reportStart = DateTime.UtcNow - TimeSpan.FromHours(2); return Ok(bar.ReportSince(reportStart).ToDto()); } [HttpPost] [Route("{id}/report")] public async Task<IActionResult> PostReport(int id, [FromBody] BarReportDto dto) { var bar = await DbContext.Bars.FindAsync(id); if (bar == null) { return NotFound(); } var report = new BarReport { Bar = bar, ReportedBy = null, ReportedOn = DateTime.UtcNow, Cover = dto.Cover, Line = dto.Line, Capacity = dto.Capacity }; DbContext.BarReports.Add(report); await DbContext.SaveChangesAsync(); return Ok(); } #endregion #region Tenders [HttpGet] [Route("{id}/tenders")] public async Task<IActionResult> GetTenders(int id) { if (await DbContext.Bars.FindAsync(id) == null) { return NotFound(); } // Start time is right now var start = DateTime.UtcNow; // If it's between 12am and 2am, add 2 hours to the date, otherwise 26 (1 day + 2 hours) var end = start.Date + TimeSpan.FromHours(start.TimeOfDay.Hours < 2 ? 2 : 26); var friends = await FacebookApi.GetUserFriends(User.Claims.Single(c => c.Type == "token").Value); var shifts = await DbContext.Shifts.Where(s => s.Bar.Id == id && s.Start < end && s.End > start && friends.Contains(s.Profile.FacebookId)) .ToArrayAsync(); return Ok(shifts.Select(s => s.ToDto())); } #endregion } }
28.747826
110
0.509982
[ "MIT" ]
tVoss/wavelength
src/api/Controllers/BarsController.cs
3,308
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.Emr.Model.V20160408 { public class DescribeEmrMainVersionResponse : AcsResponse { private string requestId; private DescribeEmrMainVersion_EmrMainVersion emrMainVersion; public string RequestId { get { return requestId; } set { requestId = value; } } public DescribeEmrMainVersion_EmrMainVersion EmrMainVersion { get { return emrMainVersion; } set { emrMainVersion = value; } } public class DescribeEmrMainVersion_EmrMainVersion { private string regionId; private string emrVersion; private bool? ecmVersion; private string imageId; private bool? display; private string stackName; private string stackVersion; private string publishType; private List<DescribeEmrMainVersion_ClusterTypeInfo> clusterTypeInfoList; private List<DescribeEmrMainVersion_ClusterTypeWhiteUser> clusterTypeWhiteUserList; private List<string> whiteUserList; public string RegionId { get { return regionId; } set { regionId = value; } } public string EmrVersion { get { return emrVersion; } set { emrVersion = value; } } public bool? EcmVersion { get { return ecmVersion; } set { ecmVersion = value; } } public string ImageId { get { return imageId; } set { imageId = value; } } public bool? Display { get { return display; } set { display = value; } } public string StackName { get { return stackName; } set { stackName = value; } } public string StackVersion { get { return stackVersion; } set { stackVersion = value; } } public string PublishType { get { return publishType; } set { publishType = value; } } public List<DescribeEmrMainVersion_ClusterTypeInfo> ClusterTypeInfoList { get { return clusterTypeInfoList; } set { clusterTypeInfoList = value; } } public List<DescribeEmrMainVersion_ClusterTypeWhiteUser> ClusterTypeWhiteUserList { get { return clusterTypeWhiteUserList; } set { clusterTypeWhiteUserList = value; } } public List<string> WhiteUserList { get { return whiteUserList; } set { whiteUserList = value; } } public class DescribeEmrMainVersion_ClusterTypeInfo { private string clusterType; private List<DescribeEmrMainVersion_ServiceInfo> serviceInfoList; public string ClusterType { get { return clusterType; } set { clusterType = value; } } public List<DescribeEmrMainVersion_ServiceInfo> ServiceInfoList { get { return serviceInfoList; } set { serviceInfoList = value; } } public class DescribeEmrMainVersion_ServiceInfo { private string serviceName; private string serviceDisplayName; private string serviceVersion; private string serviceDisplayVersion; private bool? mandatory; private bool? display; public string ServiceName { get { return serviceName; } set { serviceName = value; } } public string ServiceDisplayName { get { return serviceDisplayName; } set { serviceDisplayName = value; } } public string ServiceVersion { get { return serviceVersion; } set { serviceVersion = value; } } public string ServiceDisplayVersion { get { return serviceDisplayVersion; } set { serviceDisplayVersion = value; } } public bool? Mandatory { get { return mandatory; } set { mandatory = value; } } public bool? Display { get { return display; } set { display = value; } } } } public class DescribeEmrMainVersion_ClusterTypeWhiteUser { private string clusterType; private string userId; public string ClusterType { get { return clusterType; } set { clusterType = value; } } public string UserId { get { return userId; } set { userId = value; } } } } } }
16.106267
87
0.554728
[ "Apache-2.0" ]
aliyun/aliyun-openapi-net-sdk
aliyun-net-sdk-emr/Emr/Model/V20160408/DescribeEmrMainVersionResponse.cs
5,911
C#
using System.Diagnostics; using xnaMugen.IO; namespace xnaMugen.StateMachine.Controllers { [StateControllerName("PowerSet")] internal class PowerSet : StateController { public PowerSet(StateSystem statesystem, string label, TextSection textsection) : base(statesystem, label, textsection) { m_power = textsection.GetAttribute<Evaluation.Expression>("value", null); } public override void Run(Combat.Character character) { var power = EvaluationHelper.AsInt32(character, Power, null); if (power != null) character.BasePlayer.Power = power.Value; } public override bool IsValid() { if (base.IsValid() == false) return false; if (Power == null) return false; return true; } public Evaluation.Expression Power => m_power; #region Fields [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly Evaluation.Expression m_power; #endregion } }
23.675
82
0.706441
[ "BSD-3-Clause" ]
BlazesRus/xnamugen
src/StateMachine/Controllers/PowerSet.cs
947
C#
namespace EasyLOB { /// <summary> /// ZActivityOperations. /// </summary> public class ZActivityOperations { #region Properties /// <summary> /// Activity name. /// </summary> public string Activity { get; set; } /// <summary> /// Is Index ( open Grid from menu ) allowed ? /// </summary> public bool IsIndex { get; set; } /// <summary> /// Is Search ( open Grid from menu or lookup ) allowed ? /// </summary> public bool IsSearch { get; set; } /// <summary> /// Is Create allowed ? /// </summary> public bool IsCreate { get; set; } /// <summary> /// Is Read allowed ? /// </summary> public bool IsRead { get; set; } /// <summary> /// Is Update allowed ? /// </summary> public bool IsUpdate { get; set; } /// <summary> /// Is Delete allowed ? /// </summary> public bool IsDelete { get; set; } /// <summary> /// Is Export allowed ? /// </summary> public bool IsExport { get; set; } /// <summary> /// Is Task ( used for Tasks ) allowed ? /// </summary> public bool IsExecute { get; set; } #endregion Properties } }
24.293103
66
0.450674
[ "MIT" ]
EasyLOB/EasyLOB-3
EasyLOB/Activity/ZActivityOperations.cs
1,411
C#