content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
namespace BundleTransformer.UglifyJs
{
/// <summary>
/// Compression options
/// </summary>
public sealed class CompressionOptions
{
/// <summary>
/// Gets or sets a flag for whether to enable support of <code>@ngInject</code> annotations
/// </summary>
public bool Angular
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to enable various optimizations for boolean
/// context (for example, <code>!!a ? b : c → a ? b : c</code>)
/// </summary>
public bool Booleans
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to small optimization for sequences
/// (for example: transform <code>x, x</code> into <code>x</code>
/// and <code>x = something(), x</code> into <code>x = something()</code>)
/// </summary>
public bool Cascade
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to collapse single-use <code>var</code> and
/// <code>const</code> definitions when possible
/// </summary>
public bool CollapseVars
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to apply certain optimizations
/// to binary nodes, attempts to negate binary nodes, etc.
/// </summary>
public bool Comparisons
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to compress code
/// </summary>
public bool Compress
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to apply optimizations
/// for <code>if</code>-s and conditional expressions
/// </summary>
public bool Conditionals
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to remove unreachable code
/// </summary>
public bool DeadCode
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to discard calls to <code>console.*</code> functions
/// </summary>
public bool DropConsole
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to remove <code>debugger;</code> statements
/// </summary>
public bool DropDebugger
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to attempt to evaluate constant expressions
/// </summary>
public bool Evaluate
{
get;
set;
}
/// <summary>
/// Gets or sets a string representation of the object
/// (comma-separated list of values of the form SYMBOL[=value])
/// with properties named after symbols to replace
/// (except where symbol has properly declared by a var declaration
/// or use as function parameter or similar) and the values
/// representing the AST replacement value
/// </summary>
public string GlobalDefinitions
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to hoist function declarations
/// </summary>
public bool HoistFunctions
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to hoist <code>var</code> declarations
/// </summary>
public bool HoistVars
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to enable optimizations for if/return
/// and if/continue
/// </summary>
public bool IfReturn
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to join consecutive <code>var</code> statements
/// </summary>
public bool JoinVars
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to prevent the compressor from discarding
/// unused function arguments
/// </summary>
public bool KeepFunctionArgs
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to prevent <code>Infinity</code> from being compressed
/// into <code>1/0</code>, which may cause performance issues on Chrome
/// </summary>
public bool KeepInfinity
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to enable optimizations for <code>do</code>, <code>while</code>
/// and <code>for</code> loops when we can statically determine the condition
/// </summary>
public bool Loops
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to negate IIFEs
/// </summary>
public bool NegateIife
{
get;
set;
}
/// <summary>
/// Gets or sets a number of times to run compress
/// </summary>
public int Passes
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to rewrite property access using
/// the dot notation (for example, <code>foo["bar"] → foo.bar</code>)
/// </summary>
public bool PropertiesDotNotation
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to UglifyJS will assume
/// that object property access (e.g. <code>foo.bar</code> or <code>foo["bar"]</code>)
/// doesn't have any side effects
/// </summary>
public bool PureGetters
{
get;
set;
}
/// <summary>
/// Gets or sets a string representation of the functions list,
/// that can be safely removed if their return value is not used
/// </summary>
public string PureFunctions
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to improve optimization on variables assigned
/// with and used as constant values
/// </summary>
public bool ReduceVars
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to join consecutive simple
/// statements using the comma operator
/// </summary>
public bool Sequences
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to drop unreferenced functions and variables in
/// the toplevel scope
/// </summary>
public bool TopLevel
{
get;
set;
}
/// <summary>
/// Gets or sets a comma-separated list of toplevel functions and variables to exclude
/// from <code>unused</code> removal
/// </summary>
public string TopRetain
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to apply "unsafe" transformations
/// </summary>
public bool Unsafe
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to optimize numerical expressions like <code>2 * x * 3</code>
/// into <code>6 * x</code>, which may give imprecise floating point results
/// </summary>
public bool UnsafeMath
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to optimize expressions like
/// <code>Array.prototype.slice.call(a)</code> into <code>[].slice.call(a)</code>
/// </summary>
public bool UnsafeProto
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to enable substitutions of variables with <code>RegExp</code>
/// values the same way as if they are constants
/// </summary>
public bool UnsafeRegExp
{
get;
set;
}
/// <summary>
/// Gets or sets a flag for whether to drop unreferenced functions and variables
/// </summary>
public bool Unused
{
get;
set;
}
/// <summary>
/// Constructs a instance of the compression options
/// </summary>
public CompressionOptions()
{
Angular = false;
Booleans = true;
Cascade = true;
CollapseVars = true;
Comparisons = true;
Compress = true;
Conditionals = true;
DeadCode = true;
DropConsole = false;
DropDebugger = true;
Evaluate = true;
GlobalDefinitions = string.Empty;
HoistFunctions = true;
HoistVars = false;
IfReturn = true;
JoinVars = true;
KeepFunctionArgs = true;
KeepInfinity = false;
Loops = true;
NegateIife = true;
Passes = 1;
PropertiesDotNotation = true;
PureGetters = false;
PureFunctions = string.Empty;
ReduceVars = true;
Sequences = true;
TopLevel = false;
TopRetain = string.Empty;
Unsafe = false;
UnsafeMath = false;
UnsafeProto = false;
UnsafeRegExp = false;
Unused = true;
}
}
} | 22.008065 | 102 | 0.597655 | [
"Apache-2.0"
] | kapral/BundleTransformer | src/BundleTransformer.UglifyJS/CompressionOptions.cs | 8,193 | C# |
using System.Threading.Tasks;
using Elastic.Xunit.XunitPlumbing;
using Nest;
using Tests.Framework.EndpointTests;
using static Tests.Framework.EndpointTests.UrlTester;
namespace Tests.XPack.MachineLearning.DeleteExpiredData
{
public class DeleteExpiredDataUrlTests : UrlTestsBase
{
[U] public override async Task Urls() => await DELETE("/_ml/_delete_expired_data")
.Fluent(c => c.MachineLearning.DeleteExpiredData())
.Request(c => c.MachineLearning.DeleteExpiredData(new DeleteExpiredDataRequest()))
.FluentAsync(c => c.MachineLearning.DeleteExpiredDataAsync())
.RequestAsync(c => c.MachineLearning.DeleteExpiredDataAsync(new DeleteExpiredDataRequest()));
}
}
| 37.722222 | 96 | 0.795287 | [
"Apache-2.0"
] | AnthAbou/elasticsearch-net | src/Tests/Tests/XPack/MachineLearning/DeleteExpiredData/DeleteExpiredDataUrlTests.cs | 681 | C# |
using System.Threading.Tasks;
using OrchardCore.ContentManagement.Display.ContentDisplay;
using OrchardCore.ContentManagement.Display.Models;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Views;
using TransformalizeModule.Models;
using TransformalizeModule.ViewModels;
namespace TransformalizeModule.Drivers {
public class TransformalizeFilePartDisplayDriver : ContentPartDisplayDriver<TransformalizeFilePart> {
public TransformalizeFilePartDisplayDriver() {}
public override IDisplayResult Edit(TransformalizeFilePart part) {
return Initialize<EditTransformalizeFilePartViewModel>("TransformalizeFilePart_Edit", model => {
model.TransformalizeFilePart = part;
model.OriginalName = part.OriginalName;
model.FullPath = part.FullPath;
}).Location("Content:1");
}
public override async Task<IDisplayResult> UpdateAsync(TransformalizeFilePart part, IUpdateModel updater, UpdatePartEditorContext context) {
var model = new EditTransformalizeFilePartViewModel();
if (await updater.TryUpdateModelAsync(model, Prefix)) {
part.OriginalName.Text = model.OriginalName.Text;
part.FullPath.Text = model.FullPath.Text;
}
return Edit(part, context);
}
}
}
| 36.216216 | 146 | 0.74403 | [
"Apache-2.0"
] | EasyOC/EasyOC | src/Modules/OrchardCore.Transformalize/Drivers/TransformalizeFilePartDisplayDriver.cs | 1,340 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LibUsingFileFunctions.HardToTest
{
public class FileHandling
{
public FileHandling()
{
}
public IEnumerable<string> CheckFilesInSomeDirectory(string path)
{
var current = Directory.GetCurrentDirectory();
var filesHereAndBelow = Directory.GetFiles(current, "*.*", SearchOption.AllDirectories).ToList();
return filesHereAndBelow;
}
public string ReadAllLinesFromAFile(string path)
{
if (!File.Exists(path))
return "";
var txt = File.ReadAllText(path);
return txt;
}
}
}
| 23.558824 | 109 | 0.602996 | [
"MIT"
] | WrapThat/WrapThat.System | Demo/LibUsingFileFunctions/HardToTestFileFunctions.cs | 803 | C# |
using Microsoft.AspNetCore.Components;
namespace AntDesign.Pro.Template.Pages.Account.Center
{
public partial class AvatarList
{
[Parameter] public RenderFragment ChildContent { get; set; }
}
} | 23.777778 | 68 | 0.728972 | [
"Apache-2.0"
] | 1317907874/- | src/AntDesign.Pro/Pages/Account/Center/Components/AvatarList/AvatarList.razor.cs | 214 | C# |
using HealthyNutGuysDomain.Models;
using HealthyNutGuysDomain.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HealthyNutGuysDomain.Converters
{
public static class SpecialOfferConverter
{
public static SpecialOfferViewModel Convert(SpecialOffer specialOffer)
{
SpecialOfferViewModel model = new SpecialOfferViewModel();
model.Id = specialOffer.Id;
model.PromoCodeId = specialOffer.PromoCodeId;
model.Scope = (OfferScope)specialOffer?.Scope;
model.Type = (OfferType)specialOffer.Type;
model.ExpireDate = (DateTime)specialOffer?.ExpireDate;
model.DisplayMessage = specialOffer.DisplayMessage;
if (specialOffer.SalePrice != null)
model.SalePrice = specialOffer.SalePrice;
return model;
}
public static List<SpecialOfferViewModel> ConvertList(IEnumerable<SpecialOffer> specialOffers)
{
return specialOffers.Select(offer => Convert(offer)).ToList();
}
}
}
| 34.424242 | 102 | 0.662852 | [
"MIT"
] | omikolaj/healthy-nut-guys-api | HealthyNutGuysDomain/Converters/SpecialOfferConverter.cs | 1,138 | C# |
namespace Arke.DSL.Step
{
public enum RecordingItems
{
InboundLine,
OutboundLine,
Bridge
}
}
| 11.909091 | 30 | 0.557252 | [
"MIT"
] | sgnayak/arke | Arke.DSL/Step/RecordingItems.cs | 133 | 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 HolidayLabelsAndListsHelper;
//using GlobRes = AppWideResources.Properties.Resources;
namespace HolidayLabelsAndLists
{
public partial class frmFileMaintenance : Form
{
private HllFileListManager flm;
// Let caller (frmMain) know if it needs to update itself:
public bool FilesChanged
{
get; private set;
}
public frmFileMaintenance(HllFileListManager m)
{
InitializeComponent();
this.flm = m;
this.FilesChanged = false;
SetControls();
}
private void SetControls()
{
SetCaptions();
SetButtons();
}
private void SetCaptions()
{
btnDeleteBackups.Text = Properties.Resources.DelBackupsBtnCaption;
btnDeleteOld.Text = Properties.Resources.DelOldFilesDialogBtnCaption;
btnDone.Text = Properties.Resources.CloseBtnCaption;
btnSave.Text = Properties.Resources.SaveFilesBtnCaption;
btnHelp.Text = Properties.Resources.HelpBtnCaption;
}
/// <summary>
/// Gray out buttons which aren't relevant.
/// </summary>
private void SetButtons()
{
// Show Delete BU btn if there are backup files to delete:
btnDeleteBackups.Enabled = flm.HasBackupFiles;
// We can't delete latest year's files -- don't show this
// button unless there are some years we can delete from:
btnDeleteOld.Enabled = flm.YearsInFileList().Count() > 0;
}
private void btnDone_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnDeleteBackups_Click(object sender, EventArgs e)
{
var mbRes = MessageBox.Show(
Properties.Resources.DelBackupConfirmPrompt,
Properties.Resources.DelBackupConfirmTitle,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question
);
if (mbRes != DialogResult.Yes)
return;
try
{
if (this.flm.DeleteBackupFiles() > 0)
{
SetButtons();
this.FilesChanged = true;
}
}
catch (Exception fe)
{
MessageBox.Show(
string.Format(Properties.Resources.DelBackupErrorMsg, fe.Message),
"",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation
);
}
}
/// <summary>
/// TODO: Add code to remind about saving before opening
/// dialog.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDeleteOld_Click(object sender, EventArgs e)
{
using (frmDeleteOldFiles OldFilesForm = new frmDeleteOldFiles(flm))
{
OldFilesForm.ShowDialog();
}
this.Focus();
}
private void btnSave_Click(object sender, EventArgs e)
{
using (frmSaveFiles SaveForm = new frmSaveFiles(flm))
{
SaveForm.ShowDialog();
}
}
private void btnHelp_Click(object sender, EventArgs e)
{
//frmHelp helpForm = new frmHelp();
//string doc_html = Properties.Resources.FileManagementHTML;
//helpForm.HelpText = doc_html;
//helpForm.Text = Properties.Resources.OutputFileManagementDocTitle;
//helpForm.ShowDialog();
}
}
}
| 31.023622 | 86 | 0.552792 | [
"MIT"
] | tonyrein/HolidayLabelsAndLists_Public | HolidayLabelsAndLists/frmFileMaintenance.cs | 3,942 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using dnlib.DotNet;
using dnlib.DotNet.Emit;
namespace Confuser.Core
{
/// <summary>
/// Provides a set of utility methods about dnlib
/// </summary>
// Token: 0x0200003D RID: 61
public static class DnlibUtils
{
/// <summary>
/// Finds all definitions of interest in a module.
/// </summary>
/// <param name="module">The module.</param>
/// <returns>A collection of all required definitions</returns>
// Token: 0x06000149 RID: 329 RVA: 0x0000B284 File Offset: 0x00009484
public static IEnumerable<IDnlibDef> FindDefinitions(this ModuleDef module)
{
yield return module;
foreach (TypeDef current in module.GetTypes())
{
yield return current;
foreach (MethodDef current2 in current.Methods)
{
yield return current2;
}
foreach (FieldDef current3 in current.Fields)
{
yield return current3;
}
foreach (PropertyDef current4 in current.Properties)
{
yield return current4;
}
foreach (EventDef current5 in current.Events)
{
yield return current5;
}
}
yield break;
}
/// <summary>
/// Finds all definitions of interest in a type.
/// </summary>
/// <param name="typeDef">The type.</param>
/// <returns>A collection of all required definitions</returns>
// Token: 0x0600014A RID: 330 RVA: 0x0000B748 File Offset: 0x00009948
public static IEnumerable<IDnlibDef> FindDefinitions(this TypeDef typeDef)
{
yield return typeDef;
foreach (TypeDef current in typeDef.NestedTypes)
{
yield return current;
}
foreach (MethodDef current2 in typeDef.Methods)
{
yield return current2;
}
foreach (FieldDef current3 in typeDef.Fields)
{
yield return current3;
}
foreach (PropertyDef current4 in typeDef.Properties)
{
yield return current4;
}
foreach (EventDef current5 in typeDef.Events)
{
yield return current5;
}
yield break;
}
/// <summary>
/// Determines whether the specified type is visible outside the containing assembly.
/// </summary>
/// <param name="typeDef">The type.</param>
/// <param name="exeNonPublic">Visibility of executable modules.</param>
/// <returns><c>true</c> if the specified type is visible outside the containing assembly; otherwise, <c>false</c>.</returns>
// Token: 0x0600014B RID: 331 RVA: 0x0000B768 File Offset: 0x00009968
public static bool IsVisibleOutside(this TypeDef typeDef, bool exeNonPublic = true)
{
if (exeNonPublic && (typeDef.Module.Kind == ModuleKind.Windows || typeDef.Module.Kind == ModuleKind.Console))
{
return false;
}
while (typeDef.DeclaringType != null)
{
if (!typeDef.IsNestedPublic && !typeDef.IsNestedFamily && !typeDef.IsNestedFamilyOrAssembly)
{
return false;
}
typeDef = typeDef.DeclaringType;
if (typeDef == null)
{
throw new UnreachableException();
}
}
return typeDef.IsPublic;
}
/// <summary>
/// Determines whether the object has the specified custom attribute.
/// </summary>
/// <param name="obj">The object.</param>
/// <param name="fullName">The full name of the type of custom attribute.</param>
/// <returns><c>true</c> if the specified object has custom attribute; otherwise, <c>false</c>.</returns>
// Token: 0x0600014C RID: 332 RVA: 0x0000B7EC File Offset: 0x000099EC
public static bool HasAttribute(this IHasCustomAttribute obj, string fullName)
{
return obj.CustomAttributes.Any((CustomAttribute attr) => attr.TypeFullName == fullName);
}
/// <summary>
/// Determines whether the specified type is COM import.
/// </summary>
/// <param name="type">The type.</param>
/// <returns><c>true</c> if specified type is COM import; otherwise, <c>false</c>.</returns>
// Token: 0x0600014D RID: 333 RVA: 0x0000B81D File Offset: 0x00009A1D
public static bool IsComImport(this TypeDef type)
{
return type.IsImport || type.HasAttribute("System.Runtime.InteropServices.ComImportAttribute") || type.HasAttribute("System.Runtime.InteropServices.TypeLibTypeAttribute");
}
/// <summary>
/// Determines whether the specified type is a delegate.
/// </summary>
/// <param name="type">The type.</param>
/// <returns><c>true</c> if the specified type is a delegate; otherwise, <c>false</c>.</returns>
// Token: 0x0600014E RID: 334 RVA: 0x0000B844 File Offset: 0x00009A44
public static bool IsDelegate(this TypeDef type)
{
if (type.BaseType == null)
{
return false;
}
string fullName = type.BaseType.FullName;
return fullName == "System.Delegate" || fullName == "System.MulticastDelegate";
}
/// <summary>
/// Determines whether the specified type is inherited from a base type in corlib.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="baseType">The full name of base type.</param>
/// <returns><c>true</c> if the specified type is inherited from a base type; otherwise, <c>false</c>.</returns>
// Token: 0x0600014F RID: 335 RVA: 0x0000B884 File Offset: 0x00009A84
public static bool InheritsFromCorlib(this TypeDef type, string baseType)
{
if (type.BaseType == null)
{
return false;
}
TypeDef bas = type;
while (true)
{
bas = bas.BaseType.ResolveTypeDefThrow();
if (bas.ReflectionFullName == baseType)
{
break;
}
if (bas.BaseType == null || !bas.BaseType.DefinitionAssembly.IsCorLib())
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether the specified type is inherited from a base type.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="baseType">The full name of base type.</param>
/// <returns><c>true</c> if the specified type is inherited from a base type; otherwise, <c>false</c>.</returns>
// Token: 0x06000150 RID: 336 RVA: 0x0000B8D4 File Offset: 0x00009AD4
public static bool InheritsFrom(this TypeDef type, string baseType)
{
if (type.BaseType == null)
{
return false;
}
TypeDef bas = type;
while (true)
{
bas = bas.BaseType.ResolveTypeDefThrow();
if (bas.ReflectionFullName == baseType)
{
break;
}
if (bas.BaseType == null)
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether the specified type implements the specified interface.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="fullName">The full name of the type of interface.</param>
/// <returns><c>true</c> if the specified type implements the interface; otherwise, <c>false</c>.</returns>
// Token: 0x06000151 RID: 337 RVA: 0x0000B914 File Offset: 0x00009B14
public static bool Implements(this TypeDef type, string fullName)
{
while (true)
{
foreach (InterfaceImpl iface in type.Interfaces)
{
if (iface.Interface.ReflectionFullName == fullName)
{
return true;
}
}
if (type.BaseType == null)
{
break;
}
type = type.BaseType.ResolveTypeDefThrow();
if (type == null)
{
goto Block_2;
}
}
return false;
Block_2:
throw new UnreachableException();
}
/// <summary>
/// Resolves the method.
/// </summary>
/// <param name="method">The method to resolve.</param>
/// <returns>A <see cref="T:dnlib.DotNet.MethodDef" /> instance.</returns>
/// <exception cref="T:dnlib.DotNet.MemberRefResolveException">The method couldn't be resolved.</exception>
// Token: 0x06000152 RID: 338 RVA: 0x0000B994 File Offset: 0x00009B94
public static MethodDef ResolveThrow(this IMethod method)
{
MethodDef def = method as MethodDef;
if (def != null)
{
return def;
}
MethodSpec spec = method as MethodSpec;
if (spec != null)
{
return spec.Method.ResolveThrow();
}
return ((MemberRef)method).ResolveMethodThrow();
}
/// <summary>
/// Resolves the field.
/// </summary>
/// <param name="field">The field to resolve.</param>
/// <returns>A <see cref="T:dnlib.DotNet.FieldDef" /> instance.</returns>
/// <exception cref="T:dnlib.DotNet.MemberRefResolveException">The method couldn't be resolved.</exception>
// Token: 0x06000153 RID: 339 RVA: 0x0000B9D0 File Offset: 0x00009BD0
public static FieldDef ResolveThrow(this IField field)
{
FieldDef def = field as FieldDef;
if (def != null)
{
return def;
}
return ((MemberRef)field).ResolveFieldThrow();
}
/// <summary>
/// Find the basic type reference.
/// </summary>
/// <param name="typeSig">The type signature to get the basic type.</param>
/// <returns>A <see cref="T:dnlib.DotNet.ITypeDefOrRef" /> instance, or null if the typeSig cannot be resolved to basic type.</returns>
// Token: 0x06000154 RID: 340 RVA: 0x0000B9F4 File Offset: 0x00009BF4
public static ITypeDefOrRef ToBasicTypeDefOrRef(this TypeSig typeSig)
{
while (typeSig.Next != null)
{
typeSig = typeSig.Next;
}
if (typeSig is GenericInstSig)
{
return ((GenericInstSig)typeSig).GenericType.TypeDefOrRef;
}
if (typeSig is TypeDefOrRefSig)
{
return ((TypeDefOrRefSig)typeSig).TypeDefOrRef;
}
return null;
}
/// <summary>
/// Find the type references within the specified type signature.
/// </summary>
/// <param name="typeSig">The type signature to find the type references.</param>
/// <returns>A list of <see cref="T:dnlib.DotNet.ITypeDefOrRef" /> instance.</returns>
// Token: 0x06000155 RID: 341 RVA: 0x0000BA44 File Offset: 0x00009C44
public static IList<ITypeDefOrRef> FindTypeRefs(this TypeSig typeSig)
{
List<ITypeDefOrRef> ret = new List<ITypeDefOrRef>();
DnlibUtils.FindTypeRefsInternal(typeSig, ret);
return ret;
}
// Token: 0x06000156 RID: 342 RVA: 0x0000BA60 File Offset: 0x00009C60
private static void FindTypeRefsInternal(TypeSig typeSig, IList<ITypeDefOrRef> ret)
{
while (typeSig.Next != null)
{
if (typeSig is ModifierSig)
{
ret.Add(((ModifierSig)typeSig).Modifier);
}
typeSig = typeSig.Next;
}
if (typeSig is GenericInstSig)
{
GenericInstSig genInst = (GenericInstSig)typeSig;
ret.Add(genInst.GenericType.TypeDefOrRef);
using (IEnumerator<TypeSig> enumerator = genInst.GenericArguments.GetEnumerator())
{
while (enumerator.MoveNext())
{
TypeSig genArg = enumerator.Current;
DnlibUtils.FindTypeRefsInternal(genArg, ret);
}
return;
}
}
if (typeSig is TypeDefOrRefSig)
{
for (ITypeDefOrRef type = ((TypeDefOrRefSig)typeSig).TypeDefOrRef; type != null; type = type.DeclaringType)
{
ret.Add(type);
}
}
}
/// <summary>
/// Determines whether the specified property is public.
/// </summary>
/// <param name="property">The property.</param>
/// <returns><c>true</c> if the specified property is public; otherwise, <c>false</c>.</returns>
// Token: 0x06000157 RID: 343 RVA: 0x0000BB28 File Offset: 0x00009D28
public static bool IsPublic(this PropertyDef property)
{
if (property.GetMethod != null && property.GetMethod.IsPublic)
{
return true;
}
if (property.SetMethod != null && property.SetMethod.IsPublic)
{
return true;
}
return property.OtherMethods.Any((MethodDef method) => method.IsPublic);
}
/// <summary>
/// Determines whether the specified property is static.
/// </summary>
/// <param name="property">The property.</param>
/// <returns><c>true</c> if the specified property is static; otherwise, <c>false</c>.</returns>
// Token: 0x06000158 RID: 344 RVA: 0x0000BB94 File Offset: 0x00009D94
public static bool IsStatic(this PropertyDef property)
{
if (property.GetMethod != null && property.GetMethod.IsStatic)
{
return true;
}
if (property.SetMethod != null && property.SetMethod.IsStatic)
{
return true;
}
return property.OtherMethods.Any((MethodDef method) => method.IsStatic);
}
/// <summary>
/// Determines whether the specified event is public.
/// </summary>
/// <param name="evt">The event.</param>
/// <returns><c>true</c> if the specified event is public; otherwise, <c>false</c>.</returns>
// Token: 0x06000159 RID: 345 RVA: 0x0000BC00 File Offset: 0x00009E00
public static bool IsPublic(this EventDef evt)
{
if (evt.AddMethod != null && evt.AddMethod.IsPublic)
{
return true;
}
if (evt.RemoveMethod != null && evt.RemoveMethod.IsPublic)
{
return true;
}
if (evt.InvokeMethod != null && evt.InvokeMethod.IsPublic)
{
return true;
}
return evt.OtherMethods.Any((MethodDef method) => method.IsPublic);
}
/// <summary>
/// Determines whether the specified event is static.
/// </summary>
/// <param name="evt">The event.</param>
/// <returns><c>true</c> if the specified event is static; otherwise, <c>false</c>.</returns>
// Token: 0x0600015A RID: 346 RVA: 0x0000BC84 File Offset: 0x00009E84
public static bool IsStatic(this EventDef evt)
{
if (evt.AddMethod != null && evt.AddMethod.IsStatic)
{
return true;
}
if (evt.RemoveMethod != null && evt.RemoveMethod.IsStatic)
{
return true;
}
if (evt.InvokeMethod != null && evt.InvokeMethod.IsStatic)
{
return true;
}
return evt.OtherMethods.Any((MethodDef method) => method.IsStatic);
}
/// <summary>
/// Replaces the specified instruction reference with another instruction.
/// </summary>
/// <param name="body">The method body.</param>
/// <param name="target">The instruction to replace.</param>
/// <param name="newInstr">The new instruction.</param>
// Token: 0x0600015B RID: 347 RVA: 0x0000BD00 File Offset: 0x00009F00
public static void ReplaceReference(this CilBody body, Instruction target, Instruction newInstr)
{
foreach (ExceptionHandler eh in body.ExceptionHandlers)
{
if (eh.TryStart == target)
{
eh.TryStart = newInstr;
}
if (eh.TryEnd == target)
{
eh.TryEnd = newInstr;
}
if (eh.HandlerStart == target)
{
eh.HandlerStart = newInstr;
}
if (eh.HandlerEnd == target)
{
eh.HandlerEnd = newInstr;
}
}
foreach (Instruction instr in body.Instructions)
{
if (instr.Operand == target)
{
instr.Operand = newInstr;
}
else if (instr.Operand is Instruction[])
{
Instruction[] targets = (Instruction[])instr.Operand;
for (int i = 0; i < targets.Length; i++)
{
if (targets[i] == target)
{
targets[i] = newInstr;
}
}
}
}
}
/// <summary>
/// Inserts Instructions
/// </summary>
/// <param name="instructions">list of instructions</param>
/// <param name="keyValuePairs">Instruction:Index</param>
public static void InsertInstructions(IList<Instruction> instructions, Dictionary<Instruction, int> keyValuePairs)
{
foreach (var kv in keyValuePairs)
{
Instruction instruction = kv.Key;
int index = kv.Value;
instructions.Insert(index, instruction);
}
}
/// <summary>
/// Determines whether the specified method is array accessors.
/// </summary>
/// <param name="method">The method.</param>
/// <returns><c>true</c> if the specified method is array accessors; otherwise, <c>false</c>.</returns>
// Token: 0x0600015C RID: 348 RVA: 0x0000BE08 File Offset: 0x0000A008
public static bool IsArrayAccessors(this IMethod method)
{
TypeSig declType = method.DeclaringType.ToTypeSig();
if (declType is GenericInstSig)
{
declType = ((GenericInstSig)declType).GenericType;
}
return declType.IsArray && (method.Name == "Get" || method.Name == "Set" || method.Name == "Address");
}
}
}
| 31.253937 | 174 | 0.654658 | [
"MIT"
] | BedTheGod/ConfuserEx-Mod-By-Bed | Confuser.Core/DnlibUtils.cs | 15,879 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
namespace AdventureWorks.Core.Domain.Entities
{
[Table("SpecialOffer", Schema = "Sales")]
public partial class SpecialOffer
{
#region Members
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SpecialOfferId { get; set; }
public string Category { get; set; }
public string Description { get; set; }
public decimal DiscountPct { get; set; }
public DateTime EndDate { get; set; }
public int? MaxQty { get; set; }
public int MinQty { get; set; }
public DateTime ModifiedDate { get; set; }
public Guid Rowguid { get; set; }
public DateTime StartDate { get; set; }
public string Type { get; set; }
#endregion Members
#region Equals/GetHashCode
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
SpecialOffer other = obj as SpecialOffer;
if (other == null) return false;
if (Category != other.Category)
return false;
if (Description != other.Description)
return false;
if (DiscountPct != other.DiscountPct)
return false;
if (EndDate != other.EndDate)
return false;
if (MaxQty != other.MaxQty)
return false;
if (MinQty != other.MinQty)
return false;
if (ModifiedDate != other.ModifiedDate)
return false;
if (Rowguid != other.Rowguid)
return false;
if (StartDate != other.StartDate)
return false;
if (Type != other.Type)
return false;
return true;
}
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = hash * 23 + (Category == null ? 0 : Category.GetHashCode());
hash = hash * 23 + (Description == null ? 0 : Description.GetHashCode());
hash = hash * 23 + (DiscountPct == default(decimal) ? 0 : DiscountPct.GetHashCode());
hash = hash * 23 + (EndDate == default(DateTime) ? 0 : EndDate.GetHashCode());
hash = hash * 23 + (MaxQty == null ? 0 : MaxQty.GetHashCode());
hash = hash * 23 + (MinQty == default(int) ? 0 : MinQty.GetHashCode());
hash = hash * 23 + (ModifiedDate == default(DateTime) ? 0 : ModifiedDate.GetHashCode());
hash = hash * 23 + (Rowguid == default(Guid) ? 0 : Rowguid.GetHashCode());
hash = hash * 23 + (StartDate == default(DateTime) ? 0 : StartDate.GetHashCode());
hash = hash * 23 + (Type == null ? 0 : Type.GetHashCode());
return hash;
}
}
public static bool operator ==(SpecialOffer left, SpecialOffer right)
{
return Equals(left, right);
}
public static bool operator !=(SpecialOffer left, SpecialOffer right)
{
return !Equals(left, right);
}
#endregion Equals/GetHashCode
}
}
| 37.892157 | 104 | 0.51436 | [
"MIT"
] | Drizin/Harbin | src/AdventureWorks.Core.Domain/Entities/SpecialOffer.generated.cs | 3,867 | C# |
using Sharpen;
namespace android.os.storage
{
[Sharpen.Stub]
public interface IMountShutdownObserver : android.os.IInterface
{
[Sharpen.Stub]
void onShutDownComplete(int statusCode);
}
[Sharpen.Stub]
public static class IMountShutdownObserverClass
{
[Sharpen.Stub]
public abstract class Stub : android.os.Binder, android.os.storage.IMountShutdownObserver
{
[Sharpen.Stub]
public Stub()
{
throw new System.NotImplementedException();
}
[Sharpen.Stub]
public static android.os.storage.IMountShutdownObserver asInterface(android.os.IBinder
obj)
{
throw new System.NotImplementedException();
}
[Sharpen.Stub]
[Sharpen.ImplementsInterface(@"android.os.IInterface")]
public virtual android.os.IBinder asBinder()
{
throw new System.NotImplementedException();
}
[Sharpen.Stub]
[Sharpen.OverridesMethod(@"android.os.Binder")]
protected internal override bool onTransact(int code, android.os.Parcel data, android.os.Parcel
reply, int flags)
{
throw new System.NotImplementedException();
}
public abstract void onShutDownComplete(int arg1);
}
}
}
| 22.88 | 98 | 0.72465 | [
"Apache-2.0"
] | Conceptengineai/XobotOS | android/generated/android/os/storage/IMountShutdownObserver.cs | 1,144 | C# |
using SFML.System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CincCamins
{
public partial class MainForm
{
public void GenerateFromGameStatus(GameStatus game)
{
_pawns.Clear();
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
var pawn = game.Pawns[i, j];
if (pawn != null)
{
_pawns.Add(new Pawn(pawn.Number, pawn.Player)
{
X = i,
Y = j,
Position = new Vector2f(i * 100f, j * 100f),
});
}
}
}
}
public GameStatus GenerateGameStatus()
{
return new GameStatus(this._pawns);
}
}
}
| 25.076923 | 72 | 0.402863 | [
"MIT"
] | MaciejZ95/CincCamins | MainFormGameInterface.cs | 980 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StructuremapWebApi.cs" company="Web Advanced">
// Copyright 2012 Web Advanced (www.webadvanced.com)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.Web.Http;
using CleanArchitecture.Service;
using CleanArchitecture.Service.DependencyResolution;
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(StructuremapWebApi), "Start")]
namespace CleanArchitecture.Service {
public static class StructuremapWebApi {
public static void Start() {
var container = StructuremapMvc.StructureMapDependencyScope.Container;
GlobalConfiguration.Configuration.DependencyResolver = new StructureMapWebApiDependencyResolver(container);
}
}
} | 47.096774 | 119 | 0.643836 | [
"BSD-3-Clause"
] | Marley365/clean-architecture-demo | Service/App_Start/StructuremapWebApi.cs | 1,460 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by \generate-code.bat.
//
// Changes to this file will be lost when the code is regenerated.
// The build server regenerates the code before each build and a pre-build
// step will regenerate the code on each local build.
//
// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units.
//
// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities.
// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities.
//
// </auto-generated>
//------------------------------------------------------------------------------
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.
using System.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("CUnitsNet")]
[assembly: AssemblyDescription("Get all the common units of measurement and the conversions between them. It is light-weight and thoroughly tested.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Andreas Gullberg Larsen")]
[assembly: AssemblyProduct("nanoFramework UnitsNet")]
[assembly: AssemblyCopyright("Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com).")]
[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)]
// 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("4.101.0")]
[assembly: AssemblyFileVersion("4.101.0")]
//////////////////////////////////////////////////
// This assembly doens't require native support //
[assembly: AssemblyNativeVersion("0.0.0.0")]
//////////////////////////////////////////////////
| 45.280702 | 150 | 0.676482 | [
"MIT-feh"
] | akaegi/UnitsNet | UnitsNet.NanoFramework/GeneratedCode/Properties/AssemblyInfo.cs | 2,581 | C# |
using System.Collections.Generic;
namespace WebApplicationExample.Models
{
public static class Db
{
public static List<Client> Clients { get; }= new List<Client>{
new Client{Id=1, Name="Jim", EmployeeId=1},
new Client{Id=2, Name="John", EmployeeId=2},
new Client{Id=3, Name="Kate", EmployeeId=3}
};
public static List<Employee> Employees { get; }= new List<Employee>{
new Employee{Id=1, Name="Jane"},
new Employee{Id=2, Name="Rick"}
};
}
}
| 27.909091 | 77 | 0.514658 | [
"MIT"
] | dimitris-papadimitriou-chr/Practical-Functional-CSharp | WebApplicationExample/Models/Db.cs | 616 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
namespace BingoX.Helper
{
public static class ListBindingHelper
{
public static PropertyDescriptorCollection GetListItemProperties(Type type)
{
return TypeDescriptor.GetProperties(GetListItemType(type));
}
public static Type GetListItemType(object list)
{
if (list == null)
{
return null;
}
Type itemType = null;
// special case for IListSource
if ((list is Type) && (typeof(IListSource).IsAssignableFrom(list as Type)))
{
list = CreateBindingList(list as Type);
}
list = GetList(list);
Type listType = (list is Type) ? (list as Type) : list.GetType();
object listInstance = (list is Type) ? null : list;
if (typeof(Array).IsAssignableFrom(listType))
{
itemType = listType.GetElementType();
}
else
{
PropertyInfo indexer = GetTypedIndexer(listType);
if (indexer != null)
{
itemType = indexer.PropertyType;
}
else if (listInstance is IEnumerable)
{
itemType = GetFirstType(listInstance as IEnumerable);
}
else
{
itemType = listType;
}
}
return itemType;
}
public static Type GetFirstType(this IEnumerable iEnumerable)
{
object instance = GetFirst(iEnumerable);
return (instance != null) ? instance.GetType() : typeof(object);
}
public static object GetFirst(this IEnumerable enumerable)
{
object instance = null;
if (enumerable is IList list)
{
instance = (list.Count > 0) ? list[0] : null;
}
else
{
try
{
IEnumerator listEnumerator = enumerable.GetEnumerator();
listEnumerator.Reset();
if (listEnumerator.MoveNext())
instance = listEnumerator.Current;
listEnumerator.Reset();
}
catch (NotSupportedException)
{
instance = null;
}
}
return instance;
}
private static bool IsListBasedType(Type type)
{
// check for IList, ITypedList, IListSource
if (typeof(IList).IsAssignableFrom(type) ||
typeof(ITypedList).IsAssignableFrom(type) ||
typeof(IListSource).IsAssignableFrom(type))
{
return true;
}
// check for IList<>:
if (type.IsGenericType && !type.IsGenericTypeDefinition)
{
if (typeof(IList<>).IsAssignableFrom(type.GetGenericTypeDefinition()))
{
return true;
}
}
// check for SomeObject<T> : IList<T> / SomeObject : IList<(SpecificListObjectType)>
foreach (Type curInterface in type.GetInterfaces())
{
if (curInterface.IsGenericType)
{
if (typeof(IList<>).IsAssignableFrom(curInterface.GetGenericTypeDefinition()))
{
return true;
}
}
}
return false;
}
private static PropertyInfo GetTypedIndexer(Type type)
{
PropertyInfo indexer = null;
if (!IsListBasedType(type))
{
return null;
}
System.Reflection.PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
for (int idx = 0; idx < props.Length; idx++)
{
if (props[idx].GetIndexParameters().Length > 0 && props[idx].PropertyType != typeof(object))
{
indexer = props[idx];
//Prefer the standard indexer, if there is one
if (indexer.Name == "Item")
{
break;
}
}
}
return indexer;
}
public static object GetList(object list)
{
if (list is IListSource listSource)
{
return listSource.GetList();
}
else
{
return list;
}
}
public static PropertyDescriptorCollection GetListItemProperties(object list)
{
PropertyDescriptorCollection pdc;
if (list == null)
{
return new PropertyDescriptorCollection(null);
}
else if (list is Type)
{
pdc = GetListItemProperties(list as Type);
}
else
{
object target = GetList(list);
if (target is ITypedList)
{
pdc = (target as ITypedList).GetItemProperties(null);
}
else if (target is IEnumerable)
{
pdc = GetListItemProperties(target as IEnumerable);
}
else
{
pdc = TypeDescriptor.GetProperties(target);
}
}
return pdc;
}
public static PropertyDescriptorCollection GetListItemProperties(this IEnumerable enumerable)
{
PropertyDescriptorCollection pdc = null;
Type targetType = enumerable.GetType();
if (typeof(Array).IsAssignableFrom(targetType))
{
pdc = TypeDescriptor.GetProperties(targetType.GetElementType());
}
else
{
ITypedList typedListEnumerable = enumerable as ITypedList;
if (typedListEnumerable != null)
{
pdc = typedListEnumerable.GetItemProperties(null);
}
else
{
PropertyInfo indexer = GetTypedIndexer(targetType);
if (indexer != null && !typeof(ICustomTypeDescriptor).IsAssignableFrom(indexer.PropertyType))
{
Type type = indexer.PropertyType;
pdc = TypeDescriptor.GetProperties(type);
}
}
}
// See if we were successful - if not, return the shape of the first
// item in the list
if (null == pdc)
{
object instance = GetFirst(enumerable);
if (enumerable is string)
{
pdc = TypeDescriptor.GetProperties(enumerable);
}
else if (instance == null)
{
pdc = new PropertyDescriptorCollection(null);
}
else
{
pdc = TypeDescriptor.GetProperties(instance);
if (!(enumerable is IList) && (pdc == null || pdc.Count == 0))
{
pdc = TypeDescriptor.GetProperties(enumerable);
}
}
}
// Return results
return pdc;
}
private static IList CreateBindingList(Type type)
{
Type genericType = typeof(BindingList<>);
Type bindingType = genericType.MakeGenericType(new Type[] { type });
return Activator.CreateInstance(bindingType) as IList;
}
}
}
| 29.933824 | 117 | 0.467453 | [
"Apache-2.0"
] | BingoRoom/BingoX | src/BingoX/BingoX.Core/Helper/ListBindingHelper.cs | 8,144 | C# |
namespace CloudNativeKit.Infrastructure.Tracing.Jaeger
{
public class JaegerOptions
{
public bool Enabled { get; set; }
public string ServiceName { get; set; }
public string UdpHost { get; set; }
public int UdpPort { get; set; }
public int MaxPacketSize { get; set; }
public string Sampler { get; set; }
public double MaxTracesPerSecond { get; set; } = 5;
public double SamplingRate { get; set; } = 0.2;
}
}
| 32.266667 | 59 | 0.609504 | [
"MIT"
] | HardikKSavaliya/coolstore-microservices | src/building-blocks/CloudNativeKit.Infrastructure.Tracing/Jaeger/JaegerOptions.cs | 484 | C# |
// Url:https://leetcode.com/problems/sales-analysis-i
/*
1082. Sales Analysis I
Easy
// {{ MISSING QUESTION }}
*/
using System;
namespace InterviewPreperationGuide.Core.LeetCode.Solution1082
{
// {{ MISSING CODE }}
}
| 14.0625 | 62 | 0.702222 | [
"MIT"
] | tarunbatta/leetcodeScraper | problems/cs/1082.cs | 225 | C# |
namespace Vehicles.Models
{
public class Truck : Vehicle
{
private const double ADDITIONAL_CONSUMPTION_PER_KM = 1.6;
private const double REFUEL_EFFICIENCY_PERCENTAGE = 0.95;
public Truck(double fuelQuantity, double fuelConsumption)
: base(fuelQuantity, fuelConsumption)
{
}
protected override double AdditionalConsumption => ADDITIONAL_CONSUMPTION_PER_KM;
public override void Refuel(double fuel)
{
base.Refuel(fuel * REFUEL_EFFICIENCY_PERCENTAGE);
}
}
}
| 25.909091 | 89 | 0.65614 | [
"MIT"
] | A-Manev/SoftUni-CSharp-Advanced-january-2020 | CSharp OOP/Polymorphism - Exercise/01. Vehicles/Models/Truck.cs | 572 | C# |
using System;
using System.Windows;
namespace Amoeba.Interface
{
/// <summary>
/// RelationWindow.xaml の相互作用ロジック
/// </summary>
partial class RelationWindow : Window
{
public RelationWindow(RelationWindowViewModel viewModel)
{
this.DataContext = viewModel;
viewModel.CloseEvent += (sender, e) => this.Close();
InitializeComponent();
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
if (this.DataContext is IDisposable disposable)
{
disposable.Dispose();
}
}
}
}
| 21.9 | 64 | 0.555556 | [
"MIT"
] | Joeyawesome/Amoeba | Amoeba.Interface/Wpf/Sources/Mvvm/Windows/Relation/RelationWindow.xaml.cs | 675 | C# |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
namespace HotChocolate.Types.Sorting
{
public static class SortExpressionBuilder
{
private static readonly ConstantExpression _null =
Expression.Constant(null, typeof(object));
public static Expression IsNull(Expression expression)
{
return Expression.Equal(expression, _null);
}
public static Expression IfNullThenDefault(
Expression left,
Expression right,
DefaultExpression defaultExpression)
{
return Expression.Condition(IsNull(left), defaultExpression, right);
}
}
}
| 26.444444 | 80 | 0.662465 | [
"MIT"
] | Coldplayer1995/GraphQLTest | src/Core/Types.Sorting/Expressions/SortExpressionBuilder.cs | 714 | C# |
#if UNITY_EDITOR
namespace CodeStage.AdvancedFPSCounter.Editor
{
using UI;
using Labels;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(AFPSCounter))]
internal class AFPSCounterEditor: Editor
{
private AFPSCounter me;
private SerializedProperty operationMode;
private SerializedProperty fps;
private SerializedProperty fpsEnabled;
private SerializedProperty fpsAnchor;
private SerializedProperty fpsInterval;
private SerializedProperty realtimeFPSFoldout;
private SerializedProperty fpsRealtime;
private SerializedProperty fpsMilliseconds;
private SerializedProperty averageFoldout;
private SerializedProperty fpsAverage;
private SerializedProperty fpsAverageMilliseconds;
private SerializedProperty fpsAverageNewLine;
private SerializedProperty fpsAverageSamples;
private SerializedProperty fpsResetAverageOnNewScene;
private SerializedProperty minMaxFoldout;
private SerializedProperty fpsMinMax;
private SerializedProperty fpsMinMaxMilliseconds;
private SerializedProperty fpsMinMaxNewLine;
private SerializedProperty fpsMinMaxTwoLines;
private SerializedProperty fpsResetMinMaxOnNewScene;
private SerializedProperty fpsMinMaxIntervalsToSkip;
private SerializedProperty renderFoldout;
private SerializedProperty fpsRender;
private SerializedProperty fpsRenderNewLine;
private SerializedProperty fpsRenderAutoAdd;
private SerializedProperty fpsWarningLevelValue;
private SerializedProperty fpsCriticalLevelValue;
private SerializedProperty fpsColor;
private SerializedProperty fpsColorWarning;
private SerializedProperty fpsColorCritical;
private SerializedProperty fpsColorRender;
private SerializedProperty fpsStyle;
private SerializedProperty memory;
private SerializedProperty memoryEnabled;
private SerializedProperty memoryAnchor;
private SerializedProperty memoryColor;
private SerializedProperty memoryStyle;
private SerializedProperty memoryInterval;
private SerializedProperty memoryPrecise;
private SerializedProperty memoryTotal;
private SerializedProperty memoryAllocated;
private SerializedProperty memoryMonoUsage;
private SerializedProperty memoryGfx;
private SerializedProperty device;
private SerializedProperty deviceEnabled;
private SerializedProperty deviceAnchor;
private SerializedProperty deviceColor;
private SerializedProperty deviceStyle;
private SerializedProperty deviceCpuModel;
private SerializedProperty deviceCpuModelNewLine;
private SerializedProperty devicePlatform;
private SerializedProperty deviceGpuModel;
private SerializedProperty deviceGpuModelNewLine;
private SerializedProperty deviceGpuApi;
private SerializedProperty deviceGpuApiNewLine;
private SerializedProperty deviceGpuSpec;
private SerializedProperty deviceGpuSpecNewLine;
private SerializedProperty deviceRamSize;
private SerializedProperty deviceRamSizeNewLine;
private SerializedProperty deviceScreenData;
private SerializedProperty deviceScreenDataNewLine;
private SerializedProperty deviceModel;
private SerializedProperty deviceModelNewLine;
private SerializedProperty lookAndFeelFoldout;
private SerializedProperty autoScale;
private SerializedProperty scaleFactor;
private SerializedProperty labelsFont;
private SerializedProperty fontSize;
private SerializedProperty lineSpacing;
private SerializedProperty countersSpacing;
private SerializedProperty paddingOffset;
private SerializedProperty pixelPerfect;
private SerializedProperty background;
private SerializedProperty backgroundColor;
private SerializedProperty backgroundPadding;
private SerializedProperty shadow;
private SerializedProperty shadowColor;
private SerializedProperty shadowDistance;
private SerializedProperty outline;
private SerializedProperty outlineColor;
private SerializedProperty outlineDistance;
private SerializedProperty advancedFoldout;
private SerializedProperty sortingOrder;
private SerializedProperty hotKey;
private SerializedProperty hotKeyCtrl;
private SerializedProperty hotKeyShift;
private SerializedProperty hotKeyAlt;
private SerializedProperty circleGesture;
private SerializedProperty keepAlive;
private SerializedProperty forceFrameRate;
private SerializedProperty forcedFrameRate;
private LabelAnchor groupAnchor = LabelAnchor.UpperLeft;
public void OnEnable()
{
me = target as AFPSCounter;
operationMode = serializedObject.FindProperty("operationMode");
hotKey = serializedObject.FindProperty("hotKey");
hotKeyCtrl = serializedObject.FindProperty("hotKeyCtrl");
hotKeyShift = serializedObject.FindProperty("hotKeyShift");
hotKeyAlt = serializedObject.FindProperty("hotKeyAlt");
circleGesture = serializedObject.FindProperty("circleGesture");
keepAlive = serializedObject.FindProperty("keepAlive");
forceFrameRate = serializedObject.FindProperty("forceFrameRate");
forcedFrameRate = serializedObject.FindProperty("forcedFrameRate");
lookAndFeelFoldout = serializedObject.FindProperty("lookAndFeelFoldout");
autoScale = serializedObject.FindProperty("autoScale");
scaleFactor = serializedObject.FindProperty("scaleFactor");
labelsFont = serializedObject.FindProperty("labelsFont");
fontSize = serializedObject.FindProperty("fontSize");
lineSpacing = serializedObject.FindProperty("lineSpacing");
countersSpacing = serializedObject.FindProperty("countersSpacing");
paddingOffset = serializedObject.FindProperty("paddingOffset");
pixelPerfect = serializedObject.FindProperty("pixelPerfect");
background = serializedObject.FindProperty("background");
backgroundColor = serializedObject.FindProperty("backgroundColor");
backgroundPadding = serializedObject.FindProperty("backgroundPadding");
shadow = serializedObject.FindProperty("shadow");
shadowColor = serializedObject.FindProperty("shadowColor");
shadowDistance = serializedObject.FindProperty("shadowDistance");
outline = serializedObject.FindProperty("outline");
outlineColor = serializedObject.FindProperty("outlineColor");
outlineDistance = serializedObject.FindProperty("outlineDistance");
advancedFoldout = serializedObject.FindProperty("advancedFoldout");
sortingOrder = serializedObject.FindProperty("sortingOrder");
fps = serializedObject.FindProperty("fpsCounter");
fpsEnabled = fps.FindPropertyRelative("enabled");
fpsInterval = fps.FindPropertyRelative("updateInterval");
fpsAnchor = fps.FindPropertyRelative("anchor");
realtimeFPSFoldout = fps.FindPropertyRelative("realtimeFPSFoldout");
fpsRealtime = fps.FindPropertyRelative("realtimeFPS");
fpsMilliseconds = fps.FindPropertyRelative("milliseconds");
averageFoldout = fps.FindPropertyRelative("averageFoldout");
fpsAverage = fps.FindPropertyRelative("average");
fpsAverageMilliseconds = fps.FindPropertyRelative("averageMilliseconds");
fpsAverageNewLine = fps.FindPropertyRelative("averageNewLine");
fpsAverageSamples = fps.FindPropertyRelative("averageSamples");
fpsResetAverageOnNewScene = fps.FindPropertyRelative("resetAverageOnNewScene");
minMaxFoldout = fps.FindPropertyRelative("minMaxFoldout");
fpsMinMax = fps.FindPropertyRelative("minMax");
fpsMinMaxMilliseconds = fps.FindPropertyRelative("minMaxMilliseconds");
fpsMinMaxNewLine = fps.FindPropertyRelative("minMaxNewLine");
fpsMinMaxTwoLines = fps.FindPropertyRelative("minMaxTwoLines");
fpsResetMinMaxOnNewScene = fps.FindPropertyRelative("resetMinMaxOnNewScene");
fpsMinMaxIntervalsToSkip = fps.FindPropertyRelative("minMaxIntervalsToSkip");
renderFoldout = fps.FindPropertyRelative("renderFoldout");
fpsRender = fps.FindPropertyRelative("render");
fpsRenderNewLine = fps.FindPropertyRelative("renderNewLine");
fpsRenderAutoAdd = fps.FindPropertyRelative("renderAutoAdd");
fpsWarningLevelValue = fps.FindPropertyRelative("warningLevelValue");
fpsCriticalLevelValue = fps.FindPropertyRelative("criticalLevelValue");
fpsColor = fps.FindPropertyRelative("color");
fpsColorWarning = fps.FindPropertyRelative("colorWarning");
fpsColorCritical = fps.FindPropertyRelative("colorCritical");
fpsColorRender = fps.FindPropertyRelative("colorRender");
fpsStyle = fps.FindPropertyRelative("style");
memory = serializedObject.FindProperty("memoryCounter");
memoryEnabled = memory.FindPropertyRelative("enabled");
memoryInterval = memory.FindPropertyRelative("updateInterval");
memoryAnchor = memory.FindPropertyRelative("anchor");
memoryPrecise = memory.FindPropertyRelative("precise");
memoryColor = memory.FindPropertyRelative("color");
memoryStyle = memory.FindPropertyRelative("style");
memoryTotal = memory.FindPropertyRelative("total");
memoryAllocated = memory.FindPropertyRelative("allocated");
memoryMonoUsage = memory.FindPropertyRelative("monoUsage");
memoryGfx = memory.FindPropertyRelative("gfx");
device = serializedObject.FindProperty("deviceInfoCounter");
deviceEnabled = device.FindPropertyRelative("enabled");
deviceAnchor = device.FindPropertyRelative("anchor");
deviceColor = device.FindPropertyRelative("color");
deviceStyle = device.FindPropertyRelative("style");
devicePlatform = device.FindPropertyRelative("platform");
deviceCpuModel = device.FindPropertyRelative("cpuModel");
deviceCpuModelNewLine = device.FindPropertyRelative("cpuModelNewLine");
deviceGpuModel = device.FindPropertyRelative("gpuModel");
deviceGpuModelNewLine = device.FindPropertyRelative("gpuModelNewLine");
deviceGpuApi = device.FindPropertyRelative("gpuApi");
deviceGpuApiNewLine = device.FindPropertyRelative("gpuApiNewLine");
deviceGpuSpec = device.FindPropertyRelative("gpuSpec");
deviceGpuSpecNewLine = device.FindPropertyRelative("gpuSpecNewLine");
deviceRamSize = device.FindPropertyRelative("ramSize");
deviceRamSizeNewLine = device.FindPropertyRelative("ramSizeNewLine");
deviceScreenData = device.FindPropertyRelative("screenData");
deviceScreenDataNewLine = device.FindPropertyRelative("screenDataNewLine");
deviceModel = device.FindPropertyRelative("deviceModel");
deviceModelNewLine = device.FindPropertyRelative("deviceModelNewLine");
}
public override void OnInspectorGUI()
{
if (me == null) return;
serializedObject.Update();
EditorUIUtils.SetupStyles();
GUILayout.Space(5);
#region Main Settings
EditorGUIUtility.labelWidth = 120;
EditorUIUtils.DrawProperty(operationMode, () => me.OperationMode = (OperationMode)operationMode.enumValueIndex);
EditorGUILayout.PropertyField(hotKey);
EditorGUIUtility.labelWidth = 0;
using (EditorUIUtils.Horizontal())
{
GUILayout.FlexibleSpace();
EditorGUIUtility.labelWidth = 70;
EditorGUILayout.PropertyField(hotKeyCtrl, new GUIContent("Ctrl / Cmd", hotKeyCtrl.tooltip), GUILayout.Width(85));
EditorGUIUtility.labelWidth = 20;
EditorGUILayout.PropertyField(hotKeyAlt, new GUIContent("Alt", hotKeyAlt.tooltip), GUILayout.Width(35));
EditorGUIUtility.labelWidth = 35;
EditorGUILayout.PropertyField(hotKeyShift, new GUIContent("Shift", hotKeyShift.tooltip), GUILayout.Width(50));
EditorGUIUtility.labelWidth = 0;
}
EditorGUIUtility.labelWidth = 120;
EditorGUILayout.PropertyField(circleGesture);
EditorGUILayout.PropertyField(keepAlive);
if (me.transform.parent != null)
{
EditorGUILayout.LabelField("Keep Alive option will keep alive root level object (" + me.transform.root.name + ")!", EditorStyles.wordWrappedMiniLabel);
}
using (EditorUIUtils.Horizontal(GUILayout.ExpandWidth(true)))
{
EditorUIUtils.DrawProperty(forceFrameRate, "Force FPS", () => me.ForceFrameRate = forceFrameRate.boolValue, GUILayout.ExpandWidth(false));
GUILayout.Space(2);
EditorUIUtils.DrawProperty(forcedFrameRate, GUIContent.none, () => me.ForcedFrameRate = forcedFrameRate.intValue);
}
#endregion
#region Look & Feel
EditorGUIUtility.labelWidth = 0;
if (EditorUIUtils.Foldout(lookAndFeelFoldout, "Look & Feel"))
{
EditorGUIUtility.labelWidth = 130;
EditorUIUtils.DrawProperty(autoScale, () => me.AutoScale = autoScale.boolValue);
if (autoScale.boolValue)
{
GUI.enabled = false;
}
EditorUIUtils.DrawProperty(scaleFactor, () => me.ScaleFactor = scaleFactor.floatValue);
GUI.enabled = true;
EditorUIUtils.DrawProperty(labelsFont, () => me.LabelsFont = (Font)labelsFont.objectReferenceValue);
EditorUIUtils.DrawProperty(fontSize, () => me.FontSize = fontSize.intValue);
EditorUIUtils.DrawProperty(lineSpacing, () => me.LineSpacing = lineSpacing.floatValue);
EditorUIUtils.DrawProperty(countersSpacing, () => me.CountersSpacing = countersSpacing.intValue);
EditorUIUtils.DrawProperty(paddingOffset, () => me.PaddingOffset = paddingOffset.vector2Value);
EditorUIUtils.DrawProperty(pixelPerfect, () => me.PixelPerfect = pixelPerfect.boolValue);
EditorUIUtils.Header("Effects");
EditorUIUtils.Separator();
EditorUIUtils.DrawProperty(background, () => me.Background = background.boolValue);
if (background.boolValue)
{
EditorUIUtils.Indent();
EditorUIUtils.DrawProperty(backgroundColor, "Color", () => me.BackgroundColor = backgroundColor.colorValue);
EditorUIUtils.DrawProperty(backgroundPadding, "Padding", () => me.BackgroundPadding = backgroundPadding.intValue);
EditorUIUtils.UnIndent();
}
EditorUIUtils.DrawProperty(shadow, () => me.Shadow = shadow.boolValue);
if (shadow.boolValue)
{
EditorUIUtils.Indent();
EditorUIUtils.DrawProperty(shadowColor, "Color", () => me.ShadowColor = shadowColor.colorValue);
EditorUIUtils.DrawProperty(shadowDistance, "Distance", () => me.ShadowDistance = shadowDistance.vector2Value);
EditorGUILayout.LabelField(new GUIContent("<b>This effect is resource-heavy</b>", "Such effect increases resources usage on each text refresh."), EditorUIUtils.richMiniLabel);
EditorUIUtils.UnIndent();
}
EditorUIUtils.DrawProperty(outline, () => me.Outline = outline.boolValue);
if (outline.boolValue)
{
EditorUIUtils.Indent();
EditorUIUtils.DrawProperty(outlineColor, "Color", () => me.OutlineColor = outlineColor.colorValue);
EditorUIUtils.DrawProperty(outlineDistance, "Distance", () => me.OutlineDistance = outlineDistance.vector2Value);
EditorGUILayout.LabelField(new GUIContent("<b>This effect is <color=#FF4040ff>very</color> resource-heavy!</b>", "Such effect significantly increases resources usage on each text refresh. Use only if really necessary."), EditorUIUtils.richMiniLabel);
EditorUIUtils.UnIndent();
}
EditorUIUtils.Header("Service Commands");
using (EditorUIUtils.Horizontal())
{
groupAnchor = (LabelAnchor)EditorGUILayout.EnumPopup(
new GUIContent("Move All To", "Use to explicitly move all counters to the specified anchor label.\n" +
"Select anchor and press Apply."), groupAnchor);
if (GUILayout.Button(new GUIContent("Apply", "Press to move all counters to the selected anchor label."),
GUILayout.Width(45)))
{
Undo.RegisterCompleteObjectUndo(target, "Move all counters to anchor");
me.fpsCounter.Anchor = groupAnchor;
fpsAnchor.enumValueIndex = (int)groupAnchor;
me.memoryCounter.Anchor = groupAnchor;
memoryAnchor.enumValueIndex = (int)groupAnchor;
me.deviceInfoCounter.Anchor = groupAnchor;
deviceAnchor.enumValueIndex = (int)groupAnchor;
}
}
EditorGUIUtility.labelWidth = 0;
}
#endregion
#region Advanced Settings
if (EditorUIUtils.Foldout(advancedFoldout, "Advanced Settings"))
{
EditorGUIUtility.labelWidth = 120;
EditorUIUtils.DrawProperty(sortingOrder, () => me.SortingOrder = sortingOrder.intValue);
EditorGUIUtility.labelWidth = 0;
}
#endregion
#region FPS Counter
GUI.enabled = EditorUIUtils.ToggleFoldout(fpsEnabled, fps, "FPS Counter");
me.fpsCounter.Enabled = fpsEnabled.boolValue;
if (fps.isExpanded)
{
GUILayout.Space(5);
EditorGUIUtility.labelWidth = 100;
EditorUIUtils.DrawProperty(fpsInterval, "Interval", () => me.fpsCounter.UpdateInterval = fpsInterval.floatValue);
EditorUIUtils.DrawProperty(fpsAnchor, () => me.fpsCounter.Anchor = (LabelAnchor)fpsAnchor.enumValueIndex);
GUILayout.Space(5);
float minVal = fpsCriticalLevelValue.intValue;
float maxVal = fpsWarningLevelValue.intValue;
EditorGUILayout.MinMaxSlider(new GUIContent("Colors Range",
"This range will be used to apply colors below on specific FPS:\n" +
"Critical: 0 - min\n" +
"Warning: min+1 - max-1\n" +
"Normal: max+"),
ref minVal, ref maxVal, 1, 60);
fpsCriticalLevelValue.intValue = (int)minVal;
fpsWarningLevelValue.intValue = (int)maxVal;
using (EditorUIUtils.Horizontal())
{
EditorUIUtils.DrawProperty(fpsColor, "Normal", () => me.fpsCounter.Color = fpsColor.colorValue);
GUILayout.Label(maxVal + "+ FPS", GUILayout.Width(75));
}
using (EditorUIUtils.Horizontal())
{
EditorUIUtils.DrawProperty(fpsColorWarning, "Warning", () => me.fpsCounter.ColorWarning = fpsColorWarning.colorValue);
GUILayout.Label(minVal + 1 + " - " + (maxVal - 1) + " FPS", GUILayout.Width(75));
}
using (EditorUIUtils.Horizontal())
{
EditorUIUtils.DrawProperty(fpsColorCritical, "Critical", () => me.fpsCounter.ColorCritical = fpsColorCritical.colorValue);
GUILayout.Label("0 - " + minVal + " FPS", GUILayout.Width(75));
}
GUILayout.Space(5);
EditorUIUtils.DrawProperty(fpsStyle, () => me.fpsCounter.Style = (FontStyle)fpsStyle.enumValueIndex);
EditorUIUtils.Separator(5);
EditorGUIUtility.labelWidth = 120;
GUI.enabled = EditorUIUtils.ToggleFoldout(fpsRealtime, realtimeFPSFoldout, "Realtime FPS", false, false, false);
me.fpsCounter.RealtimeFPS = fpsRealtime.boolValue;
if (realtimeFPSFoldout.isExpanded)
{
EditorUIUtils.DoubleIndent();
EditorUIUtils.DrawProperty(fpsMilliseconds, () => me.fpsCounter.Milliseconds = fpsMilliseconds.boolValue);
EditorUIUtils.DoubleUnIndent();
}
GUI.enabled = true;
GUI.enabled = EditorUIUtils.ToggleFoldout(fpsAverage, averageFoldout, "Average FPS", false, false, false);
me.fpsCounter.Average = fpsAverage.boolValue;
if (averageFoldout.isExpanded)
{
EditorUIUtils.DoubleIndent();
EditorUIUtils.DrawProperty(fpsAverageSamples, "Samples", () => me.fpsCounter.AverageSamples = fpsAverageSamples.intValue);
EditorUIUtils.DrawProperty(fpsAverageMilliseconds, "Milliseconds", () => me.fpsCounter.AverageMilliseconds = fpsAverageMilliseconds.boolValue);
EditorUIUtils.DrawProperty(fpsAverageNewLine, "New Line", () => me.fpsCounter.AverageNewLine = fpsAverageNewLine.boolValue);
using (EditorUIUtils.Horizontal())
{
EditorGUILayout.PropertyField(fpsResetAverageOnNewScene, new GUIContent("Auto Reset"), GUILayout.ExpandWidth(false));
if (GUILayout.Button("Reset", /*GUILayout.MaxWidth(200),*/ GUILayout.MinWidth(40)))
{
me.fpsCounter.ResetAverage();
}
}
EditorUIUtils.DoubleUnIndent();
}
GUI.enabled = true;
GUI.enabled = EditorUIUtils.ToggleFoldout(fpsMinMax, minMaxFoldout, "MinMax FPS", false, false, false);
me.fpsCounter.MinMax = fpsMinMax.boolValue;
if (minMaxFoldout.isExpanded)
{
EditorUIUtils.DoubleIndent();
EditorGUILayout.PropertyField(fpsMinMaxIntervalsToSkip, new GUIContent("Delay"));
EditorUIUtils.DrawProperty(fpsMinMaxMilliseconds, "Milliseconds", () => me.fpsCounter.MinMaxMilliseconds = fpsMinMaxMilliseconds.boolValue);
EditorUIUtils.DrawProperty(fpsMinMaxNewLine, "New Line", () => me.fpsCounter.MinMaxNewLine = fpsMinMaxNewLine.boolValue);
EditorUIUtils.DrawProperty(fpsMinMaxTwoLines, "Two Lines", () => me.fpsCounter.MinMaxTwoLines = fpsMinMaxTwoLines.boolValue);
using (EditorUIUtils.Horizontal())
{
EditorGUILayout.PropertyField(fpsResetMinMaxOnNewScene, new GUIContent("Auto Reset"), GUILayout.ExpandWidth(false));
if (GUILayout.Button("Reset", /*GUILayout.MaxWidth(200),*/ GUILayout.MinWidth(40)))
{
me.fpsCounter.ResetMinMax();
}
}
EditorUIUtils.DoubleUnIndent();
}
GUI.enabled = true;
GUI.enabled = EditorUIUtils.ToggleFoldout(fpsRender, renderFoldout, "Render Time", false, false, false);
me.fpsCounter.Render = fpsRender.boolValue;
if (renderFoldout.isExpanded)
{
EditorUIUtils.DoubleIndent();
EditorUIUtils.DrawProperty(fpsColorRender, "Color", () => me.fpsCounter.ColorRender = fpsColorRender.colorValue);
EditorUIUtils.DrawProperty(fpsRenderNewLine, "New Line", () => me.fpsCounter.RenderNewLine = fpsRenderNewLine.boolValue);
EditorUIUtils.DrawProperty(fpsRenderAutoAdd, "Auto add", () => me.fpsCounter.RenderAutoAdd = fpsRenderAutoAdd.boolValue);
EditorUIUtils.DoubleUnIndent();
}
GUI.enabled = true;
EditorGUIUtility.labelWidth = 0;
}
GUI.enabled = true;
#endregion
#region Memory Counter
GUI.enabled = EditorUIUtils.ToggleFoldout(memoryEnabled, memory, "Memory Counter");
me.memoryCounter.Enabled = memoryEnabled.boolValue;
if (memory.isExpanded)
{
GUILayout.Space(5);
EditorGUIUtility.labelWidth = 100;
EditorUIUtils.DrawProperty(memoryInterval, "Interval", () => me.memoryCounter.UpdateInterval = memoryInterval.floatValue);
EditorUIUtils.DrawProperty(memoryAnchor, () => me.memoryCounter.Anchor = (LabelAnchor)memoryAnchor.enumValueIndex);
EditorUIUtils.DrawProperty(memoryColor, () => me.memoryCounter.Color = memoryColor.colorValue);
EditorUIUtils.DrawProperty(memoryStyle, () => me.memoryCounter.Style = (FontStyle)memoryStyle.enumValueIndex);
EditorUIUtils.Separator(5);
EditorUIUtils.DrawProperty(memoryPrecise, () => me.memoryCounter.Precise = memoryPrecise.boolValue);
EditorUIUtils.Separator(5);
EditorUIUtils.DrawProperty(memoryTotal, () => me.memoryCounter.Total = memoryTotal.boolValue);
EditorUIUtils.DrawProperty(memoryAllocated, () => me.memoryCounter.Allocated = memoryAllocated.boolValue);
EditorUIUtils.DrawProperty(memoryMonoUsage, "Mono", () => me.memoryCounter.MonoUsage = memoryMonoUsage.boolValue);
using (EditorUIUtils.Horizontal())
{
EditorUIUtils.DrawProperty(memoryGfx, "GfxDriver", () => me.memoryCounter.Gfx = memoryGfx.boolValue, GUILayout.ExpandWidth(false));
GUILayout.Space(0);
string extraInfo = null;
#if !UNITY_2018_1_OR_NEWER
var color = EditorGUIUtility.isProSkin ? "#FF6060" : "#FF1010";
extraInfo = "<color=\"" + color + "\">Unity 2018.1+ required</color>";
#else
if (!EditorUserBuildSettings.development)
{
extraInfo = "works in <b>Development builds</b> only";
}
#endif
if (!string.IsNullOrEmpty(extraInfo))
{
EditorGUILayout.LabelField(
new GUIContent(extraInfo),
EditorUIUtils.richMiniLabel, GUILayout.ExpandWidth(false));
}
}
EditorGUIUtility.labelWidth = 0;
}
GUI.enabled = true;
#endregion
#region Device Information
var deviceInfoEnabled = EditorUIUtils.ToggleFoldout(deviceEnabled, device, "Device Information");
GUI.enabled = deviceInfoEnabled;
me.deviceInfoCounter.Enabled = deviceEnabled.boolValue;
if (device.isExpanded)
{
GUILayout.Space(5);
EditorGUIUtility.labelWidth = 100;
EditorUIUtils.DrawProperty(deviceAnchor, () => me.deviceInfoCounter.Anchor = (LabelAnchor)deviceAnchor.intValue);
EditorUIUtils.DrawProperty(deviceColor, () => me.deviceInfoCounter.Color = deviceColor.colorValue);
EditorUIUtils.DrawProperty(deviceStyle, () => me.deviceInfoCounter.Style = (FontStyle)deviceStyle.enumValueIndex);
EditorUIUtils.Separator(5);
EditorUIUtils.DrawProperty(devicePlatform, "Platform", () => me.deviceInfoCounter.Platform = devicePlatform.boolValue);
using (EditorUIUtils.Horizontal())
{
EditorUIUtils.DrawProperty(deviceCpuModel, "CPU", () => me.deviceInfoCounter.CpuModel = deviceCpuModel.boolValue, GUILayout.ExpandWidth(false));
GUI.enabled = deviceInfoEnabled && deviceCpuModel.boolValue;
GUILayout.Space(10);
EditorGUIUtility.labelWidth = 60;
EditorUIUtils.DrawProperty(deviceCpuModelNewLine, "New Line", () => me.deviceInfoCounter.CpuModelNewLine = deviceCpuModelNewLine.boolValue);
EditorGUIUtility.labelWidth = 100;
GUI.enabled = deviceInfoEnabled;
}
using (EditorUIUtils.Horizontal())
{
EditorUIUtils.DrawProperty(deviceGpuModel, "GPU Model", () => me.deviceInfoCounter.GpuModel = deviceGpuModel.boolValue, GUILayout.ExpandWidth(false));
GUI.enabled = deviceInfoEnabled && deviceGpuModel.boolValue;
GUILayout.Space(10);
EditorGUIUtility.labelWidth = 60;
EditorUIUtils.DrawProperty(deviceGpuModelNewLine, "New Line", () => me.deviceInfoCounter.GpuModelNewLine = deviceGpuModelNewLine.boolValue);
EditorGUIUtility.labelWidth = 100;
GUI.enabled = deviceInfoEnabled;
}
using (EditorUIUtils.Horizontal())
{
EditorUIUtils.DrawProperty(deviceGpuApi, "GPU API", () => me.deviceInfoCounter.GpuApi = deviceGpuApi.boolValue, GUILayout.ExpandWidth(false));
GUI.enabled = deviceInfoEnabled && deviceGpuApi.boolValue;
GUILayout.Space(10);
EditorGUIUtility.labelWidth = 60;
EditorUIUtils.DrawProperty(deviceGpuApiNewLine, "New Line", () => me.deviceInfoCounter.GpuApiNewLine = deviceGpuApiNewLine.boolValue);
EditorGUIUtility.labelWidth = 100;
GUI.enabled = deviceInfoEnabled;
}
using (EditorUIUtils.Horizontal())
{
EditorUIUtils.DrawProperty(deviceGpuSpec, "GPU Spec", () => me.deviceInfoCounter.GpuSpec = deviceGpuSpec.boolValue, GUILayout.ExpandWidth(false));
GUI.enabled = deviceInfoEnabled && deviceGpuSpec.boolValue;
GUILayout.Space(10);
EditorGUIUtility.labelWidth = 60;
EditorUIUtils.DrawProperty(deviceGpuSpecNewLine, "New Line", () => me.deviceInfoCounter.GpuSpecNewLine = deviceGpuSpecNewLine.boolValue);
EditorGUIUtility.labelWidth = 100;
GUI.enabled = deviceInfoEnabled;
}
using (EditorUIUtils.Horizontal())
{
EditorUIUtils.DrawProperty(deviceRamSize, "RAM", () => me.deviceInfoCounter.RamSize = deviceRamSize.boolValue, GUILayout.ExpandWidth(false));
GUI.enabled = deviceInfoEnabled && deviceRamSize.boolValue;
GUILayout.Space(10);
EditorGUIUtility.labelWidth = 60;
EditorUIUtils.DrawProperty(deviceRamSizeNewLine, "New Line", () => me.deviceInfoCounter.RamSizeNewLine = deviceRamSizeNewLine.boolValue);
EditorGUIUtility.labelWidth = 100;
GUI.enabled = deviceInfoEnabled;
}
using (EditorUIUtils.Horizontal())
{
EditorUIUtils.DrawProperty(deviceScreenData, "Screen", () => me.deviceInfoCounter.ScreenData = deviceScreenData.boolValue, GUILayout.ExpandWidth(false));
GUI.enabled = deviceInfoEnabled && deviceScreenData.boolValue;
GUILayout.Space(10);
EditorGUIUtility.labelWidth = 60;
EditorUIUtils.DrawProperty(deviceScreenDataNewLine, "New Line", () => me.deviceInfoCounter.ScreenDataNewLine = deviceScreenDataNewLine.boolValue);
EditorGUIUtility.labelWidth = 100;
GUI.enabled = deviceInfoEnabled;
}
using (EditorUIUtils.Horizontal())
{
EditorUIUtils.DrawProperty(deviceModel, "Model", () => me.deviceInfoCounter.DeviceModel = deviceModel.boolValue, GUILayout.ExpandWidth(false));
GUI.enabled = deviceInfoEnabled && deviceModel.boolValue;
GUILayout.Space(10);
EditorGUIUtility.labelWidth = 60;
EditorUIUtils.DrawProperty(deviceModelNewLine, "New Line", () => me.deviceInfoCounter.DeviceModelNewLine = deviceModelNewLine.boolValue);
EditorGUIUtility.labelWidth = 100;
GUI.enabled = deviceInfoEnabled;
}
EditorGUIUtility.labelWidth = 0;
}
GUI.enabled = true;
#endregion
EditorGUILayout.Space();
serializedObject.ApplyModifiedProperties();
}
}
}
#endif | 43.06354 | 270 | 0.749306 | [
"MIT"
] | DuLovell/Battle-Simulator | Assets/Plugins/CodeStage/AdvancedFPSCounter/Editor/Scripts/AFPSCounterEditor.cs | 28,467 | C# |
using Xunit;
namespace ReproXunitIssueMakeCollectionAttributeInheritable
{
public class TestsUsingSystemConsoleAttribute //: CollectionAttribute
{
public TestsUsingSystemConsoleAttribute()
//: base("Tests using System.Console")
{
}
}
} | 23.833333 | 73 | 0.681818 | [
"MIT"
] | paulroho/Xunit.ReproIssueMakeCollectionAttributeInheritable | ReproXunitIssueMakeCollectionAttributeInheritable/TestsUsingSystemConsoleAttribute.cs | 288 | C# |
using Shared.Contracts.Services;
using Shared.Domains.Enumerations;
namespace Shared.Contracts.Factories
{
public interface ICacheFactory
{
ICacheService GetCacheService(CacheType cacheServiceType);
}
}
| 20.454545 | 66 | 0.764444 | [
"MIT"
] | RomeshAbeyawardena/Shared | Shared.Contracts/Factories/ICacheFactory.cs | 227 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Domain.Ics.Resources")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[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("06435499-0575-4dd2-ba24-2ad4aeeec3a7")]
| 42.736842 | 85 | 0.757389 | [
"Unlicense"
] | Slesa/Poseidon | old/src/2nd/Domain.Ics.Resources/Properties/AssemblyInfo.cs | 814 | C# |
using System;
using RogueElements;
using RogueEssence;
using RogueEssence.Dungeon;
using RogueEssence.Data;
namespace PMDC.Dungeon
{
[Serializable]
public class AvoidAlliesPlan : AvoidPlan
{
public AvoidAlliesPlan(AIFlags iq) : base(iq) { }
protected AvoidAlliesPlan(AvoidAlliesPlan other) : base(other) { }
public override BasePlan CreateNew() { return new AvoidAlliesPlan(this); }
protected override bool RunFromAllies { get { return true; } }
protected override bool RunFromFoes { get { return false; } }
protected override bool AbortIfCornered { get { return false; } }
}
}
| 28.130435 | 82 | 0.693972 | [
"MIT"
] | PMDCollab/PMDC | PMDC/Dungeon/AI/AvoidAlliesPlan.cs | 649 | C# |
namespace MailRu.Cloud.WebApi
{
/// <summary>
/// Object to response parsing.
/// </summary>
internal enum PObject
{
/// <summary>
/// Authorization token.
/// </summary>
Token = 0,
/// <summary>
/// List of items.
/// </summary>
Entry = 1,
/// <summary>
/// Servers info.
/// </summary>
Shard = 2,
/// <summary>
/// Full body string.
/// </summary>
BodyAsString = 3
}
} | 20.428571 | 40 | 0.38986 | [
"MIT"
] | lsoft/CHD | MailRu.Cloud.WebApi/PObject.cs | 572 | C# |
// EventAttributes.cs
//
// This code was automatically generated from
// ECMA CLI XML Library Specification.
// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)]
// Created: Wed, 5 Sep 2001 06:39:03 UTC
// Source file: all.xml
// URL: http://devresource.hp.com/devresource/Docs/TechPapers/CSharp/all.xml
//
// (C) 2001 Ximian, Inc. http://www.ximian.com
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Runtime.InteropServices;
namespace System.Reflection {
/// <summary>
/// </summary>
#if NET_2_0
[ComVisible (true)]
[Serializable]
#endif
[Flags]
public enum EventAttributes {
/// <summary>
/// </summary>
None = 0,
/// <summary>
/// </summary>
SpecialName = 512,
/// <summary>
/// </summary>
ReservedMask = 1024,
/// <summary>
/// </summary>
RTSpecialName = 1024,
} // EventAttributes
} // System.Reflection
| 29.671642 | 78 | 0.714286 | [
"MIT"
] | zlxy/Genesis-3D | Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/corlib/System.Reflection/EventAttributes.cs | 1,988 | C# |
using Abp.EntityFrameworkCore.Configuration;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Zero.EntityFrameworkCore;
using FirstProject.EntityFrameworkCore.Seed;
namespace FirstProject.EntityFrameworkCore
{
[DependsOn(
typeof(FirstProjectCoreModule),
typeof(AbpZeroCoreEntityFrameworkCoreModule))]
public class FirstProjectEntityFrameworkModule : AbpModule
{
/* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */
public bool SkipDbContextRegistration { get; set; }
public bool SkipDbSeed { get; set; }
public override void PreInitialize()
{
if (!SkipDbContextRegistration)
{
Configuration.Modules.AbpEfCore().AddDbContext<FirstProjectDbContext>(options =>
{
if (options.ExistingConnection != null)
{
FirstProjectDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
}
else
{
FirstProjectDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
}
});
}
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(FirstProjectEntityFrameworkModule).GetAssembly());
}
public override void PostInitialize()
{
if (!SkipDbSeed)
{
SeedHelper.SeedHostDb(IocManager);
}
}
}
}
| 32.54902 | 120 | 0.598193 | [
"MIT"
] | khanhly-dev/Abp_FirstProject | aspnet-core/src/FirstProject.EntityFrameworkCore/EntityFrameworkCore/FirstProjectEntityFrameworkModule.cs | 1,662 | C# |
using System;
using System.IO;
using Spark.Serialization;
using Xunit;
/* Copyright (c) 2015 Spark Software Ltd.
*
* 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 Test.Spark.Serialization
{
namespace UsingDeflateSerializer
{
public sealed class WhenSerializingStream
{
[Fact]
public void CompressBaseSerializerOutput()
{
var baseSerializer = new BinarySerializer();
var gzipSerializer = new DeflateSerializer(baseSerializer);
using (var memoryStream = new MemoryStream())
{
gzipSerializer.Serialize(memoryStream, "My Object", typeof(String));
Assert.Equal("Y2BkYGD4DwQgGgTYQAxO30oF/6Ss1OQSbgA=", Convert.ToBase64String(memoryStream.ToArray()));
}
}
}
public sealed class WhenDeserializingStream
{
[Fact]
public void DecompressBaseSerializerOutput()
{
var baseSerializer = new BinarySerializer();
var gzipSerializer = new DeflateSerializer(baseSerializer);
using (var memoryStream = new MemoryStream(Convert.FromBase64String("Y2BkYGD4DwQgGgTYQAxO30oF/6Ss1OQSbgA=")))
{
Assert.Equal("My Object", gzipSerializer.Deserialize(memoryStream, typeof(String)));
}
}
}
}
}
| 44.818182 | 158 | 0.66856 | [
"MIT"
] | cbaxter/infrastructure | src/Core.Tests/Serialization/DeflateSerializerTests.cs | 2,467 | C# |
/************************************************************************************
* @author wangjian
* 手动清除Player Preferences ,在window上Preferences存储在注册表中
************************************************************************************/
using UnityEditor;
using UnityEngine;
namespace SampleFramework.UUtils.Editor
{
public class ClearPlayerfres : ScriptableObject
{
[MenuItem("开发库/UUtils/SampleFramework/Clear All Player Preferences")]
public static void OnClearButton()
{
if (EditorUtility.DisplayDialog("Delete All Player Preferences?", " Are you sure you want to delete all player preferences?", "Yes", "No"))
{
PlayerPrefs.DeleteAll();
PlayerPrefs.Save();
}
}
}
} | 33.166667 | 151 | 0.497487 | [
"MIT"
] | waneta/uutils_public | SampleFramework/Editor/ClearPlayerPrefs.cs | 832 | C# |
using NetOffice.Attributes;
using NetOffice.CollectionsGeneric;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using NetRuntimeSystem = System;
namespace NetOffice.OfficeApi
{
/// <summary>
/// DispatchInterface DiagramNodes
/// SupportByVersion Office, 10,11,12,14,15,16
/// </summary>
[SupportByVersion("Office", 10, 11, 12, 14, 15, 16)]
[EntityType(EntityType.IsDispatchInterface), Enumerator(Enumerator.Reference, EnumeratorInvoke.Property), HasIndexProperty(IndexInvoke.Method, "Item")]
[Duplicate("NetOffice.ExcelApi.DiagramNodes")]
public class DiagramNodes : _IMsoDispObj, IEnumerableProvider<NetOffice.OfficeApi.DiagramNode>
{
#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(DiagramNodes);
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 DiagramNodes(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 DiagramNodes(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 DiagramNodes(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 DiagramNodes(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 DiagramNodes(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 DiagramNodes(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public DiagramNodes() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public DiagramNodes(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Office 10, 11, 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("Office", 10, 11, 12, 14, 15, 16), ProxyResult]
public object Parent
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion Office 10, 11, 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Office", 10, 11, 12, 14, 15, 16)]
public Int32 Count
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "Count");
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Office 10, 11, 12, 14, 15, 16
/// </summary>
/// <param name="index">object index</param>
[SupportByVersion("Office", 10, 11, 12, 14, 15, 16)]
[NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty]
public NetOffice.OfficeApi.DiagramNode this[object index]
{
get
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.OfficeApi.DiagramNode>(this, "Item", NetOffice.OfficeApi.DiagramNode.LateBindingApiWrapperType, index);
}
}
/// <summary>
/// SupportByVersion Office 10, 11, 12, 14, 15, 16
/// </summary>
[SupportByVersion("Office", 10, 11, 12, 14, 15, 16)]
public void SelectAll()
{
Factory.ExecuteMethod(this, "SelectAll");
}
#endregion
#region IEnumerableProvider<NetOffice.OfficeApi.DiagramNode>
ICOMObject IEnumerableProvider<NetOffice.OfficeApi.DiagramNode>.GetComObjectEnumerator(ICOMObject parent)
{
return NetOffice.Utils.GetComObjectEnumeratorAsProperty(parent, this, false);
}
IEnumerable IEnumerableProvider<NetOffice.OfficeApi.DiagramNode>.FetchVariantComObjectEnumerator(ICOMObject parent, ICOMObject enumerator)
{
return NetOffice.Utils.FetchVariantComObjectEnumerator(parent, enumerator, false);
}
#endregion
#region IEnumerable<NetOffice.OfficeApi.DiagramNode>
/// <summary>
/// SupportByVersion Office, 10,11,12,14,15,16
/// </summary>
[SupportByVersion("Office", 10, 11, 12, 14, 15, 16)]
public IEnumerator<NetOffice.OfficeApi.DiagramNode> GetEnumerator()
{
NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable);
foreach (NetOffice.OfficeApi.DiagramNode item in innerEnumerator)
yield return item;
}
#endregion
#region IEnumerable
/// <summary>
/// SupportByVersion Office, 10,11,12,14,15,16
/// </summary>
[SupportByVersion("Office", 10, 11, 12, 14, 15, 16)]
IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator()
{
return NetOffice.Utils.GetProxyEnumeratorAsProperty(this, false);
}
#endregion
#pragma warning restore
}
} | 35.35514 | 175 | 0.624637 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | ehsan2022002/VirastarE | Office/Office/DispatchInterfaces/DiagramNodes.cs | 7,568 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.Azure.IIoT.OpcUa.Protocol.Sample {
using Microsoft.Azure.IIoT.Utils;
using Serilog;
using Opc.Ua;
using Opc.Ua.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Security.Cryptography.X509Certificates;
/// <summary>
/// Sample server factory
/// </summary>
public class ServerFactory : IServerFactory {
/// <summary>
/// Whether to log status
/// </summary>
public bool LogStatus { get; set; }
/// <summary>
/// Server factory
/// </summary>
/// <param name="logger"></param>
/// <param name="nodes"></param>
public ServerFactory(ILogger logger, IEnumerable<INodeManagerFactory> nodes) {
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_nodes = nodes ?? throw new ArgumentNullException(nameof(nodes));
}
/// <summary>
/// Create sample servers
/// </summary>
/// <param name="logger"></param>
public ServerFactory(ILogger logger) :
this(logger, new List<INodeManagerFactory> {
new TestData.TestDataServer(),
new MemoryBuffer.MemoryBufferServer(),
new Boiler.BoilerServer(),
new Vehicles.VehiclesServer(),
new Reference.ReferenceServer(),
new HistoricalEvents.HistoricalEventsServer(),
new HistoricalAccess.HistoricalAccessServer(),
new Views.ViewsServer(),
new DataAccess.DataAccessServer(),
new Alarms.AlarmConditionServer(),
// new PerfTest.PerfTestServer(),
new SimpleEvents.SimpleEventsServer(),
new Plc.PlcServer()
}) {
}
/// <inheritdoc/>
public ApplicationConfiguration CreateServer(IEnumerable<int> ports, string applicationName,
out ServerBase server) {
server = new Server(LogStatus, _nodes, _logger);
return Server.CreateServerConfiguration(ports, applicationName);
}
/// <inheritdoc/>
private class Server : StandardServer {
/// <summary>
/// Create server
/// </summary>
/// <param name="logStatus"></param>
/// <param name="nodes"></param>
/// <param name="logger"></param>
public Server(bool logStatus, IEnumerable<INodeManagerFactory> nodes,
ILogger logger) {
_logger = logger;
_logStatus = logStatus;
_nodes = nodes;
}
/// <summary>
/// Create server configuration
/// </summary>
/// <param name="ports"></param>
/// <returns></returns>
public static ApplicationConfiguration CreateServerConfiguration(
IEnumerable<int> ports, string pkiRootPath) {
var extensions = new List<object> {
new MemoryBuffer.MemoryBufferConfiguration {
Buffers = new MemoryBuffer.MemoryBufferInstanceCollection {
new MemoryBuffer.MemoryBufferInstance {
Name = "UInt32",
TagCount = 10000,
DataType = "UInt32"
},
new MemoryBuffer.MemoryBufferInstance {
Name = "Double",
TagCount = 100,
DataType = "Double"
},
}
},
/// ...
};
if (string.IsNullOrEmpty(pkiRootPath)) {
pkiRootPath = "pki";
}
return new ApplicationConfiguration {
ApplicationName = "UA Core Sample Server",
ApplicationType = ApplicationType.Server,
ApplicationUri = $"urn:{Utils.GetHostName()}:OPCFoundation:CoreSampleServer",
Extensions = new XmlElementCollection(
extensions.Select(XmlElementEx.SerializeObject)),
ProductUri = "http://opcfoundation.org/UA/SampleServer",
SecurityConfiguration = new SecurityConfiguration {
ApplicationCertificate = new CertificateIdentifier {
StoreType = CertificateStoreType.Directory,
StorePath = $"{pkiRootPath}/own",
SubjectName = "UA Core Sample Server",
},
TrustedPeerCertificates = new CertificateTrustList {
StoreType = CertificateStoreType.Directory,
StorePath = $"{pkiRootPath}/trusted",
},
TrustedIssuerCertificates = new CertificateTrustList {
StoreType = CertificateStoreType.Directory,
StorePath = $"{pkiRootPath}/issuer",
},
RejectedCertificateStore = new CertificateTrustList {
StoreType = CertificateStoreType.Directory,
StorePath = $"{pkiRootPath}/rejected",
},
MinimumCertificateKeySize = 1024,
RejectSHA1SignedCertificates = false,
AutoAcceptUntrustedCertificates = true,
AddAppCertToTrustedStore = true
},
TransportConfigurations = new TransportConfigurationCollection(),
TransportQuotas = TransportQuotaConfigEx.DefaultTransportQuotas(),
ServerConfiguration = new ServerConfiguration {
// Sample server specific
ServerProfileArray = new StringCollection {
"Standard UA Server Profile",
"Data Access Server Facet",
"Method Server Facet"
},
ServerCapabilities = new StringCollection {
"DA"
},
SupportedPrivateKeyFormats = new StringCollection {
"PFX", "PEM"
},
NodeManagerSaveFile = "nodes.xml",
DiagnosticsEnabled = false,
ShutdownDelay = 5,
// Runtime configuration
BaseAddresses = new StringCollection(ports
.Distinct()
.Select(p => $"opc.tcp://localhost:{p}/UA/SampleServer")),
SecurityPolicies = new ServerSecurityPolicyCollection {
new ServerSecurityPolicy {
SecurityMode = MessageSecurityMode.Sign,
SecurityPolicyUri = SecurityPolicies.Basic256Sha256,
},
new ServerSecurityPolicy {
SecurityMode = MessageSecurityMode.SignAndEncrypt,
SecurityPolicyUri =SecurityPolicies.Basic256Sha256,
},
new ServerSecurityPolicy {
SecurityMode = MessageSecurityMode.None,
SecurityPolicyUri = SecurityPolicies.None
}
},
UserTokenPolicies = new UserTokenPolicyCollection {
new UserTokenPolicy {
TokenType = UserTokenType.Anonymous,
SecurityPolicyUri = SecurityPolicies.None,
},
new UserTokenPolicy {
TokenType = UserTokenType.UserName
},
new UserTokenPolicy {
TokenType = UserTokenType.Certificate
}
},
MinRequestThreadCount = 20,
MaxRequestThreadCount = 200,
MaxQueuedRequestCount = 200000,
MaxSessionCount = 1000,
MinSessionTimeout = 10000,
MaxSessionTimeout = 3600000,
MaxBrowseContinuationPoints = 1000,
MaxQueryContinuationPoints = 1000,
MaxHistoryContinuationPoints = 1000,
MaxRequestAge = 600000,
MinPublishingInterval = 100,
MaxPublishingInterval = 3600000,
PublishingResolution = 50,
MaxSubscriptionLifetime = 3600000,
MaxMessageQueueSize = 100,
MaxNotificationQueueSize = 100,
MaxNotificationsPerPublish = 1000,
MinMetadataSamplingInterval = 1000,
MaxPublishRequestCount = 20,
MaxSubscriptionCount = 100,
MaxEventQueueSize = 10000,
MinSubscriptionLifetime = 10000,
// Do not register with LDS
MaxRegistrationInterval = 0, // TODO
RegistrationEndpoint = null
},
TraceConfiguration = new TraceConfiguration {
TraceMasks = 1
}
};
}
/// <inheritdoc/>
protected override ServerProperties LoadServerProperties() {
var properties = new ServerProperties {
ManufacturerName = "OPC Foundation",
ProductName = "OPC UA Sample Servers",
ProductUri = "http://opcfoundation.org/UA/Samples/v1.0",
SoftwareVersion = Utils.GetAssemblySoftwareVersion(),
BuildNumber = Utils.GetAssemblyBuildNumber(),
BuildDate = Utils.GetAssemblyTimestamp()
};
return properties;
}
/// <inheritdoc/>
protected override MasterNodeManager CreateMasterNodeManager(
IServerInternal server, ApplicationConfiguration configuration) {
_logger.Information("Creating the Node Managers.");
var nodeManagers = _nodes
.Select(n => n.Create(server, configuration));
return new MasterNodeManager(server, configuration, null,
nodeManagers.ToArray());
}
/// <inheritdoc/>
protected override void OnServerStopping() {
_logger.Debug("The server is stopping.");
base.OnServerStopping();
_cts.Cancel();
_statusLogger?.Wait();
}
/// <inheritdoc/>
protected override void OnServerStarted(IServerInternal server) {
// start the status thread
_cts = new CancellationTokenSource();
if (_logStatus) {
_statusLogger = Task.Run(() => LogStatusAsync(_cts.Token));
// print notification on session events
CurrentInstance.SessionManager.SessionActivated += OnEvent;
CurrentInstance.SessionManager.SessionClosing += OnEvent;
CurrentInstance.SessionManager.SessionCreated += OnEvent;
}
base.OnServerStarted(server);
// request notifications when the user identity is changed. all valid users are accepted by default.
server.SessionManager.ImpersonateUser += SessionManager_ImpersonateUser;
}
/// <inheritdoc/>
protected override void OnServerStarting(ApplicationConfiguration configuration) {
_logger.Debug("The server is starting.");
CreateUserIdentityValidators(configuration);
base.OnServerStarting(configuration);
}
/// <inheritdoc/>
protected override void OnNodeManagerStarted(IServerInternal server) {
_logger.Information("The NodeManagers have started.");
base.OnNodeManagerStarted(server);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
_cts?.Dispose();
}
/// <summary>
/// Handle session event by logging status
/// </summary>
/// <param name="session"></param>
/// <param name="reason"></param>
private void OnEvent(Session session, SessionEventReason reason) {
_lastEventTime = DateTime.UtcNow;
LogSessionStatus(session, reason.ToString());
}
/// <summary>
/// Continously log session status if not logged during events
/// </summary>
/// <returns></returns>
private async Task LogStatusAsync(CancellationToken ct) {
while (!ct.IsCancellationRequested) {
if (DateTime.UtcNow - _lastEventTime > TimeSpan.FromMilliseconds(6000)) {
foreach (var session in CurrentInstance.SessionManager.GetSessions()) {
LogSessionStatus(session, "-Status-", true);
}
_lastEventTime = DateTime.UtcNow;
}
await Try.Async(() => Task.Delay(1000, ct));
}
}
/// <summary>
/// Helper to log session status
/// </summary>
/// <param name="session"></param>
/// <param name="reason"></param>
/// <param name="lastContact"></param>
private void LogSessionStatus(Session session, string reason, bool lastContact = false) {
lock (session.DiagnosticsLock) {
var item = string.Format("{0,9}:{1,20}:", reason,
session.SessionDiagnostics.SessionName);
if (lastContact) {
item += string.Format("Last Event:{0:HH:mm:ss}",
session.SessionDiagnostics.ClientLastContactTime.ToLocalTime());
}
else {
if (session.Identity != null) {
item += string.Format(":{0,20}", session.Identity.DisplayName);
}
item += string.Format(":{0}", session.Id);
}
_logger.Information(item);
}
}
/// <summary>
/// Creates the objects used to validate the user identity tokens supported by the server.
/// </summary>
private void CreateUserIdentityValidators(ApplicationConfiguration configuration) {
for (var ii = 0; ii < configuration.ServerConfiguration.UserTokenPolicies.Count; ii++) {
var policy = configuration.ServerConfiguration.UserTokenPolicies[ii];
// ignore policies without an explicit id.
if (string.IsNullOrEmpty(policy.PolicyId)) {
continue;
}
// create a validator for an issued token policy.
if (policy.TokenType == UserTokenType.IssuedToken) {
// the name of the element in the configuration file.
var qname = new XmlQualifiedName(policy.PolicyId, Namespaces.OpcUa);
// find the id for the issuer certificate.
var id = configuration.ParseExtension<CertificateIdentifier>(qname);
if (id == null) {
Utils.Trace(
Utils.TraceMasks.Error,
"Could not load CertificateIdentifier for UserTokenPolicy {0}",
policy.PolicyId);
continue;
}
}
// create a validator for a certificate token policy.
if (policy.TokenType == UserTokenType.Certificate) {
// the name of the element in the configuration file.
var qname = new XmlQualifiedName(policy.PolicyId, Namespaces.OpcUa);
// find the location of the trusted issuers.
var trustedIssuers = configuration.ParseExtension<CertificateTrustList>(qname);
if (trustedIssuers == null) {
Utils.Trace(
Utils.TraceMasks.Error,
"Could not load CertificateTrustList for UserTokenPolicy {0}",
policy.PolicyId);
continue;
}
// trusts any certificate in the trusted people store.
_certificateValidator = CertificateValidator.GetChannelValidator();
}
}
}
/// <summary>
/// Called when a client tries to change its user identity.
/// </summary>
private void SessionManager_ImpersonateUser(Session session,
ImpersonateEventArgs args) {
if (session == null) {
throw new ArgumentNullException(nameof(session));
}
if (args.NewIdentity is AnonymousIdentityToken guest) {
args.Identity = new UserIdentity(guest);
Utils.Trace("Guest access accepted: {0}", args.Identity.DisplayName);
return;
}
// check for a user name token.
if (args.NewIdentity is UserNameIdentityToken userNameToken) {
var admin = VerifyPassword(userNameToken.UserName, userNameToken.DecryptedPassword);
args.Identity = new UserIdentity(userNameToken);
if (admin) {
args.Identity = new SystemConfigurationIdentity(args.Identity);
}
Utils.Trace("UserName Token accepted: {0}", args.Identity.DisplayName);
return;
}
// check for x509 user token.
if (args.NewIdentity is X509IdentityToken x509Token) {
var admin = VerifyCertificate(x509Token.Certificate);
args.Identity = new UserIdentity(x509Token);
if (admin) {
args.Identity = new SystemConfigurationIdentity(args.Identity);
}
Utils.Trace("X509 Token accepted: {0}", args.Identity.DisplayName);
return;
}
// check for x509 user token.
if (args.NewIdentity is IssuedIdentityToken wssToken) {
var admin = VerifyToken(wssToken);
args.Identity = new UserIdentity(wssToken);
if (admin) {
args.Identity = new SystemConfigurationIdentity(args.Identity);
}
Utils.Trace("Issued Token accepted: {0}", args.Identity.DisplayName);
return;
}
// construct translation object with default text.
var info = new TranslationInfo("InvalidToken", "en-US",
"Specified token is not valid.");
// create an exception with a vendor defined sub-code.
throw new ServiceResultException(new ServiceResult(
StatusCodes.BadIdentityTokenRejected, "Bad token",
kServerNamespaceUri, new LocalizedText(info)));
}
/// <summary>
/// Validates the token
/// </summary>
/// <param name="wssToken"></param>
private bool VerifyToken(IssuedIdentityToken wssToken) {
if ((wssToken.TokenData?.Length ?? 0) == 0) {
var info = new TranslationInfo("InvalidToken", "en-US",
"Specified token is empty.");
// create an exception with a vendor defined sub-code.
throw new ServiceResultException(new ServiceResult(
StatusCodes.BadIdentityTokenRejected, "Bad token",
kServerNamespaceUri, new LocalizedText(info)));
}
return false;
}
/// <summary>
/// Validates the password for a username token.
/// </summary>
private bool VerifyPassword(string userName, string password) {
if (string.IsNullOrEmpty(password)) {
// construct translation object with default text.
var info = new TranslationInfo(
"InvalidPassword", "en-US",
"Specified password is not valid for user '{0}'.",
userName);
// create an exception with a vendor defined sub-code.
throw new ServiceResultException(new ServiceResult(
StatusCodes.BadIdentityTokenRejected, "InvalidPassword",
kServerNamespaceUri, new LocalizedText(info)));
}
if (userName.EqualsIgnoreCase("test") && password == "test") {
// Testing purposes only
return true;
}
return false;
}
/// <summary>
/// Verifies that a certificate user token is trusted.
/// </summary>
private bool VerifyCertificate(X509Certificate2 certificate) {
try {
if (_certificateValidator != null) {
_certificateValidator.Validate(certificate);
}
else {
CertificateValidator.Validate(certificate);
}
// determine if self-signed.
var isSelfSigned = X509Utils.CompareDistinguishedName(
certificate.Subject, certificate.Issuer);
// do not allow self signed application certs as user token
if (isSelfSigned && X509Utils.HasApplicationURN(certificate)) {
throw new ServiceResultException(StatusCodes.BadCertificateUseNotAllowed);
}
return false;
}
catch (Exception e) {
TranslationInfo info;
StatusCode result = StatusCodes.BadIdentityTokenRejected;
if (e is ServiceResultException se &&
se.StatusCode == StatusCodes.BadCertificateUseNotAllowed) {
info = new TranslationInfo(
"InvalidCertificate",
"en-US",
"'{0}' is an invalid user certificate.",
certificate.Subject);
result = StatusCodes.BadIdentityTokenInvalid;
}
else {
// construct translation object with default text.
info = new TranslationInfo(
"UntrustedCertificate",
"en-US",
"'{0}' is not a trusted user certificate.",
certificate.Subject);
}
// create an exception with a vendor defined sub-code.
throw new ServiceResultException(new ServiceResult(
result, info.Key, kServerNamespaceUri, new LocalizedText(info)));
}
}
private readonly ILogger _logger;
private readonly bool _logStatus;
private readonly IEnumerable<INodeManagerFactory> _nodes;
private Task _statusLogger;
private DateTime _lastEventTime;
private CancellationTokenSource _cts;
private ICertificateValidator _certificateValidator;
private const string kServerNamespaceUri = "http://opcfoundation.org/UA/Sample/";
}
private readonly ILogger _logger;
private readonly IEnumerable<INodeManagerFactory> _nodes;
}
}
| 45.980392 | 116 | 0.492692 | [
"MIT"
] | Azure/azure-iiot-components | components/opc-ua/src/Microsoft.Azure.IIoT.OpcUa.Testing/src/Servers/ServerFactory.cs | 25,795 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace DV_Json.DataSource.Generator
{
public class Program
{
public static void Main(string[] args)
{
Common.DV_Client client = new Common.DV_Client("127.0.0.1", 9001);
double rightAscensionSpeed = 0.33f;
double declinationSpeed = 0.1f;
double rightAscension = 0;
double declination = -1;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Task.Run(async () =>
{
while (true)
{
var elapsed = stopwatch.Elapsed;
stopwatch.Restart();
rightAscension += elapsed.TotalSeconds * rightAscensionSpeed;
declination += elapsed.TotalSeconds * declinationSpeed;
while (rightAscension > 1)
{
rightAscension -= 1;
}
while (declination > 1)
{
declination -= 2;
}
var dataPoint = new DataPointViewModel()
{
color = new DataPointColor(),
rightAscension = (float)rightAscension,
declination = (float)declination
};
var message = JsonConvert.SerializeObject(dataPoint);
Console.WriteLine("Sending message {0}", message);
await client.SendMessageToServerTaskAsync(message);
}
}).Wait();
}
}
}
| 33.907407 | 82 | 0.471327 | [
"MIT"
] | alchemz/Unity_DataVisualization | DV_Json/DataSource/DV_Json.DataSource.Generator/Program.cs | 1,833 | C# |
using System;
using System.Collections.Generic;
using System.Collections;
namespace BEPUutilities.DataStructures
{
///<summary>
/// List of objects which fires events when it is changed.
///</summary>
///<typeparam name="T">Type of elements in the list.</typeparam>
public class ObservableList<T> : IList<T>
{
/// <summary>
/// Gets the list wrapped by the observable list. Adds and removes made to this list directly will not trigger events.
/// </summary>
public RawList<T> WrappedList { get; private set; }
///<summary>
/// Fires when elements in the list are changed.
///</summary>
public event Action<ObservableList<T>> Changed;
///<summary>
/// Constructs a new observable list.
///</summary>
///<param name="list">List to copy into the internal wrapped list.</param>
public ObservableList(IList<T> list)
{
this.WrappedList = new RawList<T>(list.Count);
list.CopyTo(this.WrappedList.Elements, 0);
}
///<summary>
/// Constructs an empty observable list.
///</summary>
public ObservableList()
{
WrappedList = new RawList<T>();
}
///<summary>
/// Constructs an empty observable list with a given capacity.
///</summary>
///<param name="initialCapacity">Initial allocated storage in the list.</param>
public ObservableList(int initialCapacity)
{
WrappedList = new RawList<T>(initialCapacity);
}
protected void OnChanged()
{
if (Changed != null)
Changed(this);
}
/// <summary>
/// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>.
/// </summary>
/// <returns>
/// The index of <paramref name="item"/> if found in the list; otherwise, -1.
/// </returns>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param>
public int IndexOf(T item)
{
return WrappedList.IndexOf(item);
}
/// <summary>
/// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param><param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
public void Insert(int index, T item)
{
WrappedList.Insert(index, item);
}
/// <summary>
/// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
public void RemoveAt(int index)
{
WrappedList.RemoveAt(index);
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <returns>
/// The element at the specified index.
/// </returns>
/// <param name="index">The zero-based index of the element to get or set.</param><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception><exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception>
public T this[int index]
{
get
{
return WrappedList[index];
}
set
{
WrappedList[index] = value;
OnChanged();
}
}
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
public void Add(T item)
{
WrappedList.Add(item);
OnChanged();
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception>
public void Clear()
{
WrappedList.Clear();
OnChanged();
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
/// </summary>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
/// </returns>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
public bool Contains(T item)
{
return WrappedList.Contains(item);
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional.-or-The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.-or-Type cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
public void CopyTo(T[] array, int arrayIndex)
{
Array.Copy(WrappedList.Elements, 0, array, 0, WrappedList.Count);
}
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
public int Count
{
get { return WrappedList.Count; }
}
bool ICollection<T>.IsReadOnly
{
get { return (WrappedList as ICollection<T>).IsReadOnly; }
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
public bool Remove(T item)
{
if (WrappedList.Remove(item))
{
OnChanged();
return true;
}
return false;
}
///<summary>
/// Gets an enumerator for the list.
///</summary>
///<returns>Enumerator for the list.</returns>
public RawList<T>.Enumerator GetEnumerator()
{
return WrappedList.GetEnumerator();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return WrappedList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return WrappedList.GetEnumerator();
}
}
}
| 46.910448 | 994 | 0.610563 | [
"Unlicense",
"MIT"
] | MSylvia/Lemma | BEPUutilities/DataStructures/ObservableList.cs | 9,431 | C# |
/*********************************************
作者:曹旭升
QQ:279060597
访问博客了解详细介绍及更多内容:
http://blog.shengxunwei.com
**********************************************/
using System.Collections.Generic;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Manageability;
namespace Microsoft.Practices.EnterpriseLibrary.Data.Configuration.Manageability
{
public static class DatabaseSettingsWmiMapper
{
public static void GenerateWmiObjects(DatabaseSettings configurationObject,
ICollection<ConfigurationSetting> wmiSettings)
{
wmiSettings.Add(new DatabaseBlockSetting(configurationObject, configurationObject.DefaultDatabase));
}
public static bool SaveChanges(DatabaseBlockSetting setting, ConfigurationElement sourceElement)
{
DatabaseSettings section = (DatabaseSettings)sourceElement;
section.DefaultDatabase = setting.DefaultDatabase;
return true;
}
public static void GenerateDbProviderMappingWmiObjects(DbProviderMapping providerMapping,
ICollection<ConfigurationSetting> wmiSettings)
{
wmiSettings.Add(
new ProviderMappingSetting(providerMapping,
providerMapping.DbProviderName,
providerMapping.DatabaseType.AssemblyQualifiedName));
}
public static bool SaveChanges(ProviderMappingSetting providerMappingSetting, ConfigurationElement sourceElement)
{
DbProviderMapping element = (DbProviderMapping)sourceElement;
element.DatabaseTypeName = providerMappingSetting.DatabaseType;
return true;
}
internal static void RegisterWmiTypes()
{
ManagementEntityTypesRegistrar.SafelyRegisterTypes(typeof(DatabaseBlockSetting),
typeof(ProviderMappingSetting));
}
}
}
| 38 | 116 | 0.74714 | [
"MIT"
] | ckalvin-hub/Sheng.Winform.IDE | SourceCode/Source/EnterpriseLibrary/Data/Src/Data/Configuration/Manageability/DatabaseSettingsWmiMapper.cs | 1,796 | C# |
using Sandbox;
[CharacterBase]
public class CharacterBoyfriend : CharacterBase
{
public CharacterBoyfriend(){
id = "boyfriend";
name = "Boyfriend";
idleFrames = 6;
}
}
[CharacterBase]
public class CharacterBoyfriendPixel : CharacterBase
{
public CharacterBoyfriendPixel(){
id = "boyfriend_pixel";
name = "Boyfriend Pixel";
antialiasing = false;
idleFrames = 5;
}
}
[CharacterBase]
public class CharacterBoyfriendXmas : CharacterBase
{
public CharacterBoyfriendXmas(){
id = "boyfriend_xmas";
name = "Boyfriend Xmas";
idleFrames = 5;
}
} | 18.428571 | 52 | 0.634109 | [
"Apache-2.0"
] | CarsonKompon/sbox-funkin | code/characters/Boyfriends.cs | 645 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Inputs
{
public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleHeaderArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Name of the query header to inspect. This setting must be provided as lower case characters.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
public WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleHeaderArgs()
{
}
}
}
| 37.884615 | 189 | 0.745178 | [
"ECL-2.0",
"Apache-2.0"
] | chivandikwa/pulumi-aws | sdk/dotnet/WafV2/Inputs/WebAclRuleStatementRateBasedStatementScopeDownStatementNotStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleHeaderArgs.cs | 985 | C# |
#if NET461 || UNO_REFERENCE_API || __MACOS__
#pragma warning disable CS0067, CS649
#endif
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Windows.System;
using Uno.Extensions;
using Uno.UI.Common;
using Windows.UI.Text;
using Windows.UI.Xaml.Automation;
using Windows.UI.Xaml.Automation.Peers;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.Foundation;
using Windows.UI.Core;
using Microsoft.Extensions.Logging;
using Uno.UI.DataBinding;
namespace Windows.UI.Xaml.Controls
{
public class TextBoxConstants
{
public const string HeaderContentPartName = "HeaderContentPresenter";
public const string ContentElementPartName = "ContentElement";
public const string PlaceHolderPartName = "PlaceholderTextContentPresenter";
public const string DeleteButtonPartName = "DeleteButton";
public const string ButtonVisibleStateName = "ButtonVisible";
public const string ButtonCollapsedStateName = "ButtonCollapsed";
}
public partial class TextBox : Control, IFrameworkTemplatePoolAware
{
#pragma warning disable CS0067, CS0649
private IFrameworkElement _placeHolder;
private ContentControl _contentElement;
private WeakReference<Button> _deleteButton;
#pragma warning restore CS0067, CS0649
private ContentPresenter _header;
protected private bool _isButtonEnabled = true;
protected private bool CanShowButton => Text.HasValue() && FocusState != FocusState.Unfocused && !IsReadOnly && !AcceptsReturn && TextWrapping == TextWrapping.NoWrap;
public event TextChangedEventHandler TextChanged;
public event TypedEventHandler<TextBox, TextBoxTextChangingEventArgs> TextChanging;
public event TypedEventHandler<TextBox, TextBoxBeforeTextChangingEventArgs> BeforeTextChanging;
public event RoutedEventHandler SelectionChanged;
/// <summary>
/// Set when <see cref="TextChanged"/> event is being raised, to ensure modifications by handlers don't trigger an infinite loop.
/// </summary>
private bool _isInvokingTextChanged;
/// <summary>
/// Set when the <see cref="Text"/> property is being modified by user input.
/// </summary>
private bool _isInputModifyingText;
/// <summary>
/// Set when <see cref="RaiseTextChanged"/> has been dispatched but not yet called.
/// </summary>
private bool _isTextChangedPending;
/// <summary>
/// True if Text has changed while the TextBox has had focus, false otherwise
///
/// This flag is checked to avoid pushing a value to a two-way binding if no edits have occurred, per UWP's behavior.
/// </summary>
private bool _hasTextChangedThisFocusSession;
public TextBox()
{
InitializeVisualStates();
this.RegisterParentChangedCallback(this, OnParentChanged);
DefaultStyleKey = typeof(TextBox);
SizeChanged += OnSizeChanged;
}
private void OnSizeChanged(object sender, SizeChangedEventArgs args)
{
UpdateButtonStates();
}
private void OnParentChanged(object instance, object key, DependencyObjectParentChangedEventArgs args) => UpdateFontPartial();
private void InitializeProperties()
{
UpdatePlaceholderVisibility();
UpdateButtonStates();
OnInputScopeChanged(CreateInitialValueChangerEventArgs(InputScopeProperty, null, InputScope));
OnMaxLengthChanged(CreateInitialValueChangerEventArgs(MaxLengthProperty, null, MaxLength));
OnAcceptsReturnChanged(CreateInitialValueChangerEventArgs(AcceptsReturnProperty, null, AcceptsReturn));
OnIsReadonlyChanged(CreateInitialValueChangerEventArgs(IsReadOnlyProperty, null, IsReadOnly));
OnForegroundColorChanged(null, Foreground);
UpdateFontPartial();
OnHeaderChanged();
OnIsTextPredictionEnabledChanged(CreateInitialValueChangerEventArgs(IsTextPredictionEnabledProperty, IsTextPredictionEnabledProperty.GetMetadata(GetType()).DefaultValue, IsTextPredictionEnabled));
OnIsSpellCheckEnabledChanged(CreateInitialValueChangerEventArgs(IsSpellCheckEnabledProperty, IsSpellCheckEnabledProperty.GetMetadata(GetType()).DefaultValue, IsSpellCheckEnabled));
OnTextAlignmentChanged(CreateInitialValueChangerEventArgs(TextAlignmentProperty, TextAlignmentProperty.GetMetadata(GetType()).DefaultValue, TextAlignment));
OnTextWrappingChanged(CreateInitialValueChangerEventArgs(TextWrappingProperty, TextWrappingProperty.GetMetadata(GetType()).DefaultValue, TextWrapping));
OnFocusStateChanged((FocusState)FocusStateProperty.GetMetadata(GetType()).DefaultValue, FocusState, initial: true);
OnVerticalContentAlignmentChanged(VerticalAlignment.Top, VerticalContentAlignment);
OnTextCharacterCasingChanged(CreateInitialValueChangerEventArgs(CharacterCasingProperty, CharacterCasingProperty.GetMetadata(GetType()).DefaultValue, CharacterCasing));
var buttonRef = _deleteButton?.GetTarget();
if (buttonRef != null)
{
var thisRef = (this as IWeakReferenceProvider).WeakReference;
buttonRef.Command = new DelegateCommand(() => (thisRef.Target as TextBox)?.DeleteButtonClick());
}
InitializePropertiesPartial();
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
// Ensures we don't keep a reference to a textBoxView that exists in a previous template
_textBoxView = null;
_placeHolder = GetTemplateChild(TextBoxConstants.PlaceHolderPartName) as IFrameworkElement;
_contentElement = GetTemplateChild(TextBoxConstants.ContentElementPartName) as ContentControl;
_header = GetTemplateChild(TextBoxConstants.HeaderContentPartName) as ContentPresenter;
if (_contentElement is ScrollViewer scrollViewer)
{
#if __IOS__ || __MACOS__
// We disable scrolling because the inner ITextBoxView provides its own scrolling
scrollViewer.HorizontalScrollMode = ScrollMode.Disabled;
scrollViewer.VerticalScrollMode = ScrollMode.Disabled;
scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
#endif
}
if (GetTemplateChild(TextBoxConstants.DeleteButtonPartName) is Button button)
{
_deleteButton = new WeakReference<Button>(button);
}
UpdateTextBoxView();
InitializeProperties();
}
partial void InitializePropertiesPartial();
private DependencyPropertyChangedEventArgs CreateInitialValueChangerEventArgs(DependencyProperty property, object oldValue, object newValue) => new DependencyPropertyChangedEventArgs(property, oldValue, DependencyPropertyValuePrecedences.DefaultValue, newValue, DependencyPropertyValuePrecedences.DefaultValue);
#region Text DependencyProperty
public string Text
{
get => (string)this.GetValue(TextProperty);
set
{
if (value == null)
{
throw new ArgumentNullException();
}
this.SetValue(TextProperty, value);
}
}
public static DependencyProperty TextProperty { get ; } =
DependencyProperty.Register(
"Text",
typeof(string),
typeof(TextBox),
new FrameworkPropertyMetadata(
defaultValue: string.Empty,
options: FrameworkPropertyMetadataOptions.None,
propertyChangedCallback: (s, e) => ((TextBox)s)?.OnTextChanged(e),
coerceValueCallback: (d, v) => ((TextBox)d)?.CoerceText(v),
defaultUpdateSourceTrigger: UpdateSourceTrigger.Explicit
)
{
CoerceWhenUnchanged = false
}
);
protected virtual void OnTextChanged(DependencyPropertyChangedEventArgs e)
{
_hasTextChangedThisFocusSession = true;
if (!_isInvokingTextChanged)
{
#if !HAS_EXPENSIVE_TRYFINALLY // Try/finally incurs a very large performance hit in mono-wasm - https://github.com/dotnet/runtime/issues/50783
try
#endif
{
_isInvokingTextChanged = true;
TextChanging?.Invoke(this, new TextBoxTextChangingEventArgs());
}
#if !HAS_EXPENSIVE_TRYFINALLY // Try/finally incurs a very large performance hit in mono-wasm - https://github.com/dotnet/runtime/issues/50783
finally
#endif
{
_isInvokingTextChanged = false;
}
}
if (!_isInputModifyingText)
{
_textBoxView?.SetTextNative(Text);
}
UpdatePlaceholderVisibility();
UpdateButtonStates();
if (!_isTextChangedPending)
{
_isTextChangedPending = true;
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, RaiseTextChanged);
}
}
private void RaiseTextChanged()
{
if (!_isInvokingTextChanged)
{
#if !HAS_EXPENSIVE_TRYFINALLY // Try/finally incurs a very large performance hit in mono-wasm - https://github.com/dotnet/runtime/issues/50783
try
#endif
{
_isInvokingTextChanged = true;
TextChanged?.Invoke(this, new TextChangedEventArgs(this));
}
#if !HAS_EXPENSIVE_TRYFINALLY // Try/finally incurs a very large performance hit in mono-wasm - https://github.com/dotnet/runtime/issues/50783
finally
#endif
{
_isInvokingTextChanged = false;
_isTextChangedPending = false;
}
}
_textBoxView?.SetTextNative(Text);
}
private void UpdatePlaceholderVisibility()
{
if (_placeHolder != null)
{
_placeHolder.Visibility = Text.IsNullOrEmpty() ? Visibility.Visible : Visibility.Collapsed;
}
}
private object CoerceText(object baseValue)
{
if (!(baseValue is string baseString))
{
return ""; //Pushing null to the binding resets the text. (Setting null to the Text property directly throws an exception.)
}
if (MaxLength > 0 && baseString.Length > MaxLength)
{
return DependencyProperty.UnsetValue;
}
var args = new TextBoxBeforeTextChangingEventArgs(baseString);
BeforeTextChanging?.Invoke(this, args);
if (args.Cancel)
{
return DependencyProperty.UnsetValue;
}
return baseValue;
}
#endregion
protected override void OnFontSizeChanged(double oldValue, double newValue)
{
base.OnFontSizeChanged(oldValue, newValue);
UpdateFontPartial();
}
protected override void OnFontFamilyChanged(FontFamily oldValue, FontFamily newValue)
{
base.OnFontFamilyChanged(oldValue, newValue);
UpdateFontPartial();
}
protected override void OnFontStyleChanged(FontStyle oldValue, FontStyle newValue)
{
base.OnFontStyleChanged(oldValue, newValue);
UpdateFontPartial();
}
protected override void OnFontWeightChanged(FontWeight oldValue, FontWeight newValue)
{
base.OnFontWeightChanged(oldValue, newValue);
UpdateFontPartial();
}
partial void UpdateFontPartial();
protected override void OnForegroundColorChanged(Brush oldValue, Brush newValue) => OnForegroundColorChangedPartial(newValue);
partial void OnForegroundColorChangedPartial(Brush newValue);
#region PlaceholderText DependencyProperty
public string PlaceholderText
{
get => (string)this.GetValue(PlaceholderTextProperty);
set => this.SetValue(PlaceholderTextProperty, value);
}
public static DependencyProperty PlaceholderTextProperty { get ; } =
DependencyProperty.Register(
"PlaceholderText",
typeof(string),
typeof(TextBox),
new FrameworkPropertyMetadata(defaultValue: string.Empty)
);
#endregion
#region InputScope DependencyProperty
public InputScope InputScope
{
get => (InputScope)this.GetValue(InputScopeProperty);
set => this.SetValue(InputScopeProperty, value);
}
public static DependencyProperty InputScopeProperty { get ; } =
DependencyProperty.Register(
"InputScope",
typeof(InputScope),
typeof(TextBox),
new FrameworkPropertyMetadata(
defaultValue: new InputScope()
{
Names =
{
new InputScopeName
{
NameValue = InputScopeNameValue.Default
}
}
},
propertyChangedCallback: (s, e) => ((TextBox)s)?.OnInputScopeChanged(e)
)
);
protected void OnInputScopeChanged(DependencyPropertyChangedEventArgs e) => OnInputScopeChangedPartial(e);
partial void OnInputScopeChangedPartial(DependencyPropertyChangedEventArgs e);
#endregion
#region MaxLength DependencyProperty
public int MaxLength
{
get => (int)this.GetValue(MaxLengthProperty);
set => this.SetValue(MaxLengthProperty, value);
}
public static DependencyProperty MaxLengthProperty { get ; } =
DependencyProperty.Register(
"MaxLength",
typeof(int),
typeof(TextBox),
new FrameworkPropertyMetadata(
defaultValue: 0,
propertyChangedCallback: (s, e) => ((TextBox)s)?.OnMaxLengthChanged(e)
)
);
private void OnMaxLengthChanged(DependencyPropertyChangedEventArgs e) => OnMaxLengthChangedPartial(e);
partial void OnMaxLengthChangedPartial(DependencyPropertyChangedEventArgs e);
#endregion
#region AcceptsReturn DependencyProperty
public bool AcceptsReturn
{
get => (bool)this.GetValue(AcceptsReturnProperty);
set => this.SetValue(AcceptsReturnProperty, value);
}
public static DependencyProperty AcceptsReturnProperty { get ; } =
DependencyProperty.Register(
"AcceptsReturn",
typeof(bool),
typeof(TextBox),
new FrameworkPropertyMetadata(
defaultValue: false,
propertyChangedCallback: (s, e) => ((TextBox)s)?.OnAcceptsReturnChanged(e)
)
);
private void OnAcceptsReturnChanged(DependencyPropertyChangedEventArgs e)
{
OnAcceptsReturnChangedPartial(e);
UpdateButtonStates();
}
partial void OnAcceptsReturnChangedPartial(DependencyPropertyChangedEventArgs e);
#endregion
#region TextWrapping DependencyProperty
public TextWrapping TextWrapping
{
get => (TextWrapping)this.GetValue(TextWrappingProperty);
set => this.SetValue(TextWrappingProperty, value);
}
public static DependencyProperty TextWrappingProperty { get ; } =
DependencyProperty.Register(
"TextWrapping",
typeof(TextWrapping),
typeof(TextBox),
new FrameworkPropertyMetadata(
defaultValue: TextWrapping.NoWrap,
propertyChangedCallback: (s, e) => ((TextBox)s)?.OnTextWrappingChanged(e))
);
private void OnTextWrappingChanged(DependencyPropertyChangedEventArgs args)
{
OnTextWrappingChangedPartial(args);
UpdateButtonStates();
}
partial void OnTextWrappingChangedPartial(DependencyPropertyChangedEventArgs e);
#endregion
#if __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[Uno.NotImplemented("__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
#endif
public CharacterCasing CharacterCasing
{
get => (CharacterCasing)this.GetValue(CharacterCasingProperty);
set => this.SetValue(CharacterCasingProperty, value);
}
#if __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[Uno.NotImplemented("__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
#endif
public static DependencyProperty CharacterCasingProperty { get; } =
DependencyProperty.Register(
nameof(CharacterCasing),
typeof(CharacterCasing),
typeof(TextBox),
new FrameworkPropertyMetadata(
defaultValue: CharacterCasing.Normal,
propertyChangedCallback: (s, e) => ((TextBox)s)?.OnTextCharacterCasingChanged(e))
);
private void OnTextCharacterCasingChanged(DependencyPropertyChangedEventArgs e)
{
OnTextCharacterCasingChangedPartial(e);
}
partial void OnTextCharacterCasingChangedPartial(DependencyPropertyChangedEventArgs e);
#region IsReadOnly DependencyProperty
public bool IsReadOnly
{
get => (bool)GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
public static DependencyProperty IsReadOnlyProperty { get ; } =
DependencyProperty.Register(
"IsReadOnly",
typeof(bool),
typeof(TextBox),
new FrameworkPropertyMetadata(
false,
propertyChangedCallback: (s, e) => ((TextBox)s)?.OnIsReadonlyChanged(e)
)
);
private void OnIsReadonlyChanged(DependencyPropertyChangedEventArgs e)
{
OnIsReadonlyChangedPartial(e);
UpdateButtonStates();
}
partial void OnIsReadonlyChangedPartial(DependencyPropertyChangedEventArgs e);
#endregion
#region Header DependencyProperties
public object Header
{
get => (object)GetValue(HeaderProperty);
set => SetValue(HeaderProperty, value);
}
public static DependencyProperty HeaderProperty { get ; } =
DependencyProperty.Register("Header",
typeof(object),
typeof(TextBox),
new FrameworkPropertyMetadata(defaultValue: null,
propertyChangedCallback: (s, e) => ((TextBox)s)?.OnHeaderChanged()
)
);
public DataTemplate HeaderTemplate
{
get => (DataTemplate)GetValue(HeaderTemplateProperty);
set => SetValue(HeaderTemplateProperty, value);
}
public static DependencyProperty HeaderTemplateProperty { get ; } =
DependencyProperty.Register("HeaderTemplate",
typeof(DataTemplate),
typeof(TextBox),
new FrameworkPropertyMetadata(
defaultValue: null,
options: FrameworkPropertyMetadataOptions.ValueDoesNotInheritDataContext,
propertyChangedCallback: (s, e) => ((TextBox)s)?.OnHeaderChanged()
)
);
private void OnHeaderChanged()
{
var headerVisibility = (Header != null || HeaderTemplate != null) ? Visibility.Visible : Visibility.Collapsed;
if (_header != null)
{
_header.Visibility = headerVisibility;
}
}
#endregion
#region IsSpellCheckEnabled DependencyProperty
public bool IsSpellCheckEnabled
{
get => (bool)this.GetValue(IsSpellCheckEnabledProperty);
set => this.SetValue(IsSpellCheckEnabledProperty, value);
}
public static DependencyProperty IsSpellCheckEnabledProperty { get ; } =
DependencyProperty.Register(
"IsSpellCheckEnabled",
typeof(bool),
typeof(TextBox),
new FrameworkPropertyMetadata(
defaultValue: true,
propertyChangedCallback: (s, e) => ((TextBox)s)?.OnIsSpellCheckEnabledChanged(e)
)
);
protected virtual void OnIsSpellCheckEnabledChanged(DependencyPropertyChangedEventArgs e) => OnIsSpellCheckEnabledChangedPartial(e);
partial void OnIsSpellCheckEnabledChangedPartial(DependencyPropertyChangedEventArgs e);
#endregion
#region IsTextPredictionEnabled DependencyProperty
[Uno.NotImplemented]
public bool IsTextPredictionEnabled
{
get => (bool)this.GetValue(IsTextPredictionEnabledProperty);
set => this.SetValue(IsTextPredictionEnabledProperty, value);
}
[Uno.NotImplemented]
public static DependencyProperty IsTextPredictionEnabledProperty { get ; } =
DependencyProperty.Register(
"IsTextPredictionEnabled",
typeof(bool),
typeof(TextBox),
new FrameworkPropertyMetadata(
defaultValue: true,
propertyChangedCallback: (s, e) => ((TextBox)s)?.OnIsTextPredictionEnabledChanged(e)
)
);
protected virtual void OnIsTextPredictionEnabledChanged(DependencyPropertyChangedEventArgs e) => OnIsTextPredictionEnabledChangedPartial(e);
partial void OnIsTextPredictionEnabledChangedPartial(DependencyPropertyChangedEventArgs e);
#endregion
#region TextAlignment DependencyProperty
#if XAMARIN_ANDROID
public new TextAlignment TextAlignment
#else
public TextAlignment TextAlignment
#endif
{
get { return (TextAlignment)GetValue(TextAlignmentProperty); }
set { SetValue(TextAlignmentProperty, value); }
}
public static DependencyProperty TextAlignmentProperty { get ; } =
DependencyProperty.Register("TextAlignment", typeof(TextAlignment), typeof(TextBox), new FrameworkPropertyMetadata(TextAlignment.Left, (s, e) => ((TextBox)s)?.OnTextAlignmentChanged(e)));
protected virtual void OnTextAlignmentChanged(DependencyPropertyChangedEventArgs e) => OnTextAlignmentChangedPartial(e);
partial void OnTextAlignmentChangedPartial(DependencyPropertyChangedEventArgs e);
#endregion
internal override void UpdateFocusState(FocusState focusState)
{
var oldValue = FocusState;
base.UpdateFocusState(focusState);
OnFocusStateChanged(oldValue, focusState, initial: false);
}
private void OnFocusStateChanged(FocusState oldValue, FocusState newValue, bool initial)
{
OnFocusStateChangedPartial(newValue);
if (!initial && newValue == FocusState.Unfocused && _hasTextChangedThisFocusSession)
{
// Manually update Source when losing focus because TextProperty's default UpdateSourceTrigger is Explicit
var bindingExpression = GetBindingExpression(TextProperty);
bindingExpression?.UpdateSource(Text);
}
UpdateButtonStates();
if (oldValue == FocusState.Unfocused || newValue == FocusState.Unfocused)
{
_hasTextChangedThisFocusSession = false;
}
}
partial void OnFocusStateChangedPartial(FocusState focusState);
protected override void OnPointerPressed(PointerRoutedEventArgs args)
{
base.OnPointerPressed(args);
args.Handled = true;
#if !__WASM__
Focus(FocusState.Pointer);
#endif
}
/// <inheritdoc />
protected override void OnPointerReleased(PointerRoutedEventArgs args)
{
base.OnPointerReleased(args);
args.Handled = true;
}
/// <inheritdoc />
protected override void OnKeyDown(KeyRoutedEventArgs args)
{
base.OnKeyDown(args);
// Note: On windows only keys that are "moving the cursor" are handled
// AND ** only KeyDown ** is handled (not KeyUp)
switch (args.Key)
{
case VirtualKey.Up:
case VirtualKey.Down:
if (AcceptsReturn)
{
args.Handled = true;
}
break;
case VirtualKey.Left:
case VirtualKey.Right:
case VirtualKey.Home:
case VirtualKey.End:
args.Handled = true;
break;
}
}
protected virtual void UpdateButtonStates()
{
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug(nameof(UpdateButtonStates));
}
// Minimum width for TextBox with DeleteButton visible is 5em.
if (CanShowButton && _isButtonEnabled && ActualWidth > FontSize * 5)
{
VisualStateManager.GoToState(this, TextBoxConstants.ButtonVisibleStateName, true);
}
else
{
VisualStateManager.GoToState(this, TextBoxConstants.ButtonCollapsedStateName, true);
}
}
/// <summary>
/// Respond to text input from user interaction.
/// </summary>
/// <param name="newText">The most recent version of the text from the input field.</param>
/// <returns>The value of the <see cref="Text"/> property, which may have been modified programmatically.</returns>
internal string ProcessTextInput(string newText)
{
#if !HAS_EXPENSIVE_TRYFINALLY // Try/finally incurs a very large performance hit in mono-wasm - https://github.com/dotnet/runtime/issues/50783
try
#endif
{
_isInputModifyingText = true;
Text = newText;
}
#if !HAS_EXPENSIVE_TRYFINALLY // Try/finally incurs a very large performance hit in mono-wasm - https://github.com/dotnet/runtime/issues/50783
finally
#endif
{
_isInputModifyingText = false;
}
return Text; //This may have been modified by BeforeTextChanging, TextChanging, DP callback, etc
}
private void DeleteButtonClick()
{
Text = string.Empty;
OnDeleteButtonClickPartial();
}
partial void OnDeleteButtonClickPartial();
internal void OnSelectionChanged() => SelectionChanged?.Invoke(this, new RoutedEventArgs(this));
public void OnTemplateRecycled()
{
Text = string.Empty;
}
protected override AutomationPeer OnCreateAutomationPeer() => new TextBoxAutomationPeer(this);
public override string GetAccessibilityInnerText() => Text;
protected override void OnVerticalContentAlignmentChanged(VerticalAlignment oldVerticalContentAlignment, VerticalAlignment newVerticalContentAlignment)
{
base.OnVerticalContentAlignmentChanged(oldVerticalContentAlignment, newVerticalContentAlignment);
if (_contentElement != null)
{
_contentElement.VerticalContentAlignment = newVerticalContentAlignment;
}
if (_placeHolder != null)
{
_placeHolder.VerticalAlignment = newVerticalContentAlignment;
}
OnVerticalContentAlignmentChangedPartial(oldVerticalContentAlignment, newVerticalContentAlignment);
}
partial void OnVerticalContentAlignmentChangedPartial(VerticalAlignment oldVerticalContentAlignment, VerticalAlignment newVerticalContentAlignment);
public void Select(int start, int length)
{
if (start < 0)
{
throw new ArgumentException($"'{start}' cannot be negative.", nameof(start));
}
if (length < 0)
{
throw new ArgumentException($"'{length}' cannot be negative.", nameof(length));
}
// TODO: Test and adjust (if needed) this logic for surrogate pairs.
var textLength = Text.Length;
if (start >= textLength)
{
start = textLength;
length = 0;
}
else if (start + length > textLength)
{
length = textLength - start;
}
if (SelectionStart == start && SelectionLength == length)
{
return;
}
SelectPartial(start, length);
OnSelectionChanged();
}
public void SelectAll() => SelectAllPartial();
partial void SelectPartial(int start, int length);
partial void SelectAllPartial();
internal override bool CanHaveChildren() => true;
}
}
| 30.542331 | 313 | 0.751326 | [
"Apache-2.0"
] | Arieldelossantos/uno | src/Uno.UI/UI/Xaml/Controls/TextBox/TextBox.cs | 24,894 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Lidgren.Core;
using System.Numerics;
namespace UnitTests
{
[TestClass]
public class SpanExtensionsTests
{
[TestMethod]
public void Test7BitEncoding()
{
byte[] arr = new byte[1024];
// test variable lengths
var numbers = new ulong[7];
numbers = new ulong[] { 1, 25, 137, 255, 256, 10000, 1000000 };
ulong state = RandomSeed.GetUInt64();
for (int runs = 0; runs < 250000; runs++)
{
var work = arr.AsSpan();
for (int i = 0; i < numbers.Length; i++)
work.WriteVariableUInt64(numbers[i]);
int resultLength = arr.Length - work.Length;
ReadOnlySpan<byte> res = arr.AsSpan(0, resultLength);
for (int i = 0; i < numbers.Length; i++)
{
var nr = res.ReadVariableUInt64();
Assert.AreEqual(numbers[i], nr);
}
// re-randomize
numbers[0] = (ulong)PRNG.Next(ref state, 0, 6);
numbers[1] = (ulong)PRNG.Next(ref state, 7, 300);
numbers[2] = (ulong)PRNG.Next(ref state, 300, 5000);
numbers[3] = (ulong)PRNG.Next(ref state, 5000, 50000);
numbers[4] = (ulong)PRNG.Next(ref state, 50000, 500000);
numbers[5] = (ulong)PRNG.NextUInt64(ref state);
numbers[6] = (ulong)PRNG.NextUInt64(ref state);
}
// signed 64 bit
var signed64 = new long[7];
for (int runs = 0; runs < 250000; runs++)
{
// re-randomize
signed64[0] = (long)PRNG.Next(ref state, -5, 5);
signed64[1] = (long)PRNG.Next(ref state, -100, 100);
signed64[2] = (long)PRNG.Next(ref state, -300, 300);
signed64[3] = (long)PRNG.Next(ref state, -5000, 5000);
signed64[4] = (long)PRNG.Next(ref state, -70000, 70000);
signed64[5] = (long)PRNG.NextUInt64(ref state);
signed64[6] = (long)PRNG.NextUInt64(ref state);
var work = arr.AsSpan();
for (int i = 0; i < signed64.Length; i++)
work.WriteVariableInt64(signed64[i]);
int resultLength = arr.Length - work.Length;
ReadOnlySpan<byte> res = arr.AsSpan(0, resultLength);
for (int i = 0; i < signed64.Length; i++)
{
var nr = res.ReadVariableInt64();
Assert.AreEqual(signed64[i], nr);
}
}
// signed int32
var signed32 = new int[7];
for (int runs = 0; runs < 250000; runs++)
{
// re-randomize
signed32[0] = (int)PRNG.Next(ref state, -5, 5);
signed32[1] = (int)PRNG.Next(ref state, -100, 100);
signed32[2] = (int)PRNG.Next(ref state, -300, 300);
signed32[3] = (int)PRNG.Next(ref state, -5000, 5000);
signed32[4] = (int)PRNG.Next(ref state, -70000, 70000);
signed32[5] = (int)PRNG.NextUInt32(ref state);
signed32[6] = (int)PRNG.NextUInt32(ref state);
var work = arr.AsSpan();
for (int i = 0; i < signed32.Length; i++)
work.WriteVariableInt32(signed32[i]);
int resultLength = arr.Length - work.Length;
ReadOnlySpan<byte> res = arr.AsSpan(0, resultLength);
for (int i = 0; i < signed64.Length; i++)
{
var nr = res.ReadVariableInt32();
Assert.AreEqual(signed32[i], nr);
}
}
}
[TestMethod]
public void TestSpanExtensions()
{
var arr = new byte[1024];
var span = arr.AsSpan();
span.WriteBool(true);
span.WriteDouble(1.2);
span.WriteString("Pararibulitis");
span.WriteUInt16(12);
span.Write<Vector2>(new Vector2(1.0f, 2.0f));
span.WriteLengthPrefixedArray<byte>(new byte[] { 43, 42, 41 });
span.Write<Vector3>(new Vector3(1.0f, 2.0f, 3.0f));
span.Write<Vector4>(new Vector4(1.0f, 2.0f, 3.0f, 4.0f));
span.Write<Quaternion>(new Quaternion(1.0f, 2.0f, 3.0f, 4.0f));
span.WriteInt32(-120);
span.WriteString("Pickle Rick");
var len = arr.Length - span.Length;
var rdr = new ReadOnlySpan<byte>(arr, 0, len);
Assert.IsTrue(rdr.ReadBool());
Assert.AreEqual(1.2, rdr.ReadDouble());
Assert.AreEqual("Pararibulitis", rdr.ReadString());
Assert.AreEqual(12, rdr.ReadUInt16());
Assert.IsTrue(rdr.Read<Vector2>() == new Vector2(1.0f, 2.0f));
var barr = rdr.ReadLengthPrefixedArray<byte>();
Assert.AreEqual(3, barr.Length);
Assert.AreEqual(43, barr[0]);
Assert.AreEqual(42, barr[1]);
Assert.AreEqual(41, barr[2]);
Assert.IsTrue(rdr.Read<Vector3>() == new Vector3(1.0f, 2.0f, 3.0f));
Assert.IsTrue(rdr.Read<Vector4>() == new Vector4(1.0f, 2.0f, 3.0f, 4.0f));
Assert.IsTrue(rdr.Read<Quaternion>() == new Quaternion(1.0f, 2.0f, 3.0f, 4.0f));
Assert.AreEqual(-120, rdr.ReadInt32());
var tmp = new char[32];
var plen = rdr.ReadString(tmp.AsSpan());
Assert.AreEqual("Pickle Rick".Length, plen);
Assert.IsTrue(tmp.AsSpan(0, plen).SequenceEqual("Pickle Rick".AsSpan()));
Assert.AreEqual(0, rdr.Length);
}
}
}
| 30.98 | 83 | 0.63116 | [
"MIT"
] | lidgren/Lidgren.Core | tests/SpanExtensionsTests.cs | 4,649 | C# |
#region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2017
// by DotNetNuke Corporation
//
// 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.
#endregion
#region Usings
using System;
using System.Collections.Generic;
#endregion
namespace DotNetNuke.Services.Mobile
{
public interface IRedirection
{
/// <summary>
/// Primary ID.
/// </summary>
int Id { get; }
/// <summary>
/// Portal Id.
/// </summary>
int PortalId { get; set; }
/// <summary>
/// Redirection name.
/// </summary>
string Name { get; set; }
/// <summary>
/// if redirect by visit the whole portal, this value should be -1;
/// otherwise should be the exactly page id for redirection.
/// </summary>
int SourceTabId { get; set; }
/// <summary>
/// This value will be available when SourceTabId have a specific value, in that way when this value is true, page will rediect
/// to target when request source tab and all child tabs under source tab.
/// </summary>
bool IncludeChildTabs { get; set; }
/// <summary>
/// The redirection type: should be Mobile, Tablet, Both of mobile and tablet, and all other unknown devices.
/// if this value is Other, should use MatchRules to match the special request need to redirect.
/// </summary>
RedirectionType Type { get; set; }
/// <summary>
/// request match rules.
/// </summary>
IList<IMatchRule> MatchRules { get; set; }
/// <summary>
/// Redirection target type.
/// </summary>
TargetType TargetType { get; set; }
/// <summary>
/// Redirection target value, can a portal id, tab id or a specific url.
/// </summary>
object TargetValue { get; set; }
/// <summary>
/// Enabled the Redirection.
/// </summary>
bool Enabled { get; set; }
/// <summary>
/// Redirection's Order
/// </summary>
int SortOrder { get; set; }
}
}
| 32.573034 | 129 | 0.688513 | [
"MIT"
] | Expasys/Expasys.Web.Platform | DNN Platform/Library/Services/Mobile/IRedirection.cs | 2,902 | C# |
//------------------------------------------------------------------------------
// <auto-generated>This code was generated by LLBLGen Pro v4.1.</auto-generated>
//------------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.Collections.Specialized;
using System.Collections.Generic;
namespace EF6.Bencher.EntityClasses
{
/// <summary>Class which represents the entity 'ProductDescription'.</summary>
[Serializable]
[DataContract(IsReference=true)]
public partial class ProductDescription : CommonEntityBase
{
/// <summary>Initializes a new instance of the <see cref="ProductDescription"/> class.</summary>
public ProductDescription() : base()
{
this.ProductModelProductDescriptionCultures = new HashSet<ProductModelProductDescriptionCulture>();
}
#region Class Property Declarations
/// <summary>Gets or sets the Description field. </summary>
[DataMember]
public System.String Description { get; set;}
/// <summary>Gets or sets the ModifiedDate field. </summary>
[DataMember]
public System.DateTime ModifiedDate { get; set;}
/// <summary>Gets or sets the ProductDescriptionId field. </summary>
[DataMember]
public System.Int32 ProductDescriptionId { get; set;}
/// <summary>Gets or sets the Rowguid field. </summary>
[DataMember]
public System.Guid Rowguid { get; set;}
/// <summary>Represents the navigator which is mapped onto the association 'ProductModelProductDescriptionCulture.ProductDescription - ProductDescription.ProductModelProductDescriptionCultures (m:1)'</summary>
[DataMember]
public virtual ICollection<ProductModelProductDescriptionCulture> ProductModelProductDescriptionCultures { get; set;}
#endregion
}
}
| 42.395349 | 211 | 0.706528 | [
"MIT"
] | FransBouma/RawDataAccessBencher | EF6/Model/EntityClasses/ProductDescription.cs | 1,825 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace IM_PJ {
public partial class bao_cao_nhan_vien {
/// <summary>
/// txtTextSearch control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtTextSearch;
/// <summary>
/// ddlCategory control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlCategory;
/// <summary>
/// rFromDate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::Telerik.Web.UI.RadDatePicker rFromDate;
/// <summary>
/// rToDate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::Telerik.Web.UI.RadDatePicker rToDate;
/// <summary>
/// btnSearch control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnSearch;
/// <summary>
/// ltrTotalRemainQuantity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltrTotalRemainQuantity;
/// <summary>
/// ltrAverageRemainQuantity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltrAverageRemainQuantity;
/// <summary>
/// ltrTotalSaleOrder control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltrTotalSaleOrder;
/// <summary>
/// ltrAverageSaleOrder control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltrAverageSaleOrder;
/// <summary>
/// ltrTotalSoldQuantity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltrTotalSoldQuantity;
/// <summary>
/// ltrAverageSoldQuantity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltrAverageSoldQuantity;
/// <summary>
/// ltrTotalRefundQuantity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltrTotalRefundQuantity;
/// <summary>
/// ltrAverageRefundQuantity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltrAverageRefundQuantity;
/// <summary>
/// ltrPercentOfSystem control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltrPercentOfSystem;
/// <summary>
/// ltrTotalNewCustomer control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltrTotalNewCustomer;
/// <summary>
/// ltrChartData control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltrChartData;
}
}
| 37.2625 | 86 | 0.54059 | [
"Apache-2.0"
] | phanhoanganh9x/ANNsys | IM_PJ/bao-cao-nhan-vien.aspx.designer.cs | 5,964 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801
{
using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell;
/// <summary>Function secrets.</summary>
[System.ComponentModel.TypeConverter(typeof(FunctionSecretsTypeConverter))]
public partial class FunctionSecrets
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.FunctionSecrets"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecrets" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecrets DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new FunctionSecrets(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.FunctionSecrets"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecrets" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecrets DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new FunctionSecrets(content);
}
/// <summary>
/// Creates a new instance of <see cref="FunctionSecrets" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecrets FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.FunctionSecrets"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal FunctionSecrets(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Property"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.FunctionSecretsPropertiesTypeConverter.ConvertFrom);
}
if (content.Contains("Id"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Id, global::System.Convert.ToString);
}
if (content.Contains("Name"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Name, global::System.Convert.ToString);
}
if (content.Contains("Kind"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Kind = (string) content.GetValueForProperty("Kind",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Kind, global::System.Convert.ToString);
}
if (content.Contains("Type"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Type, global::System.Convert.ToString);
}
if (content.Contains("Key"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsInternal)this).Key = (string) content.GetValueForProperty("Key",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsInternal)this).Key, global::System.Convert.ToString);
}
if (content.Contains("TriggerUrl"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsInternal)this).TriggerUrl = (string) content.GetValueForProperty("TriggerUrl",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsInternal)this).TriggerUrl, global::System.Convert.ToString);
}
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.FunctionSecrets"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal FunctionSecrets(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("Property"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.FunctionSecretsPropertiesTypeConverter.ConvertFrom);
}
if (content.Contains("Id"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Id, global::System.Convert.ToString);
}
if (content.Contains("Name"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Name, global::System.Convert.ToString);
}
if (content.Contains("Kind"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Kind = (string) content.GetValueForProperty("Kind",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Kind, global::System.Convert.ToString);
}
if (content.Contains("Type"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IProxyOnlyResourceInternal)this).Type, global::System.Convert.ToString);
}
if (content.Contains("Key"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsInternal)this).Key = (string) content.GetValueForProperty("Key",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsInternal)this).Key, global::System.Convert.ToString);
}
if (content.Contains("TriggerUrl"))
{
((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsInternal)this).TriggerUrl = (string) content.GetValueForProperty("TriggerUrl",((Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IFunctionSecretsInternal)this).TriggerUrl, global::System.Convert.ToString);
}
AfterDeserializePSObject(content);
}
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Function secrets.
[System.ComponentModel.TypeConverter(typeof(FunctionSecretsTypeConverter))]
public partial interface IFunctionSecrets
{
}
} | 70.052632 | 480 | 0.692036 | [
"MIT"
] | Agazoth/azure-powershell | src/Functions/generated/api/Models/Api20190801/FunctionSecrets.PowerShell.cs | 13,121 | C# |
using System.Collections.Generic;
using System.Formats.Asn1;
using Xunit;
namespace Codemations.Asn1.Tests
{
public class AsnExtensionsTests
{
public static IEnumerable<object[]> Data
{
get
{
yield return new object[] {new Asn1Tag(TagClass.ContextSpecific, 0x00, false), 0x80};
yield return new object[] {new Asn1Tag(TagClass.ContextSpecific, 0x1F, false), 0x9F};
yield return new object[] {new Asn1Tag(TagClass.ContextSpecific, 0x00, true), 0xA0};
yield return new object[] {new Asn1Tag(TagClass.ContextSpecific, 0x1F, true), 0xBF};
yield return new object[] {new Asn1Tag(TagClass.Universal, 0x00, false), 0x00};
yield return new object[] {new Asn1Tag(TagClass.Universal, 0x1F, false), 0x1F};
yield return new object[] {new Asn1Tag(TagClass.Private, 0x00, true), 0xE0};
yield return new object[] {new Asn1Tag(TagClass.Private, 0x1F, true), 0xFF};
}
}
[Theory]
[MemberData(nameof(Data))]
public void ShouldConvertTagToByte(Asn1Tag asn1Tag, byte expectedTag)
{
// Act
var actualTag = asn1Tag.ToByte();
// Assert
Assert.Equal(expectedTag, actualTag);
}
[Theory]
[MemberData(nameof(Data))]
public void ShouldConvertByteToTag(Asn1Tag expectedAsn1Tag, byte tag)
{
// Act
var actualAsn1Tag = tag.ToAsn1Tag();
// Assert
Assert.Equal(expectedAsn1Tag, actualAsn1Tag);
}
}
} | 35.782609 | 101 | 0.586877 | [
"MIT"
] | aprochwicz/AP.Asn1 | tests/Codemations.Asn1.Tests/AsnExtensionsTests.cs | 1,648 | C# |
using System.Linq;
using Ncqrs.Eventing.Sourcing;
using Xunit;
namespace Ncqrs.Eventing.Storage.NoDB.Tests.EventStoreTests
{
public class when_getting_the_events_since_a_specific_version : NoDBEventStoreTestFixture
{
private object[] _returnedEvents;
[Theory, InlineData(0), InlineData(1), InlineData(2), InlineData(3)]
public void it_should_return_the_events_since_version(int version)
{
_returnedEvents = EventStore.ReadFrom(EventSourceId, version, long.MaxValue).Select(x => x.Payload).ToArray();
for (int i = 0; i < _returnedEvents.Length; i++)
{
Assert.Equal(_returnedEvents[i], Events[i + version]);
}
}
}
} | 35.809524 | 123 | 0.646277 | [
"Apache-2.0"
] | adamcogx/ncqrs | Framework/src/Ncqrs.Tests/Eventing/Storage/NoDB/EventStoreTests/when_getting_the_events_since_a_specific_version.cs | 754 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceModel;
namespace Workday.FinancialManagement
{
[GeneratedCode("System.ServiceModel", "4.0.0.0"), EditorBrowsable(EditorBrowsableState.Advanced), DebuggerStepThrough, MessageContract(IsWrapped = false)]
public class Get_OrganizationsOutput
{
[MessageBodyMember(Namespace = "urn:com.workday/bsvc", Order = 0)]
public Get_Organizations_ResponseType Get_Organizations_Response;
public Get_OrganizationsOutput()
{
}
public Get_OrganizationsOutput(Get_Organizations_ResponseType Get_Organizations_Response)
{
this.Get_Organizations_Response = Get_Organizations_Response;
}
}
}
| 28.68 | 155 | 0.81311 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.FinancialManagement/Get_OrganizationsOutput.cs | 717 | C# |
namespace Aris.Moe.OverlayTranslate.Server.Image.Fetching.Error
{
public class ExternalServerError : CorrelatedError
{
public ExternalServerError() : base("Failed to load the image due to an error on the target server that hosts the image. Maybe try again later?")
{
}
}
} | 34.333333 | 153 | 0.692557 | [
"MIT"
] | Amiron49/Aris.Moe.Ocr.Translation.Overlay | Aris.Moe.OverlayTranslate.Server/Image/Fetching/Error/ExternalServerError.cs | 311 | C# |
namespace Reportr.Components
{
using Reportr.Components.Collections;
using Reportr.Components.Graphics;
using Reportr.Components.Metrics;
using Reportr.Components.Separators;
using System;
/// <summary>
/// Various extension methods for the report component type enum
/// </summary>
internal static class ReportComponentTypeExtensions
{
/// <summary>
/// Gets a component generator for the report component type
/// </summary>
/// <param name="componentType">The component type</param>
/// <returns>The component generator</returns>
public static IReportComponentGenerator GetGenerator
(
this ReportComponentType componentType
)
{
switch (componentType)
{
case ReportComponentType.Chart:
return new ChartGenerator();
case ReportComponentType.Graphic:
return new GraphicGenerator();
case ReportComponentType.Statistic:
return new StatisticGenerator();
case ReportComponentType.Repeater:
return new RepeaterGenerator();
case ReportComponentType.Table:
return new TableGenerator();
case ReportComponentType.Separator:
return new SeparatorGenerator();
default:
throw new InvalidOperationException
(
$"The component type {componentType} is not supported."
);
}
}
}
}
| 31.584906 | 79 | 0.557945 | [
"MIT"
] | JTOne123/Reportr | src/Reportr/Components/ReportComponentTypeExtensions.cs | 1,676 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace SendIt.Areas.HelpPage.ModelDescriptions
{
public class ParameterDescription
{
public ParameterDescription()
{
Annotations = new Collection<ParameterAnnotation>();
}
public Collection<ParameterAnnotation> Annotations { get; private set; }
public string Documentation { get; set; }
public string Name { get; set; }
public ModelDescription TypeDescription { get; set; }
}
} | 25.571429 | 80 | 0.674115 | [
"Unlicense",
"MIT"
] | truekasun/SendIt | SendIt/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs | 537 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ScreenSystemLibrary;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;
namespace TowerDefense
{
public class HelpScreen : GameScreen
{
GameScreen screenBefore;
SpriteFont font;
List<Texture2D> helpTextures;
int helpTexturesCount;
int index;
public override bool AcceptsInput
{
get { return true; }
}
public HelpScreen(GameScreen before)
{
screenBefore = before;
}
public override void InitializeScreen()
{
InputMap.NewAction("Finished", Microsoft.Xna.Framework.Input.Keys.Escape);
InputMap.NewAction("Next", Microsoft.Xna.Framework.Input.Keys.Space);
helpTexturesCount = 3;
index = 0;
helpTextures = new List<Texture2D>(helpTexturesCount);
EnableFade(Color.Black, 0.85f);
}
public override void LoadContent()
{
ContentManager content = ScreenSystem.Content;
font = content.Load<SpriteFont>(@"Fonts/help");
for (int i = 0; i < helpTexturesCount; i++)
{
helpTextures.Add(content.Load<Texture2D>(String.Format("Textures\\Help\\help_{0}", i + 1)));
}
}
protected override void DrawScreen(GameTime gameTime)
{
SpriteBatch spriteBatch = ScreenSystem.SpriteBatch;
spriteBatch.Draw(helpTextures[index], new Rectangle(0, 0, 1280, 720), Color.White);
spriteBatch.DrawString(font, "Press Space to advance to the next image", Vector2.Zero, Color.Red);
}
protected override void UpdateScreen(GameTime gameTime)
{
if (InputMap.NewActionPress("Finished"))
{
ExitScreen();
screenBefore.ActivateScreen();
}
if (InputMap.NewActionPress("Next"))
{
if (index >= (helpTextures.Count - 1))
index = 0;
else
index++;
}
}
}
}
| 28.43038 | 110 | 0.569457 | [
"MIT"
] | PHStudios/TowerDefense-Legacy | TowerDefense/TowerDefense/TowerDefense/Screens/HelpScreen.cs | 2,248 | C# |
using Newtonsoft.Json;
namespace MailChimp.Net.Models
{
public class MemberStats
{
[JsonProperty("avg_open_rate")]
public double AverageOpenRate { get; set; }
[JsonProperty("avg_click_rate")]
public double AverageClickRate { get; set; }
}
}
| 22.076923 | 52 | 0.648084 | [
"MIT"
] | Argenteneo/MailChimp.Net | MailChimp.Net/Models/MemberStats.cs | 289 | C# |
using BasicTestApp.Client;
using Blazorise.Tests.Helpers;
using Bunit;
using Xunit;
namespace Blazorise.Tests.Components
{
public class TextEditComponentTest : ComponentTestFixture
{
public TextEditComponentTest()
{
BlazoriseConfig.AddBootstrapProviders( Services );
}
[Fact]
public void CanChangeText()
{
// setup
var comp = RenderComponent<TextEditComponent>();
var paragraph = comp.Find( "#text-basic" );
var text = comp.Find( "input" );
Assert.Null( text.GetAttribute( "value" ) );
// test
text.Input( "abc" );
// validate
Assert.Contains( "abc", text.GetAttribute( "value" ) );
}
[Fact]
public void CanChangeTextUsingEvent()
{
// setup
var comp = RenderComponent<TextEditComponent>();
var paragraph = comp.Find( "#text-event-initially-blank" );
var text = comp.Find( "#text-with-event" );
var result = comp.Find( "#text-event-initially-blank-result" );
Assert.Equal( string.Empty, result.InnerHtml );
// test initial
text.Input( "abcde" );
Assert.Equal( "abcde", result.InnerHtml );
// test additional text
text.Input( "abcdefghijklmnopqrstuvwxyz" );
Assert.Equal( "abcdefghijklmnopqrstuvwxyz", result.InnerHtml );
// text backspace.
// todo: figure out how to set special keys.
// text.KeyPress( "Keys.Backspace" );
// Assert.Equal( "abcdefghijklmnopqrstuvwxy", result.InnerHtml );
}
[Fact]
public void CanChangeTextUsingBind()
{
// setup
var comp = RenderComponent<TextEditComponent>();
var paragraph = comp.Find( "#text-bind-initially-blank" );
var text = comp.Find( "#text-binding" );
var result = comp.Find( "#text-bind-initially-blank-result" );
Assert.Equal( string.Empty, result.InnerHtml );
// test additional text
text.Input( "abcdefghijklmnopqrstuvwxyz" );
Assert.Equal( "abcdefghijklmnopqrstuvwxyz", result.InnerHtml );
// text backspace.
// todo: figure out how to set special keys.
// text.KeyPress( "Keys.Backspace" );
// Assert.Equal( "abcdefghijklmnopqrstuvwxy", result.InnerHtml );
}
}
} | 32.371795 | 77 | 0.558812 | [
"MIT"
] | AhmedHemdan21/Blazorise | Tests/Blazorise.Tests/Components/TextEditComponentTest.cs | 2,527 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace NnCase.Designer.Modules.GraphEditor.Controls
{
public class ElementItemsControl : ListBox
{
protected override DependencyObject GetContainerForItemOverride()
{
return new ElementItem();
}
protected override bool IsItemItsOwnContainerOverride(object item)
{
return item is ElementItem;
}
public ElementItemsControl()
{
SelectionMode = SelectionMode.Extended;
}
}
}
| 23 | 74 | 0.670165 | [
"Apache-2.0"
] | svija/nncase | src/NnCase.Designer.Modules.GraphEditor/Controls/ElementItemsControl.cs | 669 | 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("Lift_ver2.0")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lift_ver2.0")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8a12d684-a0dc-4d35-a5af-813d5647e0ce")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.567568 | 84 | 0.746043 | [
"MIT"
] | DevStrikerTech/Elevator-Control-System | Lift_ver2.0/Properties/AssemblyInfo.cs | 1,393 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text;
using Silk.NET.Core;
using Silk.NET.Core.Native;
using Silk.NET.Core.Attributes;
using Silk.NET.Core.Contexts;
using Silk.NET.Core.Loader;
#pragma warning disable 1591
namespace Silk.NET.DXGI
{
[Guid("770aae78-f26f-4dba-a829-253c83d1b387")]
[NativeName("Name", "IDXGIFactory1")]
public unsafe partial struct IDXGIFactory1
{
public static readonly Guid Guid = new("770aae78-f26f-4dba-a829-253c83d1b387");
public static implicit operator IDXGIFactory(IDXGIFactory1 val)
=> Unsafe.As<IDXGIFactory1, IDXGIFactory>(ref val);
public static implicit operator IDXGIObject(IDXGIFactory1 val)
=> Unsafe.As<IDXGIFactory1, IDXGIObject>(ref val);
public static implicit operator Silk.NET.Core.Native.IUnknown(IDXGIFactory1 val)
=> Unsafe.As<IDXGIFactory1, Silk.NET.Core.Native.IUnknown>(ref val);
public IDXGIFactory1
(
void** lpVtbl = null
) : this()
{
if (lpVtbl is not null)
{
LpVtbl = lpVtbl;
}
}
[NativeName("Type", "")]
[NativeName("Type.Name", "")]
[NativeName("Name", "lpVtbl")]
public void** LpVtbl;
/// <summary>To be documented.</summary>
public readonly unsafe int QueryInterface(Guid* riid, void** ppvObject)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, void**, int>)LpVtbl[0])(@this, riid, ppvObject);
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int QueryInterface(Guid* riid, ref void* ppvObject)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (void** ppvObjectPtr = &ppvObject)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, void**, int>)LpVtbl[0])(@this, riid, ppvObjectPtr);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int QueryInterface(ref Guid riid, void** ppvObject)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Guid* riidPtr = &riid)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, void**, int>)LpVtbl[0])(@this, riidPtr, ppvObject);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int QueryInterface(ref Guid riid, ref void* ppvObject)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Guid* riidPtr = &riid)
{
fixed (void** ppvObjectPtr = &ppvObject)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, void**, int>)LpVtbl[0])(@this, riidPtr, ppvObjectPtr);
}
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly uint AddRef()
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
uint ret = default;
ret = ((delegate* unmanaged[Stdcall]<IDXGIFactory1*, uint>)LpVtbl[1])(@this);
return ret;
}
/// <summary>To be documented.</summary>
public readonly uint Release()
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
uint ret = default;
ret = ((delegate* unmanaged[Stdcall]<IDXGIFactory1*, uint>)LpVtbl[2])(@this);
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int SetPrivateData(Guid* Name, uint DataSize, void* pData)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, uint, void*, int>)LpVtbl[3])(@this, Name, DataSize, pData);
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int SetPrivateData<T0>(Guid* Name, uint DataSize, ref T0 pData) where T0 : unmanaged
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (void* pDataPtr = &pData)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, uint, void*, int>)LpVtbl[3])(@this, Name, DataSize, pDataPtr);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int SetPrivateData(ref Guid Name, uint DataSize, void* pData)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Guid* NamePtr = &Name)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, uint, void*, int>)LpVtbl[3])(@this, NamePtr, DataSize, pData);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly int SetPrivateData<T0>(ref Guid Name, uint DataSize, ref T0 pData) where T0 : unmanaged
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Guid* NamePtr = &Name)
{
fixed (void* pDataPtr = &pData)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, uint, void*, int>)LpVtbl[3])(@this, NamePtr, DataSize, pDataPtr);
}
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int SetPrivateDataInterface(Guid* Name, [Flow(FlowDirection.In)] Silk.NET.Core.Native.IUnknown* pUnknown)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[4])(@this, Name, pUnknown);
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int SetPrivateDataInterface(Guid* Name, [Flow(FlowDirection.In)] in Silk.NET.Core.Native.IUnknown pUnknown)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Silk.NET.Core.Native.IUnknown* pUnknownPtr = &pUnknown)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[4])(@this, Name, pUnknownPtr);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int SetPrivateDataInterface(ref Guid Name, [Flow(FlowDirection.In)] Silk.NET.Core.Native.IUnknown* pUnknown)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Guid* NamePtr = &Name)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[4])(@this, NamePtr, pUnknown);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly int SetPrivateDataInterface(ref Guid Name, [Flow(FlowDirection.In)] in Silk.NET.Core.Native.IUnknown pUnknown)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Guid* NamePtr = &Name)
{
fixed (Silk.NET.Core.Native.IUnknown* pUnknownPtr = &pUnknown)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, Silk.NET.Core.Native.IUnknown*, int>)LpVtbl[4])(@this, NamePtr, pUnknownPtr);
}
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int GetPrivateData(Guid* Name, uint* pDataSize, void* pData)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, uint*, void*, int>)LpVtbl[5])(@this, Name, pDataSize, pData);
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int GetPrivateData<T0>(Guid* Name, uint* pDataSize, ref T0 pData) where T0 : unmanaged
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (void* pDataPtr = &pData)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, uint*, void*, int>)LpVtbl[5])(@this, Name, pDataSize, pDataPtr);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int GetPrivateData(Guid* Name, ref uint pDataSize, void* pData)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (uint* pDataSizePtr = &pDataSize)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, uint*, void*, int>)LpVtbl[5])(@this, Name, pDataSizePtr, pData);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int GetPrivateData<T0>(Guid* Name, ref uint pDataSize, ref T0 pData) where T0 : unmanaged
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (uint* pDataSizePtr = &pDataSize)
{
fixed (void* pDataPtr = &pData)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, uint*, void*, int>)LpVtbl[5])(@this, Name, pDataSizePtr, pDataPtr);
}
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int GetPrivateData(ref Guid Name, uint* pDataSize, void* pData)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Guid* NamePtr = &Name)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, uint*, void*, int>)LpVtbl[5])(@this, NamePtr, pDataSize, pData);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int GetPrivateData<T0>(ref Guid Name, uint* pDataSize, ref T0 pData) where T0 : unmanaged
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Guid* NamePtr = &Name)
{
fixed (void* pDataPtr = &pData)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, uint*, void*, int>)LpVtbl[5])(@this, NamePtr, pDataSize, pDataPtr);
}
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int GetPrivateData(ref Guid Name, ref uint pDataSize, void* pData)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Guid* NamePtr = &Name)
{
fixed (uint* pDataSizePtr = &pDataSize)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, uint*, void*, int>)LpVtbl[5])(@this, NamePtr, pDataSizePtr, pData);
}
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly int GetPrivateData<T0>(ref Guid Name, ref uint pDataSize, ref T0 pData) where T0 : unmanaged
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Guid* NamePtr = &Name)
{
fixed (uint* pDataSizePtr = &pDataSize)
{
fixed (void* pDataPtr = &pData)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, uint*, void*, int>)LpVtbl[5])(@this, NamePtr, pDataSizePtr, pDataPtr);
}
}
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int GetParent(Guid* riid, void** ppParent)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, void**, int>)LpVtbl[6])(@this, riid, ppParent);
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int GetParent(Guid* riid, ref void* ppParent)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (void** ppParentPtr = &ppParent)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, void**, int>)LpVtbl[6])(@this, riid, ppParentPtr);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int GetParent(ref Guid riid, void** ppParent)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Guid* riidPtr = &riid)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, void**, int>)LpVtbl[6])(@this, riidPtr, ppParent);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int GetParent(ref Guid riid, ref void* ppParent)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Guid* riidPtr = &riid)
{
fixed (void** ppParentPtr = &ppParent)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Guid*, void**, int>)LpVtbl[6])(@this, riidPtr, ppParentPtr);
}
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int EnumAdapters(uint Adapter, Silk.NET.DXGI.IDXGIAdapter** ppAdapter)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, uint, Silk.NET.DXGI.IDXGIAdapter**, int>)LpVtbl[7])(@this, Adapter, ppAdapter);
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int EnumAdapters(uint Adapter, ref Silk.NET.DXGI.IDXGIAdapter* ppAdapter)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Silk.NET.DXGI.IDXGIAdapter** ppAdapterPtr = &ppAdapter)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, uint, Silk.NET.DXGI.IDXGIAdapter**, int>)LpVtbl[7])(@this, Adapter, ppAdapterPtr);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly int MakeWindowAssociation(nint WindowHandle, uint Flags)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, nint, uint, int>)LpVtbl[8])(@this, WindowHandle, Flags);
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int GetWindowAssociation(nint* pWindowHandle)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, nint*, int>)LpVtbl[9])(@this, pWindowHandle);
return ret;
}
/// <summary>To be documented.</summary>
public readonly int GetWindowAssociation(ref nint pWindowHandle)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (nint* pWindowHandlePtr = &pWindowHandle)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, nint*, int>)LpVtbl[9])(@this, pWindowHandlePtr);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int CreateSwapChain(Silk.NET.Core.Native.IUnknown* pDevice, SwapChainDesc* pDesc, Silk.NET.DXGI.IDXGISwapChain** ppSwapChain)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Silk.NET.Core.Native.IUnknown*, SwapChainDesc*, Silk.NET.DXGI.IDXGISwapChain**, int>)LpVtbl[10])(@this, pDevice, pDesc, ppSwapChain);
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int CreateSwapChain(Silk.NET.Core.Native.IUnknown* pDevice, SwapChainDesc* pDesc, ref Silk.NET.DXGI.IDXGISwapChain* ppSwapChain)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Silk.NET.DXGI.IDXGISwapChain** ppSwapChainPtr = &ppSwapChain)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Silk.NET.Core.Native.IUnknown*, SwapChainDesc*, Silk.NET.DXGI.IDXGISwapChain**, int>)LpVtbl[10])(@this, pDevice, pDesc, ppSwapChainPtr);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int CreateSwapChain(Silk.NET.Core.Native.IUnknown* pDevice, ref SwapChainDesc pDesc, Silk.NET.DXGI.IDXGISwapChain** ppSwapChain)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (SwapChainDesc* pDescPtr = &pDesc)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Silk.NET.Core.Native.IUnknown*, SwapChainDesc*, Silk.NET.DXGI.IDXGISwapChain**, int>)LpVtbl[10])(@this, pDevice, pDescPtr, ppSwapChain);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int CreateSwapChain(Silk.NET.Core.Native.IUnknown* pDevice, ref SwapChainDesc pDesc, ref Silk.NET.DXGI.IDXGISwapChain* ppSwapChain)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (SwapChainDesc* pDescPtr = &pDesc)
{
fixed (Silk.NET.DXGI.IDXGISwapChain** ppSwapChainPtr = &ppSwapChain)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Silk.NET.Core.Native.IUnknown*, SwapChainDesc*, Silk.NET.DXGI.IDXGISwapChain**, int>)LpVtbl[10])(@this, pDevice, pDescPtr, ppSwapChainPtr);
}
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int CreateSwapChain(ref Silk.NET.Core.Native.IUnknown pDevice, SwapChainDesc* pDesc, Silk.NET.DXGI.IDXGISwapChain** ppSwapChain)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Silk.NET.Core.Native.IUnknown* pDevicePtr = &pDevice)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Silk.NET.Core.Native.IUnknown*, SwapChainDesc*, Silk.NET.DXGI.IDXGISwapChain**, int>)LpVtbl[10])(@this, pDevicePtr, pDesc, ppSwapChain);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int CreateSwapChain(ref Silk.NET.Core.Native.IUnknown pDevice, SwapChainDesc* pDesc, ref Silk.NET.DXGI.IDXGISwapChain* ppSwapChain)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Silk.NET.Core.Native.IUnknown* pDevicePtr = &pDevice)
{
fixed (Silk.NET.DXGI.IDXGISwapChain** ppSwapChainPtr = &ppSwapChain)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Silk.NET.Core.Native.IUnknown*, SwapChainDesc*, Silk.NET.DXGI.IDXGISwapChain**, int>)LpVtbl[10])(@this, pDevicePtr, pDesc, ppSwapChainPtr);
}
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int CreateSwapChain(ref Silk.NET.Core.Native.IUnknown pDevice, ref SwapChainDesc pDesc, Silk.NET.DXGI.IDXGISwapChain** ppSwapChain)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Silk.NET.Core.Native.IUnknown* pDevicePtr = &pDevice)
{
fixed (SwapChainDesc* pDescPtr = &pDesc)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Silk.NET.Core.Native.IUnknown*, SwapChainDesc*, Silk.NET.DXGI.IDXGISwapChain**, int>)LpVtbl[10])(@this, pDevicePtr, pDescPtr, ppSwapChain);
}
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int CreateSwapChain(ref Silk.NET.Core.Native.IUnknown pDevice, ref SwapChainDesc pDesc, ref Silk.NET.DXGI.IDXGISwapChain* ppSwapChain)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Silk.NET.Core.Native.IUnknown* pDevicePtr = &pDevice)
{
fixed (SwapChainDesc* pDescPtr = &pDesc)
{
fixed (Silk.NET.DXGI.IDXGISwapChain** ppSwapChainPtr = &ppSwapChain)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, Silk.NET.Core.Native.IUnknown*, SwapChainDesc*, Silk.NET.DXGI.IDXGISwapChain**, int>)LpVtbl[10])(@this, pDevicePtr, pDescPtr, ppSwapChainPtr);
}
}
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int CreateSoftwareAdapter(nint Module, Silk.NET.DXGI.IDXGIAdapter** ppAdapter)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, nint, Silk.NET.DXGI.IDXGIAdapter**, int>)LpVtbl[11])(@this, Module, ppAdapter);
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int CreateSoftwareAdapter(nint Module, ref Silk.NET.DXGI.IDXGIAdapter* ppAdapter)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (Silk.NET.DXGI.IDXGIAdapter** ppAdapterPtr = &ppAdapter)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, nint, Silk.NET.DXGI.IDXGIAdapter**, int>)LpVtbl[11])(@this, Module, ppAdapterPtr);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int EnumAdapters1(uint Adapter, IDXGIAdapter1** ppAdapter)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, uint, IDXGIAdapter1**, int>)LpVtbl[12])(@this, Adapter, ppAdapter);
return ret;
}
/// <summary>To be documented.</summary>
public readonly unsafe int EnumAdapters1(uint Adapter, ref IDXGIAdapter1* ppAdapter)
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
fixed (IDXGIAdapter1** ppAdapterPtr = &ppAdapter)
{
ret = ((delegate* unmanaged[Cdecl]<IDXGIFactory1*, uint, IDXGIAdapter1**, int>)LpVtbl[12])(@this, Adapter, ppAdapterPtr);
}
return ret;
}
/// <summary>To be documented.</summary>
public readonly int IsCurrent()
{
var @this = (IDXGIFactory1*) Unsafe.AsPointer(ref Unsafe.AsRef(in this));
int ret = default;
ret = ((delegate* unmanaged[Stdcall]<IDXGIFactory1*, int>)LpVtbl[13])(@this);
return ret;
}
}
}
| 44.405172 | 217 | 0.570142 | [
"MIT"
] | Zellcore/Silk.NET | src/Microsoft/Silk.NET.DXGI/Structs/IDXGIFactory1.gen.cs | 25,755 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// AlipayMarketingVoucherTemplateDeleteModel Data Structure.
/// </summary>
[Serializable]
public class AlipayMarketingVoucherTemplateDeleteModel : AopObject
{
/// <summary>
/// 券模板 id,可通过<a href="https://opendocs.alipay.com/apis/api_5/alipay.marketing.voucher.templatelist.query">alipay.marketing.voucher.templatelist.query</a>(查询券模板列表)接口查询获取。
/// </summary>
[XmlElement("template_id")]
public string TemplateId { get; set; }
}
}
| 31.894737 | 179 | 0.658416 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Domain/AlipayMarketingVoucherTemplateDeleteModel.cs | 648 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _14.LINQ_Filtering_operator
{
class Program
{
static void Main(string[] args)
{
// 1. Datasource
List<string> names = new List<string>() {
"John",
"Jacky",
"Monica",
"Jason",
"John",
"Monica",
"Monika",
"Jon",
"Bdandon",
"Chris",
"Monicanson"
};
// 2. Linq query
var query1 = (from n in names
where n.Contains("Mon")
select n).Distinct();
// 2.1 Method query
var query2 = names.Where(x => x.Contains("Mon")).Distinct();
// 3. Execution
foreach (var i in query2)
Console.WriteLine(i);
Console.ReadKey();
}
}
}
| 22.659091 | 72 | 0.44333 | [
"Apache-2.0"
] | VanchoDimitrov/Linq | 14.LINQ-Filtering-operator/Program.cs | 999 | C# |
using System.Collections.Generic;
using Tools;
using UnityEngine;
namespace LD47
{
[CreateAssetMenu(menuName = "LD47/Managers/Instruction Manager")]
public class InstructionManager : ScriptableManager
{
[SerializeField]
private List<Instruction> _instructions = null;
private int _currentInstructionIndex = 0;
public override void Initialize()
{
_currentInstructionIndex = 0;
}
public bool Validate(InstructionAction action)
{
Instruction current = GetCurrentInstruction();
// Invalid action
if (current == null)
{
return false;
}
// Incorrect instruction
if (current.requiredAction != action)
{
return false;
}
// Execute action
current.completionAction?.Execute();
// Go to next action
_currentInstructionIndex++;
// Notifiy listeners (UI)
EventManager.Instance.Trigger(GameplayEvent.InstructionCompleted);
return true;
}
public List<Instruction> GetInstructions()
{
return _instructions;
}
public Instruction GetCurrentInstruction()
{
if (_currentInstructionIndex >= _instructions.Count)
{
return null;
}
return _instructions[_currentInstructionIndex];
}
}
}
| 24.8125 | 79 | 0.531486 | [
"MIT"
] | LRP500/LD47 | Assets/Scripts/Instruction/InstructionManager.cs | 1,590 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lm.Comol.Modules.EduPath.Domain
{
[Serializable]
public class dtoActivity:dtoGenericItem
{
public bool isRuleChecked { get; set; }
public StatusStatistic statusStat { get; set; }
public IList<dtoSubActivity> SubActivities { get; set; }
public DateTime? EndDate { get; set; }
public DateTime? StartDate { get; set; }
public virtual Boolean isQuiz { get; set; }
public dtoActivity()
:base()
{
SubActivities = new List<dtoSubActivity>();
isRuleChecked = false;
EndDate = null;
StartDate = null;
}
public dtoActivity(Activity oActivity, Status PersonalStatus, RoleEP RoleEP, bool isRuleChecked)
:base(oActivity,PersonalStatus,RoleEP)
{
SubActivities = new List<dtoSubActivity>();
this.isRuleChecked = isRuleChecked;
EndDate = oActivity.EndDate;
StartDate = oActivity.StartDate;
isQuiz = oActivity.isQuiz;
}
public dtoActivity(Activity oActivity, Status PersonalStatus, RoleEP RoleEP, bool isRuleChecked, IList<dtoSubActivity> SubActivities)
: base(oActivity,PersonalStatus, RoleEP)
{
this.SubActivities = SubActivities;
this.isRuleChecked = isRuleChecked;
EndDate = oActivity.EndDate;
StartDate = oActivity.StartDate;
isQuiz = oActivity.isQuiz;
}
}
}
| 31.074074 | 141 | 0.583433 | [
"MIT"
] | EdutechSRL/Adevico | 3-Business/3-Modules/lm.Comol.Modules.EduPath/Domain/DTO/dtoActivity.cs | 1,680 | C# |
namespace TIKSN.Progress
{
public class OperationProgressReport : ProgressReport
{
public OperationProgressReport(double percentComplete, string currentOperation = null,
string statusDescription = null) : base(percentComplete)
{
this.CurrentOperation = currentOperation;
this.StatusDescription = statusDescription;
}
public OperationProgressReport(int completed, int overall, string currentOperation = null,
string statusDescription = null) : base(completed, overall)
{
this.CurrentOperation = currentOperation;
this.StatusDescription = statusDescription;
}
public string CurrentOperation { get; set; }
//public string Activity { get; set; }
//public int ActivityId { get; }
//public int ParentActivityId { get; set; }
//public ProgressRecordType RecordType { get; set; }
public string StatusDescription { get; set; }
}
}
| 35.892857 | 98 | 0.648756 | [
"MIT"
] | tiksn/TIKSN-Framework | TIKSN.Core/Progress/OperationProgressReport.cs | 1,005 | C# |
// IsolatedStorageScope.cs
//
// This code was automatically generated from
// ECMA CLI XML Library Specification.
// Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)]
// Created: Wed, 5 Sep 2001 06:41:21 UTC
// Source file: all.xml
// URL: http://devresource.hp.com/devresource/Docs/TechPapers/CSharp/all.xml
//
// (C) 2001 Ximian, Inc. http://www.ximian.com
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// 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.
//
#if SCE_DISABLED
using System.Runtime.InteropServices;
namespace System.IO.IsolatedStorage {
[Flags]
[ComVisible (true)]
[Serializable]
public enum IsolatedStorageScope {
None = 0,
User = 1,
#if MOONLIGHT
// Available in Silverlight
Application = 32,
#else
Domain = 2,
Assembly = 4,
// Documented in "C# In A Nutshell"
Roaming = 8,
Machine = 16,
Application = 32
#endif
}
}
#endif
| 31.885246 | 78 | 0.73419 | [
"Apache-2.0"
] | OpenPSS/psm-mono | mcs/class/corlib/System.IO.IsolatedStorage/IsolatedStorageScope.cs | 1,945 | C# |
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using ServiceStack;
using ServiceStack.Configuration;
using System;
namespace Funq
{
public partial class Container : IResolver
{
public IContainerAdapter Adapter { get; set; }
/// <summary>
/// Register an autowired dependency
/// </summary>
/// <typeparam name="T"></typeparam>
public IRegistration<T> RegisterAutoWired<T>()
{
var serviceFactory = GenerateAutoWireFn<T>();
return this.Register(serviceFactory);
}
/// <summary>
/// Register an autowired dependency as a separate type
/// </summary>
/// <typeparam name="T"></typeparam>
public IRegistration<TAs> RegisterAutoWiredAs<T, TAs>()
where T : TAs
{
var serviceFactory = GenerateAutoWireFn<T>();
Func<Container, TAs> fn = c => serviceFactory(c);
return this.Register(fn);
}
/// <summary>
/// Alias for RegisterAutoWiredAs
/// </summary>
/// <typeparam name="T"></typeparam>
public IRegistration<TAs> RegisterAs<T, TAs>()
where T : TAs
{
return this.RegisterAutoWiredAs<T, TAs>();
}
/// <summary>
/// Auto-wires an existing instance,
/// ie all public properties are tried to be resolved.
/// </summary>
/// <param name="instance"></param>
public void AutoWire(object instance)
{
AutoWire(this, instance);
}
public object GetLazyResolver(params Type[] types) // returns Func<type>
{
var tryResolveGeneric = typeof(Container).GetMethods()
.First(x => x.Name == "ReverseLazyResolve"
&& x.GetGenericArguments().Length == types.Length
&& x.GetParameters().Length == 0);
var tryResolveMethod = tryResolveGeneric.MakeGenericMethod(types);
var instance = tryResolveMethod.Invoke(this, new object[0]);
return instance;
}
public Func<TService> ReverseLazyResolve<TService>()
{
return LazyResolve<TService>(null);
}
public Func<TArg, TService> ReverseLazyResolve<TArg, TService>()
{
Register<Func<TArg, TService>>(c => a => c.TryResolve<TService>());
return TryResolve<Func<TArg, TService>>();
}
public Func<TArg1, TArg2, TService> ReverseLazyResolve<TArg1, TArg2, TService>()
{
Register<Func<TArg1, TArg2, TService>>(c => (a1, a2) => c.TryResolve<TService>());
return TryResolve<Func<TArg1, TArg2, TService>>();
}
public Func<TArg1, TArg2, TArg3, TService> ReverseLazyResolve<TArg1, TArg2, TArg3, TService>()
{
Register<Func<TArg1, TArg2, TArg3, TService>>(c => (a1, a2, a3) => c.TryResolve<TService>());
return TryResolve<Func<TArg1, TArg2, TArg3, TService>>();
}
public bool Exists<TService>()
{
var entry = GetEntry<TService, Func<Container, TService>>(null, throwIfMissing:false);
return entry != null;
}
private Dictionary<Type, Action<object>[]> autoWireCache = new Dictionary<Type, Action<object>[]>();
private static MethodInfo GetResolveMethod(Type typeWithResolveMethod, Type serviceType)
{
var methodInfo = typeWithResolveMethod.GetMethod("Resolve", new Type[0]);
return methodInfo.MakeGenericMethod(new[] { serviceType });
}
public static ConstructorInfo GetConstructorWithMostParams(Type type)
{
return type.GetConstructors()
.OrderByDescending(x => x.GetParameters().Length)
.FirstOrDefault(ctor => !ctor.IsStatic);
}
public static HashSet<string> IgnorePropertyTypeFullNames = new HashSet<string>
{
"System.Web.Mvc.ViewDataDictionary", //overrides ViewBag set in Controller constructor
};
private static bool IsPublicWritableUserPropertyType(PropertyInfo pi)
{
return pi.CanWrite
&& !pi.PropertyType.IsValueType
&& pi.PropertyType != typeof(string)
&& !IgnorePropertyTypeFullNames.Contains(pi.PropertyType.FullName);
}
/// <summary>
/// Generates a function which creates and auto-wires <see cref="TService"/>.
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <param name="lambdaParam"></param>
/// <returns></returns>
public static Func<Container, TService> GenerateAutoWireFn<TService>()
{
var lambdaParam = Expression.Parameter(typeof(Container), "container");
var propertyResolveFn = typeof(Container).GetMethod("TryResolve", new Type[0]);
var memberBindings = typeof(TService).GetPublicProperties()
.Where(IsPublicWritableUserPropertyType)
.Select(x =>
Expression.Bind
(
x,
ResolveTypeExpression(propertyResolveFn, x.PropertyType, lambdaParam)
)
).ToArray();
var ctorResolveFn = typeof(Container).GetMethod("Resolve", new Type[0]);
return Expression.Lambda<Func<Container, TService>>
(
Expression.MemberInit
(
ConstructorExpression(ctorResolveFn, typeof(TService), lambdaParam),
memberBindings
),
lambdaParam
).Compile();
}
/// <summary>
/// Auto-wires an existing instance of a specific type.
/// The auto-wiring progress is also cached to be faster
/// when calling next time with the same type.
/// </summary>
/// <param name="instance"></param>
public void AutoWire(Container container, object instance)
{
var instanceType = instance.GetType();
var propertyResolveFn = typeof(Container).GetMethod("TryResolve", new Type[0]);
Action<object>[] setters;
if (!autoWireCache.TryGetValue(instanceType, out setters))
{
setters = instanceType.GetPublicProperties()
.Where(IsPublicWritableUserPropertyType)
.Select(x => GenerateAutoWireFnForProperty(container, propertyResolveFn, x, instanceType))
.ToArray();
//Support for multiple threads is needed
Dictionary<Type, Action<object>[]> snapshot, newCache;
do
{
snapshot = autoWireCache;
newCache = new Dictionary<Type, Action<object>[]>(autoWireCache);
newCache[instanceType] = setters;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref autoWireCache, newCache, snapshot), snapshot));
}
foreach (var setter in setters)
setter(instance);
}
private static Action<object> GenerateAutoWireFnForProperty(
Container container, MethodInfo propertyResolveFn, PropertyInfo property, Type instanceType)
{
var instanceParam = Expression.Parameter(typeof(object), "instance");
var containerParam = Expression.Constant(container);
Func<object, object> getter = Expression.Lambda<Func<object, object>>(
Expression.Call(
Expression.Convert(instanceParam, instanceType),
property.GetGetMethod()
),
instanceParam
).Compile();
Action<object> setter = Expression.Lambda<Action<object>>(
Expression.Call(
Expression.Convert(instanceParam, instanceType),
property.GetSetMethod(),
ResolveTypeExpression(propertyResolveFn, property.PropertyType, containerParam)
),
instanceParam
).Compile();
return obj =>
{
if (getter(obj) == null) setter(obj);
};
}
private static NewExpression ConstructorExpression(
MethodInfo resolveMethodInfo, Type type, Expression lambdaParam)
{
var ctorWithMostParameters = GetConstructorWithMostParams(type);
if (ctorWithMostParameters == null)
throw new Exception(ErrorMessages.ConstructorNotFoundForType.Fmt(type.Name));
var constructorParameterInfos = ctorWithMostParameters.GetParameters();
var regParams = constructorParameterInfos
.Select(pi => ResolveTypeExpression(resolveMethodInfo, pi.ParameterType, lambdaParam));
return Expression.New(ctorWithMostParameters, regParams.ToArray());
}
private static MethodCallExpression ResolveTypeExpression(
MethodInfo resolveFn, Type resolveType, Expression containerParam)
{
var method = resolveFn.MakeGenericMethod(resolveType);
return Expression.Call(containerParam, method);
}
public object TryResolve(Type type)
{
var mi = typeof(Container).GetMethods(BindingFlags.Public | BindingFlags.Instance)
.First(x => x.Name == "TryResolve" &&
x.GetGenericArguments().Length == 1 &&
x.GetParameters().Length == 0);
var genericMi = mi.MakeGenericMethod(type);
var instance = genericMi.Invoke(this, new object[0]);
return instance;
}
}
} | 39.21875 | 111 | 0.573207 | [
"Apache-2.0"
] | bodell/ServiceStack | src/ServiceStack/Funq/Container.Adapter.cs | 9,785 | C# |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
namespace osu.Game.Rulesets.RP.UI.GamePlay.Playfield.Layout.CommonDwawablePiece
{
/// <summary>
/// 顯示外框
/// </summary>
public class GlowPiece : Container
{
private readonly Sprite layer;
public GlowPiece()
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
Children = new[]
{
layer = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Blending = BlendingMode.Additive,
Alpha = 0.5f
}
};
}
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
layer.Texture = textures.Get(@"Play/osu/ring-glow@2x");
}
}
}
| 28.209302 | 103 | 0.548228 | [
"MIT"
] | akmvihfan/osu-RP | osu.Game.Rulesets.RP/UI/Piece/GlowPiece.cs | 1,223 | C# |
using System;
using System.Collections.Generic;
#nullable disable
namespace ZM_CS234N_Term_Project.Models
{
public partial class IngredientSubstitute
{
public int IngredientId { get; set; }
public int SubstituteIngredientId { get; set; }
public virtual Ingredient Ingredient { get; set; }
public virtual Ingredient SubstituteIngredient { get; set; }
}
}
| 23.647059 | 68 | 0.701493 | [
"Apache-2.0"
] | ZabienMcKeeLCC/ZM_CS234N_Term_Project | ZM_CS234N_Term_Project/Models/IngredientSubstitute.cs | 404 | C# |
namespace Calculator
{
partial class frmMain
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
this.lblHienThi = new System.Windows.Forms.Label();
this.btn = new System.Windows.Forms.Button();
this.btnXoa = new System.Windows.Forms.Button();
this.btn7 = new System.Windows.Forms.Button();
this.btn8 = new System.Windows.Forms.Button();
this.btn9 = new System.Windows.Forms.Button();
this.btnCong = new System.Windows.Forms.Button();
this.btnPhanTram = new System.Windows.Forms.Button();
this.btn4 = new System.Windows.Forms.Button();
this.btn5 = new System.Windows.Forms.Button();
this.btn6 = new System.Windows.Forms.Button();
this.btnTru = new System.Windows.Forms.Button();
this.btnCanBac2 = new System.Windows.Forms.Button();
this.btn1 = new System.Windows.Forms.Button();
this.btn3 = new System.Windows.Forms.Button();
this.btn2 = new System.Windows.Forms.Button();
this.btn0 = new System.Windows.Forms.Button();
this.btnNhan = new System.Windows.Forms.Button();
this.btnChia = new System.Windows.Forms.Button();
this.btnKetQua = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.menuStrip2 = new System.Windows.Forms.MenuStrip();
this.thôngTinToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.càiĐặtToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.button3 = new System.Windows.Forms.Button();
this.càiĐặtToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.menuStrip2.SuspendLayout();
this.SuspendLayout();
//
// lblHienThi
//
this.lblHienThi.BackColor = System.Drawing.SystemColors.ScrollBar;
this.lblHienThi.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblHienThi.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblHienThi.Location = new System.Drawing.Point(31, 34);
this.lblHienThi.Name = "lblHienThi";
this.lblHienThi.Size = new System.Drawing.Size(256, 39);
this.lblHienThi.TabIndex = 0;
this.lblHienThi.Text = "0";
this.lblHienThi.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// btn
//
this.btn.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btn.Location = new System.Drawing.Point(29, 90);
this.btn.Name = "btn";
this.btn.Size = new System.Drawing.Size(98, 36);
this.btn.TabIndex = 1;
this.btn.Text = "Clear";
this.btn.UseVisualStyleBackColor = true;
this.btn.Click += new System.EventHandler(this.btn_Click);
//
// btnXoa
//
this.btnXoa.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnXoa.Location = new System.Drawing.Point(134, 90);
this.btnXoa.Name = "btnXoa";
this.btnXoa.Size = new System.Drawing.Size(153, 36);
this.btnXoa.TabIndex = 2;
this.btnXoa.Text = "Backspace";
this.btnXoa.UseVisualStyleBackColor = true;
this.btnXoa.Click += new System.EventHandler(this.btnXoa_Click);
//
// btn7
//
this.btn7.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btn7.Location = new System.Drawing.Point(29, 132);
this.btn7.Name = "btn7";
this.btn7.Size = new System.Drawing.Size(47, 43);
this.btn7.TabIndex = 3;
this.btn7.Text = "7";
this.btn7.UseVisualStyleBackColor = true;
this.btn7.Click += new System.EventHandler(this.NhapSo);
//
// btn8
//
this.btn8.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btn8.Location = new System.Drawing.Point(82, 132);
this.btn8.Name = "btn8";
this.btn8.Size = new System.Drawing.Size(47, 43);
this.btn8.TabIndex = 4;
this.btn8.Text = "8";
this.btn8.UseVisualStyleBackColor = true;
this.btn8.Click += new System.EventHandler(this.NhapSo);
//
// btn9
//
this.btn9.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btn9.Location = new System.Drawing.Point(134, 132);
this.btn9.Name = "btn9";
this.btn9.Size = new System.Drawing.Size(47, 43);
this.btn9.TabIndex = 5;
this.btn9.Text = "9";
this.btn9.UseVisualStyleBackColor = true;
this.btn9.Click += new System.EventHandler(this.NhapSo);
//
// btnCong
//
this.btnCong.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCong.Location = new System.Drawing.Point(187, 132);
this.btnCong.Name = "btnCong";
this.btnCong.Size = new System.Drawing.Size(47, 43);
this.btnCong.TabIndex = 6;
this.btnCong.Text = "+";
this.btnCong.UseVisualStyleBackColor = true;
this.btnCong.Click += new System.EventHandler(this.NhapPhepToan);
//
// btnPhanTram
//
this.btnPhanTram.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnPhanTram.Location = new System.Drawing.Point(134, 277);
this.btnPhanTram.Name = "btnPhanTram";
this.btnPhanTram.Size = new System.Drawing.Size(47, 43);
this.btnPhanTram.TabIndex = 7;
this.btnPhanTram.Text = "%";
this.btnPhanTram.UseVisualStyleBackColor = true;
this.btnPhanTram.Click += new System.EventHandler(this.NhapPhepToan);
//
// btn4
//
this.btn4.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btn4.Location = new System.Drawing.Point(29, 181);
this.btn4.Name = "btn4";
this.btn4.Size = new System.Drawing.Size(47, 43);
this.btn4.TabIndex = 8;
this.btn4.Text = "4";
this.btn4.UseVisualStyleBackColor = true;
this.btn4.Click += new System.EventHandler(this.NhapSo);
//
// btn5
//
this.btn5.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btn5.Location = new System.Drawing.Point(82, 181);
this.btn5.Name = "btn5";
this.btn5.Size = new System.Drawing.Size(47, 43);
this.btn5.TabIndex = 9;
this.btn5.Text = "5";
this.btn5.UseVisualStyleBackColor = true;
this.btn5.Click += new System.EventHandler(this.NhapSo);
//
// btn6
//
this.btn6.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btn6.Location = new System.Drawing.Point(134, 181);
this.btn6.Name = "btn6";
this.btn6.Size = new System.Drawing.Size(47, 43);
this.btn6.TabIndex = 10;
this.btn6.Text = "6";
this.btn6.UseVisualStyleBackColor = true;
this.btn6.Click += new System.EventHandler(this.NhapSo);
//
// btnTru
//
this.btnTru.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnTru.Location = new System.Drawing.Point(187, 181);
this.btnTru.Name = "btnTru";
this.btnTru.Size = new System.Drawing.Size(48, 43);
this.btnTru.TabIndex = 11;
this.btnTru.Text = "-";
this.btnTru.UseVisualStyleBackColor = true;
this.btnTru.Click += new System.EventHandler(this.NhapPhepToan);
//
// btnCanBac2
//
this.btnCanBac2.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCanBac2.Location = new System.Drawing.Point(240, 277);
this.btnCanBac2.Name = "btnCanBac2";
this.btnCanBac2.Size = new System.Drawing.Size(47, 43);
this.btnCanBac2.TabIndex = 12;
this.btnCanBac2.Text = "√";
this.btnCanBac2.UseVisualStyleBackColor = true;
this.btnCanBac2.Click += new System.EventHandler(this.NhapPhepToan);
//
// btn1
//
this.btn1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btn1.Location = new System.Drawing.Point(29, 230);
this.btn1.Name = "btn1";
this.btn1.Size = new System.Drawing.Size(47, 43);
this.btn1.TabIndex = 13;
this.btn1.Text = "1";
this.btn1.UseVisualStyleBackColor = true;
this.btn1.Click += new System.EventHandler(this.NhapSo);
//
// btn3
//
this.btn3.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btn3.Location = new System.Drawing.Point(134, 230);
this.btn3.Name = "btn3";
this.btn3.Size = new System.Drawing.Size(47, 43);
this.btn3.TabIndex = 14;
this.btn3.Text = "3";
this.btn3.UseVisualStyleBackColor = true;
this.btn3.Click += new System.EventHandler(this.NhapSo);
//
// btn2
//
this.btn2.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btn2.Location = new System.Drawing.Point(82, 230);
this.btn2.Name = "btn2";
this.btn2.Size = new System.Drawing.Size(47, 43);
this.btn2.TabIndex = 15;
this.btn2.Text = "2";
this.btn2.UseVisualStyleBackColor = true;
this.btn2.Click += new System.EventHandler(this.NhapSo);
//
// btn0
//
this.btn0.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btn0.Location = new System.Drawing.Point(29, 277);
this.btn0.Name = "btn0";
this.btn0.Size = new System.Drawing.Size(47, 43);
this.btn0.TabIndex = 16;
this.btn0.Text = "0";
this.btn0.UseVisualStyleBackColor = true;
this.btn0.Click += new System.EventHandler(this.NhapSo);
//
// btnNhan
//
this.btnNhan.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnNhan.Location = new System.Drawing.Point(187, 230);
this.btnNhan.Name = "btnNhan";
this.btnNhan.Size = new System.Drawing.Size(48, 43);
this.btnNhan.TabIndex = 18;
this.btnNhan.Text = "*";
this.btnNhan.UseVisualStyleBackColor = true;
this.btnNhan.Click += new System.EventHandler(this.NhapPhepToan);
//
// btnChia
//
this.btnChia.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnChia.Location = new System.Drawing.Point(188, 277);
this.btnChia.Name = "btnChia";
this.btnChia.Size = new System.Drawing.Size(47, 43);
this.btnChia.TabIndex = 19;
this.btnChia.Text = "/";
this.btnChia.UseVisualStyleBackColor = true;
this.btnChia.Click += new System.EventHandler(this.NhapPhepToan);
//
// btnKetQua
//
this.btnKetQua.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnKetQua.Location = new System.Drawing.Point(82, 328);
this.btnKetQua.Name = "btnKetQua";
this.btnKetQua.Size = new System.Drawing.Size(205, 43);
this.btnKetQua.TabIndex = 20;
this.btnKetQua.Text = "=";
this.btnKetQua.UseVisualStyleBackColor = true;
this.btnKetQua.Click += new System.EventHandler(this.btnKetQua_Click);
//
// button1
//
this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button1.Location = new System.Drawing.Point(82, 277);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(47, 43);
this.button1.TabIndex = 21;
this.button1.Text = ",";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button2.Location = new System.Drawing.Point(240, 132);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(47, 43);
this.button2.TabIndex = 23;
this.button2.Text = "Sin";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.NhapPhepToan);
//
// button5
//
this.button5.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button5.Location = new System.Drawing.Point(239, 181);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(48, 43);
this.button5.TabIndex = 26;
this.button5.Text = "Cos";
this.button5.UseVisualStyleBackColor = true;
this.button5.Click += new System.EventHandler(this.NhapPhepToan);
//
// button6
//
this.button6.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button6.Location = new System.Drawing.Point(239, 230);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(48, 43);
this.button6.TabIndex = 27;
this.button6.Text = "Tan";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.NhapPhepToan);
//
// menuStrip2
//
this.menuStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.thôngTinToolStripMenuItem,
this.càiĐặtToolStripMenuItem1,
this.càiĐặtToolStripMenuItem});
this.menuStrip2.Location = new System.Drawing.Point(0, 0);
this.menuStrip2.Name = "menuStrip2";
this.menuStrip2.Size = new System.Drawing.Size(322, 24);
this.menuStrip2.TabIndex = 28;
this.menuStrip2.Text = "Cài đặt";
//
// thôngTinToolStripMenuItem
//
this.thôngTinToolStripMenuItem.Name = "thôngTinToolStripMenuItem";
this.thôngTinToolStripMenuItem.Size = new System.Drawing.Size(70, 20);
this.thôngTinToolStripMenuItem.Text = "Thông tin";
this.thôngTinToolStripMenuItem.Click += new System.EventHandler(this.thôngTinToolStripMenuItem_Click);
//
// càiĐặtToolStripMenuItem
//
this.càiĐặtToolStripMenuItem.Name = "càiĐặtToolStripMenuItem";
this.càiĐặtToolStripMenuItem.Size = new System.Drawing.Size(49, 20);
this.càiĐặtToolStripMenuItem.Text = "Thoát";
this.càiĐặtToolStripMenuItem.Click += new System.EventHandler(this.càiĐặtToolStripMenuItem_Click);
//
// button3
//
this.button3.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button3.Location = new System.Drawing.Point(29, 328);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(47, 43);
this.button3.TabIndex = 29;
this.button3.Text = "^";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.NhapPhepToan);
//
// càiĐặtToolStripMenuItem1
//
this.càiĐặtToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem1});
this.càiĐặtToolStripMenuItem1.Name = "càiĐặtToolStripMenuItem1";
this.càiĐặtToolStripMenuItem1.Size = new System.Drawing.Size(56, 20);
this.càiĐặtToolStripMenuItem1.Text = "Cài đặt";
this.càiĐặtToolStripMenuItem1.Click += new System.EventHandler(this.càiĐặtToolStripMenuItem1_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(152, 22);
this.toolStripMenuItem1.Text = "Theme";
this.toolStripMenuItem1.Click += new System.EventHandler(this.toolStripMenuItem1_Click);
//
// frmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
this.ClientSize = new System.Drawing.Size(322, 394);
this.Controls.Add(this.button3);
this.Controls.Add(this.button6);
this.Controls.Add(this.button5);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.btnKetQua);
this.Controls.Add(this.btnChia);
this.Controls.Add(this.btnNhan);
this.Controls.Add(this.btn0);
this.Controls.Add(this.btn2);
this.Controls.Add(this.btn3);
this.Controls.Add(this.btn1);
this.Controls.Add(this.btnCanBac2);
this.Controls.Add(this.btnTru);
this.Controls.Add(this.btn6);
this.Controls.Add(this.btn5);
this.Controls.Add(this.btn4);
this.Controls.Add(this.btnPhanTram);
this.Controls.Add(this.btnCong);
this.Controls.Add(this.btn9);
this.Controls.Add(this.btn8);
this.Controls.Add(this.btn7);
this.Controls.Add(this.btnXoa);
this.Controls.Add(this.btn);
this.Controls.Add(this.lblHienThi);
this.Controls.Add(this.menuStrip2);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.KeyPreview = true;
this.MaximizeBox = false;
this.Name = "frmMain";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Calculator - Copyright Nguyễn Văn Giàu";
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.frmMain_KeyPress);
this.menuStrip2.ResumeLayout(false);
this.menuStrip2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblHienThi;
private System.Windows.Forms.Button btn;
private System.Windows.Forms.Button btnXoa;
private System.Windows.Forms.Button btn7;
private System.Windows.Forms.Button btn8;
private System.Windows.Forms.Button btn9;
private System.Windows.Forms.Button btnCong;
private System.Windows.Forms.Button btnPhanTram;
private System.Windows.Forms.Button btn4;
private System.Windows.Forms.Button btn5;
private System.Windows.Forms.Button btn6;
private System.Windows.Forms.Button btnTru;
private System.Windows.Forms.Button btnCanBac2;
private System.Windows.Forms.Button btn1;
private System.Windows.Forms.Button btn3;
private System.Windows.Forms.Button btn2;
private System.Windows.Forms.Button btn0;
private System.Windows.Forms.Button btnNhan;
private System.Windows.Forms.Button btnChia;
private System.Windows.Forms.Button btnKetQua;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.MenuStrip menuStrip2;
private System.Windows.Forms.ToolStripMenuItem thôngTinToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem càiĐặtToolStripMenuItem;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.ToolStripMenuItem càiĐặtToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1;
}
}
| 52.662366 | 171 | 0.598824 | [
"MIT"
] | vangiaurecca/Course_CSharp_Basic | Calculator/Calculator/Form1.Designer.cs | 24,600 | C# |
using AutoMapper;
using AutoMapper.Extensions.ExpressionMapping;
using DonateTo.ApplicationCore.Entities;
using DonateTo.ApplicationCore.Interfaces;
using DonateTo.ApplicationCore.Interfaces.Services;
using DonateTo.ApplicationCore.Models.Pagination;
using DonateTo.ApplicationCore.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using DonateTo.ApplicationCore.Models.Filtering;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System.Globalization;
namespace DonateTo.Services
{
public class LogService : ILogService
{
private readonly IRepository<Log> _logRepository;
private readonly IUnitOfWork _unitOfWork;
private readonly IMapper _mapper;
public LogService(
IRepository<Log> logRepository,
IUnitOfWork unitOfWork,
IMapper mapper)
{
_logRepository = logRepository;
_unitOfWork = unitOfWork;
_mapper = mapper;
}
///<inheritdoc cref="ILogService"/>
public IEnumerable<Log> Get(Expression<Func<Log, bool>> filter)
{
var filterDest = _mapper.MapExpression<Expression<Func<Log, bool>>>(filter);
return _logRepository.Get(filterDest);
}
///<inheritdoc cref="ILogService"/>
public async Task<IEnumerable<Log>> GetAsync(Expression<Func<Log, bool>> filter)
{
var filterDest = _mapper.MapExpression<Expression<Func<Log, bool>>>(filter);
return await _logRepository.GetAsync(filterDest).ConfigureAwait(false);
}
///<inheritdoc cref="ILogService"/>
public PagedResult<Log> GetPaged(int page, int pageSize, Expression<Func<Log, bool>> filter = null)
{
var filterDest = _mapper.MapExpression<Expression<Func<Log, bool>>>(filter);
return _logRepository.GetPaged(page, pageSize, filterDest);
}
///<inheritdoc cref="ILogService"/>
public async Task<PagedResult<Log>> GetPagedAsync(int page, int pageSize, Expression<Func<Log, bool>> filter = null)
{
var filterDest = _mapper.MapExpression<Expression<Func<Log, bool>>>(filter);
return await _logRepository.GetPagedAsync(page, pageSize, filterDest).ConfigureAwait(false);
}
///<inheritdoc cref="ILogService"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1307:Specify StringComparison", Justification = "<Pending>")]
public PagedResult<Log> GetPagedFiltered(LogFilterModel filter)
{
var predicate = GetPredicate(filter);
return _logRepository.GetPaged(filter.PageNumber, filter.PageSize, predicate, GetSort(filter));
}
///<inheritdoc cref="ILogService"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1307:Specify StringComparison", Justification = "<Pending>")]
public async Task<PagedResult<Log>> GetPagedFilteredAsync(LogFilterModel filter)
{
var predicate = GetPredicate(filter);
return await _logRepository.GetPagedAsync(filter.PageNumber, filter.PageSize, predicate, GetSort(filter)).ConfigureAwait(false);
}
#region private
/// <summary>
/// Returns sort string from filter model
/// Default is: timestamp descending
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "<Pending>")]
private string GetSort(LogFilterModel filter)
{
var properties = typeof(LogFilterModel).GetProperties();
//Converts to lower case as Log table has all lowercase fileds
//This code should not work for column names with "_" like: message_template or log_event
var sort = !string.IsNullOrEmpty(filter.OrderBy)
&& properties.Any(p => p.Name.ToUpperInvariant() == filter.OrderBy.ToUpperInvariant()) ?
$"{ filter.OrderBy.ToLowerInvariant() } " :
"timestamp ";
sort += !string.IsNullOrEmpty(filter.OrderDirection)
&& (filter.OrderDirection == SortDirection.Ascending || filter.OrderDirection == SortDirection.Ascend || filter.OrderDirection == SortDirection.Asc) ?
SortDirection.Ascending :
SortDirection.Descending;
return sort;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1307:Specify StringComparison", Justification = "<Pending>")]
private Expression<Func<Log, bool>> GetPredicate(LogFilterModel filter)
{
var predicate = PredicateBuilder.New<Log>(true);
if (!string.IsNullOrEmpty(filter.TimeStampBegin))
{
if (DateTime.TryParse(filter.TimeStampBegin, out var outDate))
{
predicate = predicate.And(p => p.TimeStamp >= outDate);
}
}
if (!string.IsNullOrEmpty(filter.TimeStampEnd))
{
if (DateTime.TryParse(filter.TimeStampEnd, out var outDate))
{
predicate = predicate.And(p => p.TimeStamp < outDate.AddDays(1));
}
}
if (!string.IsNullOrEmpty(filter.Message))
{
predicate = predicate.And(p =>
EF.Functions.ILike(p.Message, string.Format(CultureInfo.CurrentCulture, "%{0}%", filter.Message)));
}
if (!string.IsNullOrEmpty(filter.Exception))
{
predicate = predicate.And(p =>
EF.Functions.ILike(p.Exception, string.Format(CultureInfo.CurrentCulture, "%{0}%", filter.Exception)));
}
if (filter.Level.HasValue)
{
predicate = predicate.And(p => p.Level == filter.Level);
}
return predicate;
}
#endregion
}
} | 40.38961 | 166 | 0.623151 | [
"Unlicense"
] | cognizant-softvision/donate-to | src/DonateTo.Services/Services/LogService.cs | 6,222 | C# |
//
// This test finds all possible hash algorithms and sees if they
// perform equally with GetHash vs Streaming model.
//
using System;
using System.Security.Cryptography;
using System.Reflection;
using System.Collections;
using Microsoft.SPOT.Platform.Test;
using Microsoft.SPOT.Cryptoki;
namespace Microsoft.SPOT.Platform.Tests
{
class GetHashVsStream2 : IMFTestInterface
{
bool m_isEmulator;
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// Add your functionality here.
try
{
m_isEmulator = (Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU == 3);
}
catch
{
return InitializeResult.Skip;
}
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
}
public const int MAX_PASSES = 20;
public const int MAX_SIZE = 100000;
static Random m_Rnd = new Random();
public static bool Test()
{
ArrayList alAlgorithms = null;
HashAlgorithm hash = null;
bool bRes = true;
// find all non-abstract classes in the mscorlib that derive from hashalgorithm
alAlgorithms = GetHashClasses();
Log.Comment("Found " + alAlgorithms.Count + " hash classes.");
// go through all of them
foreach (Type t in alAlgorithms)
{
Log.Comment("--- Class " + t.FullName + " ---");
// instantiate the class
try
{
hash = (HashAlgorithm)(Activator.CreateInstance(t));
}
catch (Exception e)
{
Log.Comment("Exception " + e.ToString() + "\n has been thrown" +
"when tried to instantiate the class");
continue;
}
// @todo: may be set the key in KeyedHashAlgorithms
// test the hash object
bRes = TestHash(hash) && bRes;
}
return bRes;
}
// returns all nonabstract hash classes in mscorlib
public static ArrayList GetHashClasses()
{
Type[] atAllTypes = Assembly.GetAssembly(typeof(Object)).GetTypes();
ArrayList alRes = new ArrayList();
Type tHashType = typeof(System.Security.Cryptography.HashAlgorithm);
foreach (Type t in atAllTypes)
if ((t.IsSubclassOf(tHashType)) && (!t.IsAbstract)) alRes.Add(t);
return alRes;
}
// tests a hash algorithm instance
public static bool TestHash(HashAlgorithm hash)
{
bool bRes = true;
// decide on the number of passes
int nPasses = m_Rnd.Next(MAX_PASSES) + 1;
Log.Comment("Doing " + nPasses + " passes...");
while (0 != nPasses--)
{
// init the hash object
hash.Initialize();
// create a random data blob
int nSize = m_Rnd.Next(MAX_SIZE);
byte[] abBlob = new byte[nSize];
Log.Comment("Test buffer size is " + nSize);
// first try ComputeHash
byte[] hash1 = hash.ComputeHash(abBlob);
// Log.Comment("Hash1:");
// PrintByteArray(hash1);
// now try stream
hash.Initialize();
CryptoStream cs = new CryptoStream(CryptoStream.Null, hash, CryptoStreamMode.Write);
cs.Write(abBlob, 0, abBlob.Length);
cs.Close();
byte[] hash2 = hash.Hash;
// Log.Comment("Hash2:");
// PrintByteArray(hash2);
if (Compare(hash1, hash2))
{
Log.Comment(" OK.");
}
else
{
bRes = false;
Log.Comment(" FAILED. Hashes are different.");
}
}
return bRes;
}
static Boolean Compare(Byte[] rgb1, Byte[] rgb2)
{
int i;
if (rgb1.Length != rgb2.Length) return false;
for (i = 0; i < rgb1.Length; i++)
{
if (rgb1[i] != rgb2[i]) return false;
}
return true;
}
static void PrintByteArray(Byte[] arr)
{
int i;
string str = "";
Log.Comment("Length: " + arr.Length);
for (i = 0; i < arr.Length; i++)
{
str += arr[i].ToString() + " ";
if ((i + 9) % 8 == 0)
{
Log.Comment(str);
str = "";
}
}
if (i % 8 != 0) Log.Comment(str);
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[TestMethod]
public MFTestResults GetHashvsStream2_Test()
{
bool bRes = true;
try
{
using (Session sess = new Session("", MechanismType.SHA256))
{
bRes &= Test(sess);
}
if (m_isEmulator)
{
using (Session sess = new Session("Emulator_Crypto", MechanismType.SHA256))
{
bRes &= Test(sess);
}
}
}
catch (Exception e)
{
Log.Exception("", e);
bRes = false;
}
return bRes ? MFTestResults.Pass : MFTestResults.Fail;
}
}
} | 29.445545 | 100 | 0.45612 | [
"Apache-2.0"
] | Sirokujira/MicroFrameworkPK_v4_3 | Test/Platform/Tests/CLR/System/Security/HASHING/Desktop/GetHashvsStream.cs | 5,948 | C# |
using System.Threading.Tasks;
using AutoFixture.NUnit3;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using SFA.DAS.EmployerDemand.Jobs.Application.Services;
using SFA.DAS.EmployerDemand.Jobs.Domain.Interfaces;
using SFA.DAS.EmployerDemand.Jobs.Infrastructure.Api.Requests;
using SFA.DAS.EmployerDemand.Jobs.Infrastructure.Api.Responses;
using SFA.DAS.Testing.AutoFixture;
namespace SFA.DAS.EmployerDemand.Jobs.UnitTests.Application.Services
{
public class WhenGettingDemandsOlderThan3Years
{
[Test, MoqAutoData]
public async Task Then_The_Api_Is_Called_To_Get_Demands_That_Are_3_Years_Old(
GetDemandsOlderThan3YearsResponse response,
[Frozen] Mock<IApiClient> mockApiClient,
EmployerDemandService service)
{
//Arrange
mockApiClient.Setup(x =>
x.Get<GetDemandsOlderThan3YearsResponse>(It.IsAny<GetDemandsOlderThan3YearsRequest>()))
.ReturnsAsync(response);
//Act
var actual = await service.GetDemandsOlderThan3Years();
//Assert
actual.Should().BeEquivalentTo(response.EmployerDemandIds);
}
}
} | 35.911765 | 107 | 0.695332 | [
"MIT"
] | SkillsFundingAgency/das-employerdemand-jobs | src/SFA.DAS.EmployerDemand.Jobs.UnitTests/Application/Services/WhenGettingDemandsOlderThan3Years.cs | 1,223 | C# |
using Common;
using GraphDataService.Query.Contract;
using log4net;
using Neo4j.Driver.V1;
using System;
using System.Collections.Generic;
using System.Linq;
namespace GraphDataService.Query
{
public class GraphDataServiceQuery : IGraphDataServiceQuery
{
private const string GetEdgesCypher = "MATCH (n:Vertex)--(m:Vertex) RETURN n.id, m.id";
private const string GetNodesCypher = "MATCH (v:Vertex) RETURN v.id, v.label";
private ILog log;
private IDriver driver;
public GraphDataServiceQuery(ILoggerFactory loggerFactory, IDriver driver)
{
log = loggerFactory.GetLogger(GetType());
this.driver = driver;
}
public IList<Edge> GetEdges()
{
log.Info("Requested edges.");
try
{
using (var session = driver.Session())
{
return GetEdges(session);
}
}
catch (Exception e)
{
log.Fatal("Error occured while querying the graph.", e);
throw;
}
}
private IList<Edge> GetEdges(IStatementRunner runner)
{
log.Debug("Retrieving edges...");
var result = runner.Run(GetEdgesCypher);
log.Debug("Done.");
return result.Select(rec => new Edge
{
Vertex1 = Convert.ToInt32(rec["n.id"]),
Vertex2 = Convert.ToInt32(rec["m.id"])
}).ToList();
}
public Graph GetGraph()
{
log.Info("Requested graph.");
try
{
using (var session = driver.Session())
using (var transaction = session.BeginTransaction())
{
log.Debug("Retrieving vertices...");
var vertices = transaction.Run(GetNodesCypher);
log.Debug("Done.");
var verticesList = vertices.Select(rec => new Vertex
{
Id = Convert.ToInt32(rec["v.id"]),
Label = rec["v.label"].ToString()
}).ToList();
return new Graph
{
Edges = GetEdges(transaction),
Vertices = verticesList
};
}
}
catch (Exception e)
{
log.Fatal("Error occured while querying the graph.", e);
throw;
}
}
}
}
| 31.035714 | 95 | 0.47756 | [
"MIT"
] | h4mu/GraphVisualization | GraphDataService.Query/GraphDataServiceQuery.cs | 2,609 | C# |
//----------------------------------------------
// Ruler 2D
// Copyright © 2015-2020 Pixel Fire™
//----------------------------------------------
namespace R2D
{
using UnityEditor;
using System.Collections.Generic;
public class R2DV_PanelSettings
{
static R2DV_PanelSettings instance;
public static R2DV_PanelSettings Instance
{
get
{
if (instance == null)
{
instance = new R2DV_PanelSettings();
}
return instance;
}
}
R2DV_Drawing drawing;
R2DD_Resources resources;
R2DC_Utils utils;
R2DD_State state;
private R2DV_PanelSettings()
{
drawing = R2DV_Drawing.Instance;
resources = R2DD_Resources.Instance;
utils = R2DC_Utils.Instance;
state = R2DD_State.Instance;
}
public void DrawGUI()
{
// grab data
R2DC_Settings controller = R2DC_Settings.Instance;
List<string> contextNames = controller.contextNames;
// title
drawing.BeginEditorHorizontal();
drawing.DrawPanelTitle(R2DD_Lang.titleRulerSettings, resources.panelSettings);
drawing.FlexibleSpace();
if (drawing.DrawImageButton(resources.help))
{
Help.BrowseURL(R2DD_Resources.urlSettingsHelp);
};
drawing.EndEditorHorizontal();
// Not in 2d error
if (!utils.IsSceneViewIn2D())
{
drawing.DrawErrorBox(R2DD_Lang.sceneModeError);
drawing.DrawSpace(9f);
if (drawing.DrawButton(R2DD_Lang.set2DSceneMode))
{
utils.Set2DMode();
utils.RepaintSceneView();
}
utils.RepaintEditorWindow();
return;
}
// context
drawing.DrawPanelLabel(R2DD_Lang.context);
int oldContextInstanceId = state.context.instanceId;
int contextIndex = drawing.DrawPopup(controller.contextIndex, contextNames.ToArray());
int newContextInstanceId = controller.availableContexts[contextIndex].instanceId;
if (oldContextInstanceId != newContextInstanceId)
{
controller.SetContext(contextIndex);
utils.RepaintSceneView();
}
drawing.DrawSpace(9f);
// show coordinates
bool oldDisplayCoords = state.displayCoords;
state.displayCoords = drawing.DrawToggleWithWidth(R2DD_Lang.displaySelectedCoords, state.displayCoords, toggleWidth);
if (oldDisplayCoords != state.displayCoords)
{
utils.RepaintSceneView();
}
// prefer colliders
state.preferColliders = drawing.DrawToggleWithWidth(R2DD_Lang.preferColliders, state.preferColliders, toggleWidth);
// show/hide guides
bool oldDisplayGuides = state.displayGuides;
state.displayGuides = drawing.DrawToggleWithWidth(R2DD_Lang.displayGuides, state.displayGuides, toggleWidth);
if (oldDisplayGuides != state.displayGuides)
{
utils.RepaintSceneView();
}
// lock guides
bool oldLockGuides = state.lockGuides;
state.lockGuides = drawing.DrawToggleWithWidth(R2DD_Lang.lockGuides, state.lockGuides, toggleWidth);
if (oldLockGuides != state.lockGuides)
{
utils.RepaintSceneView();
}
// snap guide to int
state.snapGuideToInt = drawing.DrawToggleWithWidth(R2DD_Lang.snapGuideToInt, state.snapGuideToInt, toggleWidth);
// use edges for snapping
state.snapEdges = drawing.DrawToggleWithWidth(R2DD_Lang.lblUseEdgesForSnap, state.snapEdges, toggleWidth);
}
const float toggleWidth = 180f;
}
}
| 26.656489 | 120 | 0.658076 | [
"MIT"
] | elitegoliath/ld43-yank-train | LD43 Yank Train/Assets/Dependencies/R2D/R2DScripts/Editor/Views/R2DV_PanelSettings.cs | 3,495 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace EmailValidationTrigger.UWP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Xamarin.Forms.Platform.UWP.WindowsPage
{
public MainPage()
{
this.InitializeComponent();
LoadApplication(new EmailValidationTrigger.App());
}
}
}
| 28.272727 | 106 | 0.729904 | [
"Apache-2.0"
] | NoleHealth/xamarin-forms-book-preview-2 | Chapter23/EmailValidationTrigger/EmailValidationTrigger/EmailValidationTrigger.UWP/MainPage.xaml.cs | 935 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void Abs_Vector128_Single()
{
var test = new SimpleUnaryOpTest__Abs_Vector128_Single();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__Abs_Vector128_Single
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__Abs_Vector128_Single testClass)
{
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__Abs_Vector128_Single testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Vector128<Single> _clsVar1;
private Vector128<Single> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__Abs_Vector128_Single()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleUnaryOpTest__Abs_Vector128_Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Abs(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector128<Single>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Abs(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Single*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__Abs_Vector128_Single();
var result = AdvSimd.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__Abs_Vector128_Single();
fixed (Vector128<Single>* pFld1 = &test._fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Single*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Single*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(Helpers.Abs(firstOp[i])) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Abs)}<Single>(Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 37.635992 | 190 | 0.573408 | [
"MIT"
] | 2m0nd/runtime | src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Abs.Vector128.Single.cs | 18,404 | C# |
using JT808.Protocol.Attributes;
using JT808.Protocol.JT808Formatters.MessageBodyFormatters;
namespace JT808.Protocol.MessageBody
{
/// <summary>
/// 事件报告
/// 0x0301
/// </summary>
[JT808Formatter(typeof(JT808_0x0301Formatter))]
public class JT808_0x0301 : JT808Bodies
{
/// <summary>
/// 事件 ID
/// </summary>
public byte EventId { get; set; }
}
}
| 21.842105 | 59 | 0.614458 | [
"MIT"
] | NealGao/JT808 | src/JT808.Protocol/MessageBody/JT808_0x0301.cs | 429 | C# |
using UnityEngine;
using System.Collections;
using System;
[System.Serializable]
public class Enemy : MonoBehaviour
{
public float xSpeed = 0f;
public float ySpeed = 0f;
public float speed = 3f;
public int health;
public int damage;
public bool impact = false;
public float impactTime;
public float angle = 0f;
public string particle;
public bool canBeFrozen = true;
public float RealFreezeTime = 2;
public float FreezeTime = 0;
public int priority = 0;
public bool killed = false;
public AudioSource sound;
public bool paused = false;
// Use this for initialization
void Awake()
{
impactTime = UnityEngine.Random.Range(0.1f, speed*0.7f);
}
void Start()
{
sound = gameObject.GetComponent<AudioSource>();
RocketLauncherSystem.e.Insert(RocketLauncherSystem.priority[priority], this);
RocketLauncherSystem.addPriority(priority);
}
/* void addPriority()
{
if (RocketLauncherSystem.e.Count >= priority)
{
}
}*/
// Update is called once per frame
void Update()
{
if (!paused)
{
FreezeTime -= Time.deltaTime;
xSpeed = Mathf.Sin(angle / 180 * Mathf.PI) * -speed;
ySpeed = Mathf.Cos(angle / 180 * Mathf.PI) * -speed;
Move();
if (transform.position.y < -5.2)
{
outOfBounds();
}
if (impact == true)
{
impactTime -= Time.deltaTime;
if (impactTime < 0)
{
Impact();
}
}
}
}
public virtual void Impact()
{
if (!killed)
{
for (int i = 0; i < Mathf.Round(damage / 10); i++)
Game.AddParticle("Dust", this.transform.position.x, this.transform.position.y);
Game.AddParticle("ImpactExplosion", this.transform.position.x, this.transform.position.y);
PlanetHealth.shield -= damage;
if (PlanetHealth.shield < 0)
{
PlanetHealth.planetHealth += PlanetHealth.shield;
PlanetHealth.shield = 0;
Game.AddParticle("Impact", this.transform.position.x, this.transform.position.y);
}
bool s = GameVar.sound;
if (GameVar.sound== true)
{
GameObject instance = Instantiate(Resources.Load("ImpactSound", typeof(GameObject))) as GameObject;
}
Kill();
}
}
public void Move()
{
if (FreezeTime < 0)
{
transform.position = new Vector2(transform.position.x + xSpeed * Time.deltaTime, transform.position.y + ySpeed * Time.deltaTime);
if (transform.position.y > 6) Kill();
}
}
public virtual void Damage(int damage)
{
if (GameVar.sound == true)
{
sound.Play();
}
if (health - damage < 1)
damage = health;
for (var i = 0; i < damage/2+1; i++)
Game.AddParticle(particle, this.transform.position.x, this.transform.position.y);
health -= damage;
if (health < 1) Kill();
}
void OnTriggerEnter2D(Collider2D col)
{
if (!impact)
{
if (col.tag == "BigPlanet")
{
impact = true;
}
}
}
public void Freeze()
{
FreezeTime = RealFreezeTime;
}
public virtual void Kill()
{
if (killed == false)
{
Vector3 p = transform.position;
if (priority == 9)
{
Game.AddParticle("SmallExplosion", p.x+0.1f, p.y);
Game.AddParticle("SmallExplosion", p.x - 0.1f, p.y-0.04f);
Game.AddParticle("SmallExplosion", p.x + 0.06f, p.y+0.04f);
}
else if(priority == 8)
{
Game.AddParticle("SmallExplosion", p.x + 0.1f, p.y);
Game.AddParticle("SmallExplosion", p.x - 0.1f, p.y - 0.04f);
Game.AddParticle("SmallExplosion", p.x + 0.06f, p.y + 0.04f);
Game.AddParticle("SmallExplosion", p.x + 0.15f, p.y + 0.1f);
Game.AddParticle("SmallExplosion", p.x - 0.15f, p.y - 0.10f);
}
else if (priority == 2)
{
Game.AddParticle("SmallExplosion", p.x + 0.1f, p.y);
Game.AddParticle("SmallExplosion", p.x - 0.1f, p.y - 0.04f);
Game.AddParticle("SmallExplosion", p.x + 0.06f, p.y + 0.04f);
Game.AddParticle("SmallExplosion", p.x + 0.15f, p.y + 0.1f);
Game.AddParticle("SmallExplosion", p.x - 0.15f, p.y - 0.10f);
Game.AddParticle("SmallExplosion", p.x - 0.25f, p.y + 0.1f);
Game.AddParticle("SmallExplosion", p.x, p.y-0.25f);
}
else if (priority == 1)
{
Game.AddParticle("SmallExplosion", p.x + 0.1f, p.y);
Game.AddParticle("SmallExplosion", p.x - 0.1f, p.y - 0.04f);
Game.AddParticle("SmallExplosion", p.x + 0.06f, p.y + 0.04f);
Game.AddParticle("SmallExplosion", p.x + 0.15f, p.y + 0.1f);
Game.AddParticle("SmallExplosion", p.x - 0.15f, p.y - 0.10f);
Game.AddParticle("SmallExplosion", p.x - 0.25f, p.y + 0.1f);
Game.AddParticle("SmallExplosion", p.x, p.y-0.25f);
Game.AddParticle("SmallExplosion", p.x + 0.5f, p.y + 0.05f);
Game.AddParticle("SmallExplosion", p.x - 0.5f, p.y - 0.05f);
}
RocketLauncherSystem.e.Remove(this);
RocketLauncherSystem.removePriority(priority);
Destroy(gameObject, sound.clip.length);
Lock();
killed = true;
}
}
public void Lock()
{
speed = 0;
canBeFrozen = false;
impactTime = 9999;
impact = false;
SpriteRenderer[] sp = GetComponentsInChildren<SpriteRenderer>();
for(int i = 0; i < sp.Length; i ++)
Destroy(sp[i]);
Destroy(GetComponent<Collider2D>());
}
public virtual void outOfBounds()
{
if (!killed)
{
PlanetHealth.shield -= damage;
if (PlanetHealth.shield < 0)
{
PlanetHealth.planetHealth += PlanetHealth.shield;
PlanetHealth.shield = 0;
RocketLauncherSystem.e.Remove(this);
RocketLauncherSystem.removePriority(priority);
Destroy(gameObject);
}
}
}
void OnPauseGame()
{
paused = true;
}
void Resume()
{
paused = false;
}
}
| 31.363636 | 141 | 0.506522 | [
"MIT"
] | PavelVjalicin/PDS_unity | Assets/Resources/Enemy.cs | 6,902 | C# |
//------------------------------------------------------------------------------
// <自动生成>
// 此代码由工具生成。
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </自动生成>
//------------------------------------------------------------------------------
namespace EIS.WebBase.SysFolder.WorkFlow {
public partial class SelectUser {
/// <summary>
/// Head1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlHead Head1;
/// <summary>
/// form1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// LinkButton1 控件。
/// </summary>
/// <remarks>
/// 自动生成的字段。
/// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton LinkButton1;
}
}
| 26.255814 | 81 | 0.430469 | [
"MIT"
] | chen1993nian/CPMPlatform | Dev/SysFolder/WorkFlow/SelectUser.aspx.designer.cs | 1,477 | C# |
namespace Chapter2.SRP.Decorator
{
public abstract class PersistorDecorator<T> : IPersistor<T>
{
protected IPersistor<T> objectToBeDecorated;
public PersistorDecorator(IPersistor<T> objectToBeDecorated)
{
this.objectToBeDecorated = objectToBeDecorated;
}
public virtual bool Persist(T objToPersist)
{
return objectToBeDecorated.Persist(objToPersist);
}
}
}
| 25.111111 | 68 | 0.650442 | [
"MIT"
] | wagnerhsu/packt-Enterprise-Application-Architecture-with-NET-Core | Chapter02/src/Chapter2/SRP/Decorator/PersistorDecorator.cs | 454 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Net.NetworkInformation
{
internal static class InterfaceInfoPal
{
public static uint InterfaceNameToIndex(string interfaceName)
{
return Interop.IpHlpApi.if_nametoindex(interfaceName);
}
}
}
| 28.142857 | 71 | 0.708122 | [
"MIT"
] | 2m0nd/runtime | src/libraries/Common/src/System/Net/NetworkInformation/InterfaceInfoPal.Windows.cs | 394 | C# |
using KitchenSink.Tests.Ui;
using KitchenSink.Tests.Ui.SectionString;
using KitchenSink.Tests.Utilities;
using NUnit.Framework;
namespace KitchenSink.Tests.Test.SectionString
{
[Parallelizable(ParallelScope.Fixtures)]
[TestFixture(Config.Browser.Chrome)]
[TestFixture(Config.Browser.Edge)]
[TestFixture(Config.Browser.Firefox)]
internal class TextPageTest : BaseTest
{
private TextPage _textPage;
private MainPage _mainPage;
public TextPageTest(Config.Browser browser) : base(browser)
{
}
[SetUp]
public void SetUp()
{
_mainPage = new MainPage(Driver).GoToMainPage();
_textPage = _mainPage.GoToTextPage();
}
[Test]
public void TextPage_TextPropagationOnUnfocus()
{
WaitUntil(x => _textPage.Input.Displayed);
_textPage.FillInput("Krystian");
Assert.IsTrue(WaitForText(_textPage.InputInfoLabel, "Hi, Krystian!", 5));
_textPage.ClearInput();
WaitUntil(x => _textPage.Input.Text == string.Empty);
Assert.AreEqual("What's your name?", _textPage.InputInfoLabel.Text);
}
[Test]
public void TextPage_TextPropagationWhileTyping()
{
WaitUntil(x => _textPage.InputDynamic.Displayed);
_textPage.FillInputDynamic("K");
Assert.IsTrue(WaitForText(_textPage.InputInfoLabelDynamic, "Hi, K!", 5));
_textPage.ClearInputDynamic();
WaitUntil(x => _textPage.InputDynamic.Text == string.Empty);
Assert.AreEqual("What's your name?", _textPage.InputInfoLabelDynamic.Text);
}
}
} | 32.557692 | 87 | 0.633196 | [
"MIT"
] | MichalMajka/KitchenSink | test/KitchenSink.Tests/Test/SectionString/TextPageTest.cs | 1,695 | C# |
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Prise.Infrastructure;
namespace Prise
{
public class DefaultAssemblyLoader<T> : DisposableAssemblyUnLoader, IPluginAssemblyLoader<T>
{
private readonly IPluginLogger<T> logger;
private readonly IAssemblyLoadOptions<T> options;
private readonly IHostFrameworkProvider hostFrameworkProvider;
private readonly IHostTypesProvider<T> hostTypesProvider;
private readonly IDowngradableDependenciesProvider<T> downgradableDependenciesProvider;
private readonly IRemoteTypesProvider<T> remoteTypesProvider;
private readonly IDependencyPathProvider<T> dependencyPathProvider;
private readonly IProbingPathsProvider<T> probingPathsProvider;
private readonly IRuntimePlatformContext runtimePlatformContext;
private readonly IDepsFileProvider<T> depsFileProvider;
private readonly IPluginDependencyResolver<T> pluginDependencyResolver;
private readonly INativeAssemblyUnloader nativeAssemblyUnloader;
private readonly IAssemblyLoadStrategyProvider assemblyLoadStrategyProvider;
public DefaultAssemblyLoader(
IPluginLogger<T> logger,
IAssemblyLoadOptions<T> options,
IHostFrameworkProvider hostFrameworkProvider,
IHostTypesProvider<T> hostTypesProvider,
IDowngradableDependenciesProvider<T> downgradableDependenciesProvider,
IRemoteTypesProvider<T> remoteTypesProvider,
IDependencyPathProvider<T> dependencyPathProvider,
IProbingPathsProvider<T> probingPathsProvider,
IRuntimePlatformContext runtimePlatformContext,
IDepsFileProvider<T> depsFileProvider,
IPluginDependencyResolver<T> pluginDependencyResolver,
INativeAssemblyUnloader nativeAssemblyUnloader,
IAssemblyLoadStrategyProvider assemblyLoadStrategyProvider) : base()
{
this.logger = logger;
this.options = options;
this.hostFrameworkProvider = hostFrameworkProvider;
this.hostTypesProvider = hostTypesProvider;
this.downgradableDependenciesProvider = downgradableDependenciesProvider;
this.remoteTypesProvider = remoteTypesProvider;
this.dependencyPathProvider = dependencyPathProvider;
this.probingPathsProvider = probingPathsProvider;
this.runtimePlatformContext = runtimePlatformContext;
this.depsFileProvider = depsFileProvider;
this.pluginDependencyResolver = pluginDependencyResolver;
this.nativeAssemblyUnloader = nativeAssemblyUnloader;
this.assemblyLoadStrategyProvider = assemblyLoadStrategyProvider;
}
public virtual Assembly Load(IPluginLoadContext pluginLoadContext)
{
var loadContext = new DefaultAssemblyLoadContext<T>(
this.logger,
this.options,
this.hostFrameworkProvider,
this.hostTypesProvider,
this.downgradableDependenciesProvider,
this.remoteTypesProvider,
this.dependencyPathProvider,
this.probingPathsProvider,
this.runtimePlatformContext,
this.depsFileProvider,
this.pluginDependencyResolver,
this.nativeAssemblyUnloader,
this.assemblyLoadStrategyProvider
);
var loadedPluginKey = new LoadedPluginKey(pluginLoadContext);
this.loadContexts[loadedPluginKey] = loadContext;
this.loadContextReferences[loadedPluginKey] = new System.WeakReference(loadContext);
return loadContext.LoadPluginAssembly(pluginLoadContext);
}
public virtual Task<Assembly> LoadAsync(IPluginLoadContext pluginLoadContext)
{
var loadContext = new DefaultAssemblyLoadContext<T>(
this.logger,
this.options,
this.hostFrameworkProvider,
this.hostTypesProvider,
this.downgradableDependenciesProvider,
this.remoteTypesProvider,
this.dependencyPathProvider,
this.probingPathsProvider,
this.runtimePlatformContext,
this.depsFileProvider,
this.pluginDependencyResolver,
this.nativeAssemblyUnloader,
this.assemblyLoadStrategyProvider
);
var loadedPluginKey = new LoadedPluginKey(pluginLoadContext);
this.loadContexts[loadedPluginKey] = loadContext;
this.loadContextReferences[loadedPluginKey] = new System.WeakReference(loadContext);
return loadContext.LoadPluginAssemblyAsync(pluginLoadContext);
}
}
}
| 46.495238 | 96 | 0.686194 | [
"MIT"
] | jingyiliu/Prise | src/Prise/DefaultAssemblyLoader.cs | 4,884 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiInterface(nativeType: typeof(IWafv2WebAclRuleStatementRateBasedStatementScopeDownStatementXssMatchStatementFieldToMatchMethod), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementRateBasedStatementScopeDownStatementXssMatchStatementFieldToMatchMethod")]
public interface IWafv2WebAclRuleStatementRateBasedStatementScopeDownStatementXssMatchStatementFieldToMatchMethod
{
[JsiiTypeProxy(nativeType: typeof(IWafv2WebAclRuleStatementRateBasedStatementScopeDownStatementXssMatchStatementFieldToMatchMethod), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementRateBasedStatementScopeDownStatementXssMatchStatementFieldToMatchMethod")]
internal sealed class _Proxy : DeputyBase, aws.IWafv2WebAclRuleStatementRateBasedStatementScopeDownStatementXssMatchStatementFieldToMatchMethod
{
private _Proxy(ByRefValue reference): base(reference)
{
}
}
}
}
| 51.1 | 264 | 0.831703 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/IWafv2WebAclRuleStatementRateBasedStatementScopeDownStatementXssMatchStatementFieldToMatchMethod.cs | 1,022 | 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.Extensions.Logging;
namespace Microsoft.Azure.Devices.Logging
{
/// <summary>
/// Extension methods to help simplify creation of a new <see cref="ColorConsoleLoggerProvider"/> instance.
/// </summary>
public static class ColorConsoleLoggerExtensions
{
/// <summary>
/// Add a new <see cref="ColorConsoleLoggerProvider"/> instance, with the supplied <see cref="ColorConsoleLoggerConfiguration"/> settings.
/// </summary>
/// <param name="loggerFactory">The type for which this extension method is defined.</param>
/// <param name="config">The <see cref="ColorConsoleLoggerConfiguration"/> settings to be used for logging.</param>
/// <returns>The <see cref="ILoggerFactory "/> instance.</returns>
public static ILoggerFactory AddColorConsoleLogger(this ILoggerFactory loggerFactory, ColorConsoleLoggerConfiguration config)
{
loggerFactory.AddProvider(new ColorConsoleLoggerProvider(config));
return loggerFactory;
}
/// <summary>
/// Add a new <see cref="ColorConsoleLoggerProvider"/> instance, with the default <see cref="ColorConsoleLoggerConfiguration"/> settings.
/// </summary>
/// <param name="loggerFactory">The type for which this extension method is defined.</param>
/// <returns>The <see cref="ILoggerFactory "/> instance.</returns>
public static ILoggerFactory AddColorConsoleLogger(this ILoggerFactory loggerFactory)
{
var config = new ColorConsoleLoggerConfiguration();
return loggerFactory.AddColorConsoleLogger(config);
}
}
}
| 49.162162 | 146 | 0.68884 | [
"MIT"
] | Azure-Samples/azure-iot-samples-csharp | helpers/ColorConsoleLogger/ColorConsoleLoggerExtensions.cs | 1,821 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Logic.Latest.Outputs
{
[OutputType]
public sealed class IntegrationServiceEnvironmenEncryptionKeyReferenceResponse
{
/// <summary>
/// Gets the key name in the Key Vault.
/// </summary>
public readonly string? KeyName;
/// <summary>
/// The key vault reference.
/// </summary>
public readonly Outputs.ResourceReferenceResponse? KeyVault;
/// <summary>
/// Gets the version of the key specified in the keyName property.
/// </summary>
public readonly string? KeyVersion;
[OutputConstructor]
private IntegrationServiceEnvironmenEncryptionKeyReferenceResponse(
string? keyName,
Outputs.ResourceReferenceResponse? keyVault,
string? keyVersion)
{
KeyName = keyName;
KeyVault = keyVault;
KeyVersion = keyVersion;
}
}
}
| 29.348837 | 82 | 0.639461 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Logic/Latest/Outputs/IntegrationServiceEnvironmenEncryptionKeyReferenceResponse.cs | 1,262 | 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;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.ML.Runtime;
namespace Microsoft.ML.Internal.Utilities
{
[BestFriend]
internal static partial class Utils
{
public const int ArrayMaxSize = ArrayUtils.ArrayMaxSize;
public static bool StartsWithInvariantCultureIgnoreCase(this string str, string startsWith)
{
return str.StartsWith(startsWith, StringComparison.InvariantCultureIgnoreCase);
}
public static bool StartsWithInvariantCulture(this string str, string startsWith)
{
return str.StartsWith(startsWith, StringComparison.InvariantCulture);
}
public static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
public static void Reverse<T>(T[] a, int iMin, int iLim)
{
while (iMin < --iLim)
Swap(ref a[iMin++], ref a[iLim]);
}
// Getting the size of a collection, when the collection may be null.
public static int Size(string x)
{
Contracts.AssertValueOrNull(x);
return x == null ? 0 : x.Length;
}
public static int Size(StringBuilder x)
{
Contracts.AssertValueOrNull(x);
return x == null ? 0 : x.Length;
}
public static int Size(Array x)
{
Contracts.AssertValueOrNull(x);
return x == null ? 0 : x.Length;
}
public static int Size<T>(T[] x)
{
Contracts.AssertValueOrNull(x);
return x == null ? 0 : x.Length;
}
public static int Size<T>(List<T> x)
{
Contracts.AssertValueOrNull(x);
return x == null ? 0 : x.Count;
}
public static int Size<T>(IList<T> x)
{
Contracts.AssertValueOrNull(x);
return x == null ? 0 : x.Count;
}
public static int Size<T>(IReadOnlyList<T> x)
{
Contracts.AssertValueOrNull(x);
return x == null ? 0 : x.Count;
}
public static int Size<T>(Stack<T> x)
{
Contracts.AssertValueOrNull(x);
return x == null ? 0 : x.Count;
}
public static int Size<T>(HashSet<T> x)
{
Contracts.AssertValueOrNull(x);
return x == null ? 0 : x.Count;
}
public static int Size<T>(SortedSet<T> x)
{
Contracts.AssertValueOrNull(x);
return x == null ? 0 : x.Count;
}
public static int Size<TKey, TValue>(Dictionary<TKey, TValue> x)
{
Contracts.AssertValueOrNull(x);
return x == null ? 0 : x.Count;
}
public static int Size(BitArray x)
{
Contracts.AssertValueOrNull(x);
return x == null ? 0 : x.Length;
}
// Getting items from a collection when the collection may be null.
public static bool TryGetValue<TKey, TValue>(Dictionary<TKey, TValue> map, TKey key, out TValue value)
{
Contracts.AssertValueOrNull(map);
if (map == null)
{
value = default(TValue);
return false;
}
return map.TryGetValue(key, out value);
}
public static T[] ToArray<T>(List<T> list)
{
Contracts.AssertValueOrNull(list);
return list == null ? null : list.ToArray();
}
// Adding items to a collection when the collection may be null.
public static void Add<T>(ref List<T> list, T item)
{
Contracts.AssertValueOrNull(list);
if (list == null)
list = new List<T>();
list.Add(item);
}
public static bool Add<T>(ref HashSet<T> set, T item)
{
Contracts.AssertValueOrNull(set);
if (set == null)
set = new HashSet<T>();
return set.Add(item);
}
public static void Add<TKey, TValue>(ref Dictionary<TKey, TValue> map, TKey key, TValue value)
{
Contracts.AssertValueOrNull(map);
if (map == null)
map = new Dictionary<TKey, TValue>();
map.Add(key, value);
}
public static void Set<TKey, TValue>(ref Dictionary<TKey, TValue> map, TKey key, TValue value)
{
Contracts.AssertValueOrNull(map);
if (map == null)
map = new Dictionary<TKey, TValue>();
map[key] = value;
}
public static void Push<T>(ref Stack<T> stack, T item)
{
Contracts.AssertValueOrNull(stack);
if (stack == null)
stack = new Stack<T>();
stack.Push(item);
}
/// <summary>
/// Copies the values from src to dst.
/// </summary>
/// <remarks>
/// This can be removed once we have the APIs from https://github.com/dotnet/corefx/issues/33006.
/// </remarks>
public static void CopyTo<T>(this List<T> src, Span<T> dst, int? count = null)
{
Contracts.Assert(src != null);
Contracts.Assert(!count.HasValue || (0 <= count && count <= src.Count));
Contracts.Assert(src.Count <= dst.Length);
count = count ?? src.Count;
for (int i = 0; i < count; i++)
{
dst[i] = src[i];
}
}
/// <summary>
/// Assumes input is sorted and finds value using BinarySearch.
/// If value is not found, returns the logical index of 'value' in the sorted list i.e index of the first element greater than value.
/// In case of duplicates it returns the index of the first one.
/// It guarantees that items before the returned index are < value, while those at and after the returned index are >= value.
/// </summary>
public static int FindIndexSorted(this IList<int> input, int value)
{
Contracts.AssertValue(input);
return FindIndexSorted(input, 0, input.Count, value);
}
/// <summary>
/// Assumes input is sorted and finds value using BinarySearch.
/// If value is not found, returns the logical index of 'value' in the sorted list i.e index of the first element greater than value.
/// In case of duplicates it returns the index of the first one.
/// It guarantees that items before the returned index are < value, while those at and after the returned index are >= value.
/// </summary>
public static int FindIndexSorted(this IList<float> input, float value)
{
Contracts.AssertValue(input);
return FindIndexSorted(input, 0, input.Count, value);
}
/// <summary>
/// Assumes input is sorted and finds value using BinarySearch.
/// If value is not found, returns the logical index of 'value' in the sorted list i.e index of the first element greater than value.
/// In case of duplicates it returns the index of the first one.
/// It guarantees that items before the returned index are < value, while those at and after the returned index are >= value.
/// </summary>
public static int FindIndexSorted(this Double[] input, Double value)
{
Contracts.AssertValue(input);
return FindIndexSorted(input, 0, input.Length, value);
}
/// <summary>
/// Akin to <c>FindIndexSorted</c>, except stores the found index in the output
/// <c>index</c> parameter, and returns whether that index is a valid index
/// pointing to a value equal to the input parameter <c>value</c>.
/// </summary>
public static bool TryFindIndexSorted(this int[] input, int min, int lim, int value, out int index)
{
return ArrayUtils.TryFindIndexSorted(input, min, lim, value, out index);
}
/// <summary>
/// Akin to <c>FindIndexSorted</c>, except stores the found index in the output
/// <c>index</c> parameter, and returns whether that index is a valid index
/// pointing to a value equal to the input parameter <c>value</c>.
/// </summary>
public static bool TryFindIndexSorted(ReadOnlySpan<int> input, int min, int lim, int value, out int index)
{
index = FindIndexSorted(input, min, lim, value);
return index < lim && input[index] == value;
}
/// <summary>
/// Assumes input is sorted and finds value using BinarySearch.
/// If value is not found, returns the logical index of 'value' in the sorted list i.e index of the first element greater than value.
/// In case of duplicates it returns the index of the first one.
/// It guarantees that items before the returned index are < value, while those at and after the returned index are >= value.
/// </summary>
public static int FindIndexSorted(this int[] input, int min, int lim, int value)
{
return FindIndexSorted(input.AsSpan(), min, lim, value);
}
/// <summary>
/// Assumes input is sorted and finds value using BinarySearch.
/// If value is not found, returns the logical index of 'value' in the sorted list i.e index of the first element greater than value.
/// In case of duplicates it returns the index of the first one.
/// It guarantees that items before the returned index are < value, while those at and after the returned index are >= value.
/// </summary>
public static int FindIndexSorted(this ReadOnlySpan<int> input, int min, int lim, int value)
{
return ArrayUtils.FindIndexSorted(input, min, lim, value);
}
/// <summary>
/// Assumes input is sorted and finds value using BinarySearch.
/// If value is not found, returns the logical index of 'value' in the sorted list i.e index of the first element greater than value.
/// In case of duplicates it returns the index of the first one.
/// It guarantees that items before the returned index are < value, while those at and after the returned index are >= value.
/// </summary>
public static int FindIndexSorted(this IList<int> input, int min, int lim, int value)
{
Contracts.AssertValue(input);
Contracts.Assert(0 <= min & min <= lim & lim <= input.Count);
int minCur = min;
int limCur = lim;
while (minCur < limCur)
{
int mid = (int)(((uint)minCur + (uint)limCur) / 2);
Contracts.Assert(minCur <= mid & mid < limCur);
if (input[mid] >= value)
limCur = mid;
else
minCur = mid + 1;
Contracts.Assert(min <= minCur & minCur <= limCur & limCur <= lim);
Contracts.Assert(minCur == min || input[minCur - 1] < value);
Contracts.Assert(limCur == lim || input[limCur] >= value);
}
Contracts.Assert(min <= minCur & minCur == limCur & limCur <= lim);
Contracts.Assert(minCur == min || input[minCur - 1] < value);
Contracts.Assert(limCur == lim || input[limCur] >= value);
return minCur;
}
/// <summary>
/// Assumes input is sorted and finds value using BinarySearch.
/// If value is not found, returns the logical index of 'value' in the sorted list i.e index of the first element greater than value.
/// In case of duplicates it returns the index of the first one.
/// It guarantees that items before the returned index are < value, while those at and after the returned index are >= value.
/// </summary>
public static int FindIndexSorted(this IList<float> input, int min, int lim, float value)
{
Contracts.AssertValue(input);
Contracts.Assert(0 <= min & min <= lim & lim <= input.Count);
Contracts.Assert(!float.IsNaN(value));
int minCur = min;
int limCur = lim;
while (minCur < limCur)
{
int mid = (int)(((uint)minCur + (uint)limCur) / 2);
Contracts.Assert(minCur <= mid & mid < limCur);
Contracts.Assert(!float.IsNaN(input[mid]));
if (input[mid] >= value)
limCur = mid;
else
minCur = mid + 1;
Contracts.Assert(min <= minCur & minCur <= limCur & limCur <= lim);
Contracts.Assert(minCur == min || input[minCur - 1] < value);
Contracts.Assert(limCur == lim || input[limCur] >= value);
}
Contracts.Assert(min <= minCur & minCur == limCur & limCur <= lim);
Contracts.Assert(minCur == min || input[minCur - 1] < value);
Contracts.Assert(limCur == lim || input[limCur] >= value);
return minCur;
}
/// <summary>
/// Assumes input is sorted and finds value using BinarySearch.
/// If value is not found, returns the logical index of 'value' in the sorted list i.e index of the first element greater than value.
/// In case of duplicates it returns the index of the first one.
/// It guarantees that items before the returned index are < value, while those at and after the returned index are >= value.
/// </summary>
public static int FindIndexSorted(this Double[] input, int min, int lim, Double value)
{
Contracts.AssertValue(input);
Contracts.Assert(0 <= min & min <= lim & lim <= input.Length);
Contracts.Assert(!Double.IsNaN(value));
int minCur = min;
int limCur = lim;
while (minCur < limCur)
{
int mid = (int)(((uint)minCur + (uint)limCur) / 2);
Contracts.Assert(minCur <= mid & mid < limCur);
Contracts.Assert(!Double.IsNaN(input[mid]));
if (input[mid] >= value)
limCur = mid;
else
minCur = mid + 1;
Contracts.Assert(min <= minCur & minCur <= limCur & limCur <= lim);
Contracts.Assert(minCur == min || input[minCur - 1] < value);
Contracts.Assert(limCur == lim || input[limCur] >= value);
}
Contracts.Assert(min <= minCur & minCur == limCur & limCur <= lim);
Contracts.Assert(minCur == min || input[minCur - 1] < value);
Contracts.Assert(limCur == lim || input[limCur] >= value);
return minCur;
}
/// <summary>
/// Finds the unique index for which func(input[i]) == false whenever i < index and
/// func(input[i]) == true whenever i >= index.
/// Callers should guarantee that there is such an index. Uses binary search.
/// </summary>
public static int FindIndexSorted<T>(this T[] input, int min, int lim, Func<T, bool> func)
{
Contracts.AssertValue(input);
Contracts.Assert(0 <= min & min <= lim & lim <= input.Length);
int minCur = min;
int limCur = lim;
while (minCur < limCur)
{
int mid = (int)(((uint)minCur + (uint)limCur) / 2);
Contracts.Assert(minCur <= mid & mid < limCur);
if (func(input[mid]))
limCur = mid;
else
minCur = mid + 1;
Contracts.Assert(min <= minCur & minCur <= limCur & limCur <= lim);
Contracts.Assert(minCur == min || !func(input[minCur - 1]));
Contracts.Assert(limCur == lim || func(input[limCur]));
}
Contracts.Assert(min <= minCur & minCur == limCur & limCur <= lim);
Contracts.Assert(minCur == min || !func(input[minCur - 1]));
Contracts.Assert(limCur == lim || func(input[limCur]));
return minCur;
}
/// <summary>
/// Finds the unique index for which func(input[i], value) == false whenever i < index and
/// func(input[i], value) == true whenever i >= index.
/// Callers should guarantee that there is such an index. Uses binary search.
/// </summary>
public static int FindIndexSorted<T, TValue>(this T[] input, int min, int lim, Func<T, TValue, bool> func, TValue value)
{
Contracts.AssertValue(input);
Contracts.Assert(0 <= min & min <= lim & lim <= input.Length);
int minCur = min;
int limCur = lim;
while (minCur < limCur)
{
int mid = (int)(((uint)minCur + (uint)limCur) / 2);
Contracts.Assert(minCur <= mid & mid < limCur);
if (func(input[mid], value))
limCur = mid;
else
minCur = mid + 1;
Contracts.Assert(min <= minCur & minCur <= limCur & limCur <= lim);
Contracts.Assert(minCur == min || !func(input[minCur - 1], value));
Contracts.Assert(limCur == lim || func(input[limCur], value));
}
Contracts.Assert(min <= minCur & minCur == limCur & limCur <= lim);
Contracts.Assert(minCur == min || !func(input[minCur - 1], value));
Contracts.Assert(limCur == lim || func(input[limCur], value));
return minCur;
}
public static int[] GetIdentityPermutation(int size)
{
Contracts.Assert(size >= 0);
var res = new int[size];
for (int i = 0; i < size; i++)
res[i] = i;
return res;
}
public static void FillIdentity(Span<int> a, int lim)
{
Contracts.Assert(0 <= lim & lim <= a.Length);
for (int i = 0; i < lim; ++i)
a[i] = i;
}
// REVIEW: Maybe remove this in future?
public static void InterlockedAdd(ref double target, double v)
{
double snapshotOfTargetBefore;
double snapshotOfTargetDuring = target;
double targetPlusV;
do
{
snapshotOfTargetBefore = snapshotOfTargetDuring;
targetPlusV = snapshotOfTargetBefore + v;
snapshotOfTargetDuring = Interlocked.CompareExchange(ref target, targetPlusV, snapshotOfTargetBefore);
} while (snapshotOfTargetDuring != snapshotOfTargetBefore);
}
public static int[] InvertPermutation(int[] perm)
{
Contracts.AssertValue(perm);
var res = new int[perm.Length];
for (int i = 0; i < perm.Length; i++)
{
int j = perm[i];
Contracts.Assert(0 <= j & j < perm.Length);
Contracts.Assert(res[j] == 0 & (j != perm[0] | i == 0));
res[j] = i;
}
return res;
}
public static int[] GetRandomPermutation(Random rand, int size)
{
Contracts.AssertValue(rand);
Contracts.Assert(size >= 0);
var res = GetIdentityPermutation(size);
Shuffle<int>(rand, res);
return res;
}
public static bool AreEqual(float[] arr1, float[] arr2)
{
if (arr1 == arr2)
return true;
if (arr1 == null || arr2 == null)
return false;
if (arr1.Length != arr2.Length)
return false;
for (int i = 0; i < arr1.Length; i++)
{
if (arr1[i] != arr2[i])
return false;
}
return true;
}
public static bool AreEqual(double[] arr1, double[] arr2)
{
if (arr1 == arr2)
return true;
if (arr1 == null || arr2 == null)
return false;
if (arr1.Length != arr2.Length)
return false;
for (int i = 0; i < arr1.Length; i++)
{
if (arr1[i] != arr2[i])
return false;
}
return true;
}
public static void Shuffle<T>(Random rand, Span<T> rgv)
{
Contracts.AssertValue(rand);
for (int iv = 0; iv < rgv.Length; iv++)
Swap(ref rgv[iv], ref rgv[iv + rand.Next(rgv.Length - iv)]);
}
public static bool AreEqual(int[] arr1, int[] arr2)
{
if (arr1 == arr2)
return true;
if (arr1 == null || arr2 == null)
return false;
if (arr1.Length != arr2.Length)
return false;
for (int i = 0; i < arr1.Length; i++)
{
if (arr1[i] != arr2[i])
return false;
}
return true;
}
public static bool AreEqual(bool[] arr1, bool[] arr2)
{
if (arr1 == arr2)
return true;
if (arr1 == null || arr2 == null)
return false;
if (arr1.Length != arr2.Length)
return false;
for (int i = 0; i < arr1.Length; i++)
{
if (arr1[i] != arr2[i])
return false;
}
return true;
}
public static string ExtractLettersAndNumbers(string value)
{
return Regex.Replace(value, "[^A-Za-z0-9]", "");
}
/// <summary>
/// Checks that an input IList is monotonically increasing.
/// </summary>
/// <param name="values">An array of values</param>
/// <returns>True if the array is monotonically increasing (if each element is greater
/// than or equal to previous elements); false otherwise. ILists containing NaN values
/// are considered to be not monotonically increasing.</returns>
public static bool IsMonotonicallyIncreasing(IList<float> values)
{
if (Utils.Size(values) <= 1)
return true;
var previousValue = values[0];
var listLength = values.Count;
for (int i = 1; i < listLength; i++)
{
var currentValue = values[i];
// Inverted check for NaNs
if (!(currentValue >= previousValue))
return false;
previousValue = currentValue;
}
return true;
}
/// <summary>
/// Checks that an input array is monotonically increasing.
/// </summary>
/// <param name="values">An array of values</param>
/// <returns>True if the array is monotonically increasing (if each element is greater
/// than or equal to previous elements); false otherwise.</returns>
public static bool IsMonotonicallyIncreasing(IList<int> values)
{
if (Utils.Size(values) <= 1)
return true;
var previousValue = values[0];
var listLength = values.Count;
for (int i = 1; i < listLength; i++)
{
var currentValue = values[i];
if (currentValue < previousValue)
return false;
previousValue = currentValue;
}
return true;
}
/// <summary>
/// Checks that an input array is monotonically increasing.
/// </summary>
/// <param name="values">An array of values</param>
/// <returns>True if the array is monotonically increasing (if each element is greater
/// than or equal to previous elements); false otherwise. Arrays containing NaN values
/// are considered to be not monotonically increasing.</returns>
public static bool IsMonotonicallyIncreasing(IList<double> values)
{
if (Utils.Size(values) <= 1)
return true;
var previousValue = values[0];
var listLength = values.Count;
for (int i = 1; i < listLength; i++)
{
var currentValue = values[i];
// Inverted check for NaNs
if (!(currentValue >= previousValue))
return false;
previousValue = currentValue;
}
return true;
}
/// <summary>
/// Returns whether an input integer vector is sorted and unique,
/// and between an inclusive lower and exclusive upper bound for
/// the first and last items, respectively.
/// </summary>
public static bool IsIncreasing(int min, ReadOnlySpan<int> values, int lim)
{
if (values.Length < 1)
return true;
var prev = values[0];
if (prev < min)
return false;
for (int i = 1; i < values.Length; i++)
{
if (values[i] <= prev)
return false;
prev = values[i];
}
return prev < lim;
}
/// <summary>
/// Returns whether an input integer vector up to <paramref name="len"/>
/// is sorted and unique, and between an inclusive lower and exclusive
/// upper bound for the first and last items, respectively.
/// </summary>
public static bool IsIncreasing(int min, ReadOnlySpan<int> values, int len, int lim)
{
Contracts.Check(values.Length >= len);
if (len < 1)
return true;
var prev = values[0];
if (prev < min)
return false;
for (int i = 1; i < len; i++)
{
if (values[i] <= prev)
return false;
prev = values[i];
}
return prev < lim;
}
/// <summary>
/// Create an array of specified length, filled with a specified value
/// </summary>
public static T[] CreateArray<T>(int length, T value)
{
Contracts.Assert(length >= 0, "Length can't be negative");
var result = new T[length];
for (int i = 0; i < length; i++)
result[i] = value;
return result;
}
public static bool[] BuildArray(int length, IEnumerable<DataViewSchema.Column> columnsNeeded)
{
Contracts.CheckParam(length >= 0, nameof(length));
var result = new bool[length];
foreach (var col in columnsNeeded)
{
if (col.Index < result.Length)
result[col.Index] = true;
}
return result;
}
public static T[] BuildArray<T>(int length, Func<int, T> func)
{
Contracts.CheckParam(length >= 0, nameof(length));
Contracts.CheckValue(func, nameof(func));
var result = new T[length];
for (int i = 0; i < result.Length; i++)
result[i] = func(i);
return result;
}
/// <summary>
/// Given a predicate, over a range of values defined by a limit calculate
/// first the values for which that predicate was true, and second an inverse
/// map.
/// </summary>
/// <param name="schema">The input schema where the predicate can check if columns are active.</param>
/// <param name="pred">The predicate to test for various value</param>
/// <param name="map">An ascending array of values from 0 inclusive
/// to <paramref name="schema.Count"/> exclusive, holding all values for which
/// <paramref name="pred"/> is true</param>
/// <param name="invMap">Forms an inverse mapping of <paramref name="map"/>,
/// so that <c><paramref name="invMap"/>[<paramref name="map"/>[i]] == i</c>,
/// and for other entries not appearing in <paramref name="map"/>,
/// <c><paramref name="invMap"/>[i] == -1</c></param>
public static void BuildSubsetMaps(DataViewSchema schema, Func<DataViewSchema.Column, bool> pred, out int[] map, out int[] invMap)
{
Contracts.CheckValue(schema, nameof(schema));
Contracts.Check(schema.Count > 0, nameof(schema));
Contracts.CheckValue(pred, nameof(pred));
// REVIEW: Better names?
List<int> mapList = new List<int>();
invMap = new int[schema.Count];
for (int c = 0; c < schema.Count; ++c)
{
if (!pred(schema[c]))
{
invMap[c] = -1;
continue;
}
invMap[c] = mapList.Count;
mapList.Add(c);
}
map = mapList.ToArray();
}
/// <summary>
/// Given a predicate, over a range of values defined by a limit calculate
/// first the values for which that predicate was true, and second an inverse
/// map.
/// </summary>
/// <param name="lim">Indicates the exclusive upper bound on the tested values</param>
/// <param name="pred">The predicate to test for various value</param>
/// <param name="map">An ascending array of values from 0 inclusive
/// to <paramref name="lim"/> exclusive, holding all values for which
/// <paramref name="pred"/> is true</param>
/// <param name="invMap">Forms an inverse mapping of <paramref name="map"/>,
/// so that <c><paramref name="invMap"/>[<paramref name="map"/>[i]] == i</c>,
/// and for other entries not appearing in <paramref name="map"/>,
/// <c><paramref name="invMap"/>[i] == -1</c></param>
public static void BuildSubsetMaps(int lim, Func<int, bool> pred, out int[] map, out int[] invMap)
{
Contracts.CheckParam(lim >= 0, nameof(lim));
Contracts.CheckValue(pred, nameof(pred));
// REVIEW: Better names?
List<int> mapList = new List<int>();
invMap = new int[lim];
for (int c = 0; c < lim; ++c)
{
if (!pred(c))
{
invMap[c] = -1;
continue;
}
invMap[c] = mapList.Count;
mapList.Add(c);
}
map = mapList.ToArray();
}
/// <summary>
/// Given the columns needed, over a range of values defined by a limit calculate
/// first the values for which the column is present was true, and second an inverse
/// map.
/// </summary>
/// <param name="lim">Indicates the exclusive upper bound on the tested values</param>
/// <param name="columnsNeeded">The set of columns the calling component operates on.</param>
/// <param name="map">An ascending array of values from 0 inclusive
/// to <paramref name="lim"/> exclusive, holding all values for which
/// <paramref name="columnsNeeded"/> are present.
/// (The respective index appears in the <paramref name="columnsNeeded"/> collection).</param>
/// <param name="invMap">Forms an inverse mapping of <paramref name="map"/>,
/// so that <c><paramref name="invMap"/>[<paramref name="map"/>[i]] == i</c>,
/// and for other entries not appearing in <paramref name="map"/>,
/// <c><paramref name="invMap"/>[i] == -1</c></param>
public static void BuildSubsetMaps(int lim, IEnumerable<DataViewSchema.Column> columnsNeeded, out int[] map, out int[] invMap)
{
Contracts.CheckParam(lim >= 0, nameof(lim));
Contracts.CheckValue(columnsNeeded, nameof(columnsNeeded));
// REVIEW: Better names?
List<int> mapList = new List<int>();
invMap = Enumerable.Repeat(-1, lim).ToArray<int>();
foreach (var col in columnsNeeded)
{
Contracts.Check(col.Index < lim);
invMap[col.Index] = mapList.Count;
mapList.Add(col.Index);
}
map = mapList.ToArray();
}
public static T[] Concat<T>(T[] a, T[] b)
{
if (a == null)
return b;
if (b == null)
return a;
if (a.Length == 0)
return b;
if (b.Length == 0)
return a;
var res = new T[a.Length + b.Length];
Array.Copy(a, res, a.Length);
Array.Copy(b, 0, res, a.Length, b.Length);
return res;
}
public static T[] Concat<T>(params T[][] arrays)
{
// Total size.
int size = 0;
// First non-null.
T[] nn = null;
// First non-empty.
T[] ne = null;
foreach (var a in arrays)
{
if (a == null)
continue;
checked { size += a.Length; }
if (nn == null)
nn = a;
if (ne == null && size > 0)
ne = a;
}
Contracts.Assert(nn != null || size == 0);
Contracts.Assert((ne == null) == (size == 0));
// If the size is zero, return the first non-null.
if (size == 0)
return nn;
// If there is only one non-empty, return it.
if (size == ne.Length)
return ne;
var res = new T[size];
int ivDst = 0;
foreach (var a in arrays)
{
int cv = Utils.Size(a);
if (cv == 0)
continue;
Array.Copy(a, 0, res, ivDst, cv);
ivDst += cv;
}
Contracts.Assert(ivDst == size);
return res;
}
/// <summary>
/// Resizes the array if necessary, to ensure that it has at least <paramref name="min"/> elements.
/// </summary>
/// <param name="array">The array to resize. Can be null.</param>
/// <param name="min">The minimum number of items the new array must have.</param>
/// <param name="keepOld">True means that the old array is preserved, if possible (Array.Resize is called). False
/// means that a new array will be allocated.
/// </param>
/// <returns>The new size, that is no less than <paramref name="min"/>.</returns>
public static int EnsureSize<T>(ref T[] array, int min, bool keepOld = true)
{
return EnsureSize(ref array, min, Utils.ArrayMaxSize, keepOld);
}
/// <summary>
/// Resizes the array if necessary, to ensure that it has at least <paramref name="min"/> and at most <paramref name="max"/> elements.
/// </summary>
/// <param name="array">The array to resize. Can be null.</param>
/// <param name="min">The minimum number of items the new array must have.</param>
/// <param name="max">The maximum number of items the new array can have.</param>
/// <param name="keepOld">True means that the old array is preserved, if possible (Array.Resize is called). False
/// means that a new array will be allocated.
/// </param>
/// <returns>The new size, that is no less than <paramref name="min"/> and no more that <paramref name="max"/>.</returns>
public static int EnsureSize<T>(ref T[] array, int min, int max, bool keepOld = true)
=> EnsureSize(ref array, min, max, keepOld, out bool _);
public static int EnsureSize<T>(ref T[] array, int min, int max, bool keepOld, out bool resized)
{
return ArrayUtils.EnsureSize(ref array, min, max, keepOld, out resized);
}
/// <summary>
/// Returns the number of set bits in a bit array.
/// </summary>
public static int GetCardinality(BitArray bitArray)
{
Contracts.CheckValue(bitArray, nameof(bitArray));
int cnt = 0;
foreach (bool b in bitArray)
{
if (b)
cnt++;
}
return cnt;
}
private static MethodInfo MarshalInvokeCheckAndCreate<TRet>(Type genArg, Delegate func)
{
var meth = MarshalActionInvokeCheckAndCreate(genArg, func);
if (meth.ReturnType != typeof(TRet))
throw Contracts.ExceptParam(nameof(func), "Cannot be generic on return type");
return meth;
}
private static MethodInfo MarshalInvokeCheckAndCreate<TRet>(Type[] genArgs, Delegate func)
{
var meth = MarshalActionInvokeCheckAndCreate(genArgs, func);
if (meth.ReturnType != typeof(TRet))
throw Contracts.ExceptParam(nameof(func), "Cannot be generic on return type");
return meth;
}
// REVIEW: n-argument versions? The multi-column re-application problem?
// Think about how to address these.
/// <summary>
/// Given a generic method with a single type parameter, re-create the generic method on a new type,
/// then reinvoke the method and return the result. A common pattern throughout the code base is to
/// have some sort of generic method, whose parameters and return value are, as defined, non-generic,
/// but whose code depends on some sort of generic type parameter. This utility method exists to make
/// this common pattern more convenient, and also safer so that the arguments, if any, can be type
/// checked at compile time instead of at runtime.
///
/// Because it is strongly typed, this can only be applied to methods whose return type
/// is known at compile time, that is, that do not depend on the type parameter of the method itself.
/// </summary>
/// <typeparam name="TTarget">The type of the receiver of the instance method.</typeparam>
/// <typeparam name="TResult">The type of the return value of the method.</typeparam>
/// <param name="func">A delegate that should be a generic method with a single type parameter.
/// The generic method definition will be extracted, then a new method will be created with the
/// given type parameter, then the method will be invoked.</param>
/// <param name="target">The target of the invocation.</param>
/// <param name="genArg">The new type parameter for the generic method</param>
/// <returns>The return value of the invoked function</returns>
public static TResult MarshalInvoke<TTarget, TResult>(FuncInstanceMethodInfo1<TTarget, TResult> func, TTarget target, Type genArg)
where TTarget : class
{
var meth = func.MakeGenericMethod(genArg);
return (TResult)meth.Invoke(target, null);
}
/// <summary>
/// A static version of <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>.
/// </summary>
public static TResult MarshalInvoke<TResult>(FuncStaticMethodInfo1<TResult> func, Type genArg)
{
var meth = func.MakeGenericMethod(genArg);
return (TResult)meth.Invoke(null, null);
}
/// <summary>
/// A one-argument version of <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>.
/// </summary>
public static TResult MarshalInvoke<TTarget, TArg1, TResult>(FuncInstanceMethodInfo1<TTarget, TArg1, TResult> func, TTarget target, Type genArg, TArg1 arg1)
where TTarget : class
{
var meth = func.MakeGenericMethod(genArg);
return (TResult)meth.Invoke(target, new object[] { arg1 });
}
/// <summary>
/// A one-argument version of <see cref="MarshalInvoke{TResult}(FuncStaticMethodInfo1{TResult}, Type)"/>.
/// </summary>
public static TResult MarshalInvoke<TArg1, TResult>(FuncStaticMethodInfo1<TArg1, TResult> func, Type genArg, TArg1 arg1)
{
var meth = func.MakeGenericMethod(genArg);
return (TResult)meth.Invoke(null, new object[] { arg1 });
}
/// <summary>
/// A one-argument, three-type-parameter version of <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>.
/// </summary>
public static TResult MarshalInvoke<TTarget, TArg1, TResult>(FuncInstanceMethodInfo3<TTarget, TArg1, TResult> func, TTarget target, Type genArg1, Type genArg2, Type genArg3, TArg1 arg1)
where TTarget : class
{
var meth = func.MakeGenericMethod(genArg1, genArg2, genArg3);
return (TResult)meth.Invoke(target, new object[] { arg1 });
}
/// <summary>
/// A one-argument, three-type-parameter version of <see cref="MarshalInvoke{TResult}(FuncStaticMethodInfo1{TResult}, Type)"/>.
/// </summary>
public static TResult MarshalInvoke<TArg1, TResult>(FuncStaticMethodInfo3<TArg1, TResult> func, Type genArg1, Type genArg2, Type genArg3, TArg1 arg1)
{
var meth = func.MakeGenericMethod(genArg1, genArg2, genArg3);
return (TResult)meth.Invoke(null, new object[] { arg1 });
}
/// <summary>
/// A two-argument version of <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>.
/// </summary>
public static TRet MarshalInvoke<TArg1, TArg2, TRet>(Func<TArg1, TArg2, TRet> func, Type genArg, TArg1 arg1, TArg2 arg2)
{
var meth = MarshalInvokeCheckAndCreate<TRet>(genArg, func);
return (TRet)meth.Invoke(func.Target, new object[] { arg1, arg2 });
}
/// <summary>
/// A three-argument version of <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>.
/// </summary>
public static TRet MarshalInvoke<TArg1, TArg2, TArg3, TRet>(Func<TArg1, TArg2, TArg3, TRet> func, Type genArg,
TArg1 arg1, TArg2 arg2, TArg3 arg3)
{
var meth = MarshalInvokeCheckAndCreate<TRet>(genArg, func);
return (TRet)meth.Invoke(func.Target, new object[] { arg1, arg2, arg3 });
}
/// <summary>
/// A four-argument version of <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>.
/// </summary>
public static TRet MarshalInvoke<TArg1, TArg2, TArg3, TArg4, TRet>(Func<TArg1, TArg2, TArg3, TArg4, TRet> func,
Type genArg, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4)
{
var meth = MarshalInvokeCheckAndCreate<TRet>(genArg, func);
return (TRet)meth.Invoke(func.Target, new object[] { arg1, arg2, arg3, arg4 });
}
/// <summary>
/// A five-argument version of <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>.
/// </summary>
public static TRet MarshalInvoke<TArg1, TArg2, TArg3, TArg4, TArg5, TRet>(Func<TArg1, TArg2, TArg3, TArg4, TArg5, TRet> func,
Type genArg, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5)
{
var meth = MarshalInvokeCheckAndCreate<TRet>(genArg, func);
return (TRet)meth.Invoke(func.Target, new object[] { arg1, arg2, arg3, arg4, arg5 });
}
/// <summary>
/// A six-argument version of <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>.
/// </summary>
public static TRet MarshalInvoke<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TRet>(Func<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TRet> func,
Type genArg, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6)
{
var meth = MarshalInvokeCheckAndCreate<TRet>(genArg, func);
return (TRet)meth.Invoke(func.Target, new object[] { arg1, arg2, arg3, arg4, arg5, arg6 });
}
/// <summary>
/// A seven-argument version of <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>.
/// </summary>
public static TRet MarshalInvoke<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TRet>(Func<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TRet> func,
Type genArg, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7)
{
var meth = MarshalInvokeCheckAndCreate<TRet>(genArg, func);
return (TRet)meth.Invoke(func.Target, new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7 });
}
/// <summary>
/// An eight-argument version of <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>.
/// </summary>
public static TRet MarshalInvoke<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TRet>(Func<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TRet> func,
Type genArg, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8)
{
var meth = MarshalInvokeCheckAndCreate<TRet>(genArg, func);
return (TRet)meth.Invoke(func.Target, new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 });
}
/// <summary>
/// A nine-argument version of <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>.
/// </summary>
public static TRet MarshalInvoke<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TRet>(
Func<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TRet> func,
Type genArg, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8, TArg9 arg9)
{
var meth = MarshalInvokeCheckAndCreate<TRet>(genArg, func);
return (TRet)meth.Invoke(func.Target, new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 });
}
/// <summary>
/// A ten-argument version of <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>.
/// </summary>
public static TRet MarshalInvoke<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TRet>(
Func<TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TRet> func,
Type genArg, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8, TArg9 arg9, TArg10 arg10)
{
var meth = MarshalInvokeCheckAndCreate<TRet>(genArg, func);
return (TRet)meth.Invoke(func.Target, new object[] { arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10 });
}
/// <summary>
/// A 2 argument and n type version of <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>.
/// </summary>
public static TRet MarshalInvoke<TArg1, TArg2, TRet>(
Func<TArg1, TArg2, TRet> func,
Type[] genArgs, TArg1 arg1, TArg2 arg2)
{
var meth = MarshalInvokeCheckAndCreate<TRet>(genArgs, func);
return (TRet)meth.Invoke(func.Target, new object[] { arg1, arg2});
}
private static MethodInfo MarshalActionInvokeCheckAndCreate(Type genArg, Delegate func)
{
Contracts.CheckValue(genArg, nameof(genArg));
Contracts.CheckValue(func, nameof(func));
var meth = func.GetMethodInfo();
Contracts.CheckParam(meth.IsGenericMethod, nameof(func), "Should be generic but is not");
Contracts.CheckParam(meth.GetGenericArguments().Length == 1, nameof(func),
"Should have exactly one generic type parameter but does not");
meth = meth.GetGenericMethodDefinition().MakeGenericMethod(genArg);
return meth;
}
private static MethodInfo MarshalActionInvokeCheckAndCreate(Type[] typeArguments, Delegate func)
{
Contracts.CheckValue(typeArguments, nameof(typeArguments));
Contracts.CheckValue(func, nameof(func));
var meth = func.GetMethodInfo();
Contracts.CheckParam(meth.IsGenericMethod, nameof(func), "Should be generic but is not");
Contracts.CheckParam(meth.GetGenericArguments().Length == typeArguments.Length, nameof(func),
"Method should have exactly the same number of generic type parameters as list passed in but it does not.");
meth = meth.GetGenericMethodDefinition().MakeGenericMethod(typeArguments);
return meth;
}
/// <summary>
/// This is akin to <see cref="MarshalInvoke{TTarget, TResult}(FuncInstanceMethodInfo1{TTarget, TResult}, TTarget, Type)"/>, except applied to
/// <see cref="Action"/> instead of <see cref="Func{TRet}"/>.
/// </summary>
/// <param name="act">A delegate that should be a generic method with a single type parameter.
/// The generic method definition will be extracted, then a new method will be created with the
/// given type parameter, then the method will be invoked.</param>
/// <param name="genArg">The new type parameter for the generic method</param>
public static void MarshalActionInvoke(Action act, Type genArg)
{
var meth = MarshalActionInvokeCheckAndCreate(genArg, act);
meth.Invoke(act.Target, null);
}
/// <summary>
/// A one-argument version of <see cref="MarshalActionInvoke(Action, Type)"/>.
/// </summary>
public static void MarshalActionInvoke<TArg1>(Action<TArg1> act, Type genArg, TArg1 arg1)
{
var meth = MarshalActionInvokeCheckAndCreate(genArg, act);
meth.Invoke(act.Target, new object[] { arg1 });
}
/// <summary>
/// A two-argument version of <see cref="MarshalActionInvoke(Action, Type)"/>.
/// </summary>
public static void MarshalActionInvoke<TArg1, TArg2>(Action<TArg1, TArg2> act, Type genArg, TArg1 arg1, TArg2 arg2)
{
var meth = MarshalActionInvokeCheckAndCreate(genArg, act);
meth.Invoke(act.Target, new object[] { arg1, arg2 });
}
/// <summary>
/// A three-argument version of <see cref="MarshalActionInvoke(Action, Type)"/>.
/// </summary>
public static void MarshalActionInvoke<TArg1, TArg2, TArg3>(Action<TArg1, TArg2, TArg3> act, Type genArg, TArg1 arg1, TArg2 arg2, TArg3 arg3)
{
var meth = MarshalActionInvokeCheckAndCreate(genArg, act);
meth.Invoke(act.Target, new object[] { arg1, arg2, arg3 });
}
/// <summary>
/// A four-argument version of <see cref="MarshalActionInvoke(Action, Type)"/>.
/// </summary>
public static void MarshalActionInvoke<TArg1, TArg2, TArg3, TArg4>(Action<TArg1, TArg2, TArg3, TArg4> act, Type genArg, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4)
{
var meth = MarshalActionInvokeCheckAndCreate(genArg, act);
meth.Invoke(act.Target, new object[] { arg1, arg2, arg3, arg4 });
}
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr =
Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
}
public static int Count<TSource>(this ReadOnlySpan<TSource> source, Func<TSource, bool> predicate)
{
Contracts.CheckValue(predicate, nameof(predicate));
int result = 0;
for (int i = 0; i < source.Length; i++)
{
if (predicate(source[i]))
result++;
}
return result;
}
public static bool All<TSource>(this ReadOnlySpan<TSource> source, Func<TSource, bool> predicate)
{
Contracts.CheckValue(predicate, nameof(predicate));
for (int i = 0; i < source.Length; i++)
{
if (!predicate(source[i]))
return false;
}
return true;
}
}
}
| 42.335423 | 193 | 0.555572 | [
"MIT"
] | dcostea/machinelearning | src/Microsoft.ML.Core/Utilities/Utils.cs | 54,020 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Dnx.Tooling.List;
using Microsoft.Dnx.Runtime;
using Microsoft.Dnx.Runtime.Common.CommandLine;
namespace Microsoft.Dnx.Tooling
{
internal static class ListConsoleCommand
{
public static void Register(CommandLineApplication cmdApp, ReportsFactory reportsFactory, IApplicationEnvironment appEnvironment)
{
cmdApp.Command("list", c =>
{
c.Description = "Print the dependencies of a given project";
var showAssemblies = c.Option("-a|--assemblies",
"Show the assembly files that are depended on by given project",
CommandOptionType.NoValue);
var frameworks = c.Option("--framework <TARGET_FRAMEWORK>",
"Show dependencies for only the given frameworks",
CommandOptionType.MultipleValue);
var runtimeFolder = c.Option("--runtime <PATH>",
"The folder containing all available framework assemblies",
CommandOptionType.SingleValue);
var details = c.Option("--details",
"Show the details of how each dependency is introduced",
CommandOptionType.NoValue);
var resultsFilter = c.Option("--filter <PATTERN>",
"Filter the libraries referenced by the project base on their names. The matching pattern supports * and ?",
CommandOptionType.SingleValue);
var argProject = c.Argument("[project]", "Path to project, default is current directory");
c.HelpOption("-?|-h|--help");
c.OnExecute(() =>
{
c.ShowRootCommandFullNameAndVersion();
var options = new DependencyListOptions(reportsFactory.CreateReports(verbose: true, quiet: false), argProject)
{
TargetFrameworks = frameworks.Values,
ShowAssemblies = showAssemblies.HasValue(),
RuntimeFolder = runtimeFolder.Value(),
Details = details.HasValue(),
ResultsFilter = resultsFilter.Value()
};
if (!options.Valid)
{
if (options.Project == null)
{
options.Reports.Error.WriteLine(string.Format("Unable to locate {0}.".Red(), Runtime.Project.ProjectFileName));
return 1;
}
else
{
options.Reports.Error.WriteLine("Invalid options.".Red());
return 2;
}
}
var command = new DependencyListCommand(options, appEnvironment.RuntimeFramework);
return command.Execute();
});
});
}
}
}
| 46.304348 | 139 | 0.530203 | [
"Apache-2.0"
] | cemoses/aspnet | dnx-dev/src/Microsoft.Dnx.Tooling/ConsoleCommands/ListConsoleCommand.cs | 3,197 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using StrawberryShake.Transport.WebSockets.Messages;
namespace StrawberryShake.Transport.WebSockets
{
/// <summary>
/// A protocol that can be used to communicate to a GraphQL server over
/// <see cref="ISocketClient"/>
/// </summary>
public abstract class SocketProtocolBase : ISocketProtocol
{
private bool _disposed;
private readonly HashSet<OnReceiveAsync> _listeners = new();
/// <inheritdoc />
public event EventHandler Disposed = default!;
/// <inheritdoc />
public abstract Task StartOperationAsync(
string operationId,
OperationRequest request,
CancellationToken cancellationToken);
/// <inheritdoc />
public abstract Task StopOperationAsync(
string operationId,
CancellationToken cancellationToken);
/// <inheritdoc />
public abstract Task InitializeAsync(CancellationToken cancellationToken);
/// <inheritdoc />
public abstract Task TerminateAsync(CancellationToken cancellationToken);
/// <inheritdoc />
public void Subscribe(OnReceiveAsync listener)
{
_listeners.Add(listener);
}
/// <inheritdoc />
public void Unsubscribe(OnReceiveAsync listener)
{
_listeners.Remove(listener);
}
/// <summary>
/// Notify all listeners that a message is received
/// </summary>
/// <param name="operationId">The ide of the operation that the message belongs to</param>
/// <param name="message">The operation message</param>
/// <param name="cancellationToken">A token to cancel processing the message</param>
/// <returns>A value task that is completed once all subscribers are notified</returns>
protected async ValueTask Notify(
string operationId,
OperationMessage message,
CancellationToken cancellationToken)
{
foreach (var listener in _listeners)
{
await listener(operationId, message, cancellationToken).ConfigureAwait(false);
}
}
/// <inheritdoc />
public virtual ValueTask DisposeAsync()
{
if (!_disposed)
{
return default;
}
Disposed.Invoke(this, EventArgs.Empty);
_disposed = true;
return default;
}
}
}
| 31.168675 | 98 | 0.608427 | [
"MIT"
] | AccountTechnologies/hotchocolate | src/StrawberryShake/Client/src/Transport.WebSockets/SocketProtocolBase.cs | 2,587 | 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void MultiplyAddByScalar_Vector128_Int16()
{
var test = new SimpleTernaryOpTest__MultiplyAddByScalar_Vector128_Int16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__MultiplyAddByScalar_Vector128_Int16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] inArray3, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int16, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int16> _fld1;
public Vector128<Int16> _fld2;
public Vector64<Int16> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyAddByScalar_Vector128_Int16 testClass)
{
var result = AdvSimd.MultiplyAddByScalar(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyAddByScalar_Vector128_Int16 testClass)
{
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
fixed (Vector64<Int16>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyAddByScalar(
AdvSimd.LoadVector128((Int16*)(pFld1)),
AdvSimd.LoadVector128((Int16*)(pFld2)),
AdvSimd.LoadVector64((Int16*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Int16[] _data3 = new Int16[Op3ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private static Vector64<Int16> _clsVar3;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private Vector64<Int16> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplyAddByScalar_Vector128_Int16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
}
public SimpleTernaryOpTest__MultiplyAddByScalar_Vector128_Int16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld3), ref Unsafe.As<Int16, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.MultiplyAddByScalar(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.MultiplyAddByScalar(
AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddByScalar), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>), typeof(Vector64<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector64<Int16>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.MultiplyAddByScalar), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>), typeof(Vector64<Int16>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector64((Int16*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.MultiplyAddByScalar(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int16>* pClsVar2 = &_clsVar2)
fixed (Vector64<Int16>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.MultiplyAddByScalar(
AdvSimd.LoadVector128((Int16*)(pClsVar1)),
AdvSimd.LoadVector128((Int16*)(pClsVar2)),
AdvSimd.LoadVector64((Int16*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray3Ptr);
var result = AdvSimd.MultiplyAddByScalar(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray3Ptr));
var result = AdvSimd.MultiplyAddByScalar(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplyAddByScalar_Vector128_Int16();
var result = AdvSimd.MultiplyAddByScalar(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplyAddByScalar_Vector128_Int16();
fixed (Vector128<Int16>* pFld1 = &test._fld1)
fixed (Vector128<Int16>* pFld2 = &test._fld2)
fixed (Vector64<Int16>* pFld3 = &test._fld3)
{
var result = AdvSimd.MultiplyAddByScalar(
AdvSimd.LoadVector128((Int16*)(pFld1)),
AdvSimd.LoadVector128((Int16*)(pFld2)),
AdvSimd.LoadVector64((Int16*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.MultiplyAddByScalar(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
fixed (Vector64<Int16>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyAddByScalar(
AdvSimd.LoadVector128((Int16*)(pFld1)),
AdvSimd.LoadVector128((Int16*)(pFld2)),
AdvSimd.LoadVector64((Int16*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyAddByScalar(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyAddByScalar(
AdvSimd.LoadVector128((Int16*)(&test._fld1)),
AdvSimd.LoadVector128((Int16*)(&test._fld2)),
AdvSimd.LoadVector64((Int16*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, Vector64<Int16> op3, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] inArray3 = new Int16[Op3ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] inArray3 = new Int16[Op3ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] secondOp, Int16[] thirdOp, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.MultiplyAdd(firstOp[i], secondOp[i], thirdOp[0]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyAddByScalar)}<Int16>(Vector128<Int16>, Vector128<Int16>, Vector64<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 46.155594 | 200 | 0.595356 | [
"MIT"
] | 06needhamt/runtime | src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyAddByScalar.Vector128.Int16.cs | 26,401 | C# |
using Atlas.Entities;
using Atlas.EventSystem;
namespace Atlas.Events
{
/// <summary>
/// Fires before a window gets damaged.
/// </summary>
public class DamagingWindow : BoolEvent
{
/// <summary>
/// Gets the player that is damaging the window. <b>Can be null.</b>
/// </summary>
public Player Player { get; }
/// <summary>
/// Gets the window that is being damaged.
/// </summary>
public Window Window { get; }
/// <summary>
/// Gets or sets the dealt damage.
/// </summary>
public float Damage { get; set; }
public DamagingWindow(Window window, float damage, bool allow, Player player = null)
{
Player = player;
Window = window;
Damage = damage;
IsAllowed = allow;
}
}
}
| 24.885714 | 92 | 0.531573 | [
"MIT"
] | Semper00/Atlas | Atlas/Events/DamagingWindow.cs | 873 | C# |
namespace NLock.NLockFile.Encryption
{
internal interface IEncryptionStrategy
{
byte[] Encrypt(byte[] keyArray, byte[] content, byte[] key = null);
byte[] Decrypt(byte[] keyArray, byte[] content, byte[] key = null);
}
} | 28.555556 | 76 | 0.618677 | [
"Apache-2.0"
] | KRVPerera/NLock | NLock_with_setup/NLock_with_setup/NLockFile/NLockFile/Encryption/EncryptionStratergy.cs | 259 | C# |
using Sharpen;
namespace android.webkit
{
[Sharpen.NakedStub]
public class PluginFullScreenHolder
{
}
}
| 10.9 | 36 | 0.761468 | [
"Apache-2.0"
] | Conceptengineai/XobotOS | android/generated/android/webkit/PluginFullScreenHolder.cs | 109 | C# |
namespace RollbarDotNet.Core
{
using Abstractions;
using Blacklisters;
using Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
public static class ServiceExtensions
{
public static IServiceCollection AddRollbar(this IServiceCollection services)
{
return services
.AddSingleton<IBuilder, ConfigurationBuilder>()
.AddSingleton<IBuilder, EnvironmentBuilder>()
.AddSingleton<IBuilder, NotifierBuilder>()
.AddSingleton<IDateTime, SystemDateTime>()
.AddSingleton<IEnvironment, SystemEnvironment>()
.AddSingleton<IBlacklister, ConfigurationBlacklister>()
.AddSingleton<IBlacklistCollection, BlacklistCollection>()
.AddSingleton<IExceptionBuilder, ExceptionBuilder>()
.AddSingleton<RollbarClient>()
.AddScoped<Rollbar>();
}
public static IServiceCollection AddRollbarWeb(this IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
return services.AddRollbar()
.AddSingleton<IBuilder, ServerBuilder>()
.AddScoped<IBuilder, RequestBuilder>()
.AddScoped<IBuilder, PersonBuilder>();
}
}
} | 40.361111 | 88 | 0.647626 | [
"MIT"
] | ECrownofFire/RollbarDotNet | RollbarDotNet/Core/ServiceExtensions.cs | 1,455 | C# |
// Copyright 2012-2018 Chris Patterson
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace GreenPipes.Agents
{
using System.Threading.Tasks;
/// <summary>
/// A handle to a PipeContext instance (of type <typeparamref name="TContext"/>), which can be disposed
/// once it is no longer needed (or can no longer be used).
/// </summary>
/// <typeparam name="TContext"></typeparam>
public interface PipeContextHandle<TContext> :
IAsyncDisposable
where TContext : class, PipeContext
{
/// <summary>
/// True if the context has been disposed (and can no longer be used)
/// </summary>
bool IsDisposed { get; }
/// <summary>
/// The <typeparamref name="TContext"/> context
/// </summary>
Task<TContext> Context { get; }
}
} | 36.702703 | 107 | 0.659794 | [
"Apache-2.0"
] | aallfredo/MassTransitPHP | src/MassTransit/Agents/PipeContextHandle.cs | 1,360 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.1433
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Mediachase.UI.Web.Apps.MetaUIEntity.Primitives {
/// <summary>
/// IntegerPercent_Filter__NotIn class.
/// </summary>
/// <remarks>
/// Auto-generated class.
/// </remarks>
public partial class IntegerPercent_Filter__NotIn {
/// <summary>
/// container control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl container;
/// <summary>
/// taText control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTextArea taText;
/// <summary>
/// imgOk control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ImageButton imgOk;
/// <summary>
/// lblText control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblText;
/// <summary>
/// lblError control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblError;
}
}
| 33.455882 | 84 | 0.528791 | [
"MIT"
] | InstantBusinessNetwork/IBN | Source/Server/WebPortal/Apps/MetaUIEntity/Primitives/IntegerPercent.Filter.@.@.NotIn.ascx.designer.cs | 2,275 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Logging;
using osu.Framework.Screens;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Input;
using osu.Game.Online.API;
using osu.Game.Online.Multiplayer;
using osu.Game.Overlays;
using osu.Game.Screens.Menu;
using osu.Game.Screens.Multi.Components;
using osu.Game.Screens.Multi.Lounge;
using osu.Game.Screens.Multi.Lounge.Components;
using osu.Game.Screens.Multi.Match;
using osu.Game.Screens.Multi.Match.Components;
using osuTK;
namespace osu.Game.Screens.Multi
{
[Cached]
public class Multiplayer : OsuScreen, IOnlineComponent
{
public override bool CursorVisible => (screenStack.CurrentScreen as IMultiplayerSubScreen)?.CursorVisible ?? true;
// this is required due to PlayerLoader eventually being pushed to the main stack
// while leases may be taken out by a subscreen.
public override bool DisallowExternalBeatmapRulesetChanges => true;
private readonly MultiplayerWaveContainer waves;
private readonly OsuButton createButton;
private readonly LoungeSubScreen loungeSubScreen;
private readonly ScreenStack screenStack;
private readonly IBindable<bool> isIdle = new BindableBool();
[Cached]
private readonly Bindable<Room> selectedRoom = new Bindable<Room>();
[Cached]
private readonly Bindable<FilterCriteria> currentFilter = new Bindable<FilterCriteria>(new FilterCriteria());
[Resolved]
private MusicController music { get; set; }
[Cached(Type = typeof(IRoomManager))]
private RoomManager roomManager;
[Resolved]
private OsuGameBase game { get; set; }
[Resolved]
private IAPIProvider api { get; set; }
[Resolved(CanBeNull = true)]
private OsuLogo logo { get; set; }
private readonly Drawable header;
private readonly Drawable headerBackground;
public Multiplayer()
{
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.Both;
Padding = new MarginPadding { Horizontal = -HORIZONTAL_OVERFLOW_PADDING };
var backgroundColour = Color4Extensions.FromHex(@"3e3a44");
InternalChild = waves = new MultiplayerWaveContainer
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = backgroundColour,
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Top = Header.HEIGHT },
Children = new[]
{
header = new Container
{
RelativeSizeAxes = Axes.X,
Height = 400,
Children = new[]
{
headerBackground = new Container
{
RelativeSizeAxes = Axes.Both,
Width = 1.25f,
Masking = true,
Children = new Drawable[]
{
new HeaderBackgroundSprite
{
RelativeSizeAxes = Axes.X,
Height = 400 // Keep a static height so the header doesn't change as it's resized between subscreens
},
}
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Bottom = -1 }, // 1px padding to avoid a 1px gap due to masking
Child = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = ColourInfo.GradientVertical(backgroundColour.Opacity(0.5f), backgroundColour)
},
}
}
},
screenStack = new MultiplayerSubScreenStack { RelativeSizeAxes = Axes.Both }
}
},
new Header(screenStack),
createButton = new CreateRoomButton
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Action = createRoom
},
roomManager = new RoomManager()
}
};
screenStack.Push(loungeSubScreen = new LoungeSubScreen());
screenStack.ScreenPushed += screenPushed;
screenStack.ScreenExited += screenExited;
}
[BackgroundDependencyLoader(true)]
private void load(IdleTracker idleTracker)
{
api.Register(this);
if (idleTracker != null)
isIdle.BindTo(idleTracker.IsIdle);
}
protected override void LoadComplete()
{
base.LoadComplete();
isIdle.BindValueChanged(idle => updatePollingRate(idle.NewValue), true);
}
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
{
var dependencies = new CachedModelDependencyContainer<Room>(base.CreateChildDependencies(parent));
dependencies.Model.BindTo(selectedRoom);
return dependencies;
}
private void updatePollingRate(bool idle)
{
if (!this.IsCurrentScreen())
{
roomManager.TimeBetweenListingPolls = 0;
roomManager.TimeBetweenSelectionPolls = 0;
}
else
{
switch (screenStack.CurrentScreen)
{
case LoungeSubScreen _:
roomManager.TimeBetweenListingPolls = idle ? 120000 : 15000;
roomManager.TimeBetweenSelectionPolls = idle ? 120000 : 15000;
break;
case MatchSubScreen _:
roomManager.TimeBetweenListingPolls = 0;
roomManager.TimeBetweenSelectionPolls = idle ? 30000 : 5000;
break;
default:
roomManager.TimeBetweenListingPolls = 0;
roomManager.TimeBetweenSelectionPolls = 0;
break;
}
}
Logger.Log($"Polling adjusted (listing: {roomManager.TimeBetweenListingPolls}, selection: {roomManager.TimeBetweenSelectionPolls})");
}
public void APIStateChanged(IAPIProvider api, APIState state)
{
if (state != APIState.Online)
Schedule(forcefullyExit);
}
private void forcefullyExit()
{
// This is temporary since we don't currently have a way to force screens to be exited
if (this.IsCurrentScreen())
{
while (this.IsCurrentScreen())
this.Exit();
}
else
{
this.MakeCurrent();
Schedule(forcefullyExit);
}
}
public override void OnEntering(IScreen last)
{
this.FadeIn();
waves.Show();
beginHandlingTrack();
}
public override void OnResuming(IScreen last)
{
this.FadeIn(250);
this.ScaleTo(1, 250, Easing.OutSine);
base.OnResuming(last);
beginHandlingTrack();
updatePollingRate(isIdle.Value);
}
public override void OnSuspending(IScreen next)
{
this.ScaleTo(1.1f, 250, Easing.InSine);
this.FadeOut(250);
endHandlingTrack();
updatePollingRate(isIdle.Value);
}
public override bool OnExiting(IScreen next)
{
roomManager.PartRoom();
waves.Hide();
this.Delay(WaveContainer.DISAPPEAR_DURATION).FadeOut();
if (screenStack.CurrentScreen != null)
loungeSubScreen.MakeCurrent();
endHandlingTrack();
base.OnExiting(next);
return false;
}
public override bool OnBackButton()
{
if ((screenStack.CurrentScreen as IMultiplayerSubScreen)?.OnBackButton() == true)
return true;
if (screenStack.CurrentScreen != null && !(screenStack.CurrentScreen is LoungeSubScreen))
{
screenStack.Exit();
return true;
}
return false;
}
protected override void LogoExiting(OsuLogo logo)
{
base.LogoExiting(logo);
// the wave overlay transition takes longer than expected to run.
logo.Delay(WaveContainer.DISAPPEAR_DURATION / 2).FadeOut();
}
private void createRoom()
{
loungeSubScreen.Open(new Room { Name = { Value = $"{api.LocalUser}'s awesome room" } });
}
private void beginHandlingTrack()
{
Beatmap.BindValueChanged(updateTrack, true);
}
private void endHandlingTrack()
{
cancelLooping();
Beatmap.ValueChanged -= updateTrack;
}
private void screenPushed(IScreen lastScreen, IScreen newScreen)
{
subScreenChanged(newScreen);
}
private void screenExited(IScreen lastScreen, IScreen newScreen)
{
subScreenChanged(newScreen);
if (screenStack.CurrentScreen == null && this.IsCurrentScreen())
this.Exit();
}
private void subScreenChanged(IScreen newScreen)
{
switch (newScreen)
{
case LoungeSubScreen _:
header.Delay(MultiplayerSubScreen.RESUME_TRANSITION_DELAY).ResizeHeightTo(400, MultiplayerSubScreen.APPEAR_DURATION, Easing.OutQuint);
headerBackground.MoveToX(0, MultiplayerSubScreen.X_MOVE_DURATION, Easing.OutQuint);
break;
case MatchSubScreen _:
header.ResizeHeightTo(135, MultiplayerSubScreen.APPEAR_DURATION, Easing.OutQuint);
headerBackground.MoveToX(-MultiplayerSubScreen.X_SHIFT, MultiplayerSubScreen.X_MOVE_DURATION, Easing.OutQuint);
break;
}
updatePollingRate(isIdle.Value);
createButton.FadeTo(newScreen is LoungeSubScreen ? 1 : 0, 200);
updateTrack();
}
private void updateTrack(ValueChangedEvent<WorkingBeatmap> _ = null)
{
if (screenStack.CurrentScreen is MatchSubScreen)
{
var track = Beatmap.Value?.Track;
if (track != null)
{
track.RestartPoint = Beatmap.Value.Metadata.PreviewTime;
track.Looping = true;
music.EnsurePlayingSomething();
}
}
else
{
cancelLooping();
}
}
private void cancelLooping()
{
var track = Beatmap?.Value?.Track;
if (track != null)
{
track.Looping = false;
track.RestartPoint = 0;
}
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
api?.Unregister(this);
}
private class MultiplayerWaveContainer : WaveContainer
{
protected override bool StartHidden => true;
public MultiplayerWaveContainer()
{
FirstWaveColour = Color4Extensions.FromHex(@"654d8c");
SecondWaveColour = Color4Extensions.FromHex(@"554075");
ThirdWaveColour = Color4Extensions.FromHex(@"44325e");
FourthWaveColour = Color4Extensions.FromHex(@"392850");
}
}
private class HeaderBackgroundSprite : MultiplayerBackgroundSprite
{
protected override UpdateableBeatmapBackgroundSprite CreateBackgroundSprite() => new BackgroundSprite { RelativeSizeAxes = Axes.Both };
private class BackgroundSprite : UpdateableBeatmapBackgroundSprite
{
protected override double TransformDuration => 200;
}
}
public class CreateRoomButton : PurpleTriangleButton
{
public CreateRoomButton()
{
Size = new Vector2(150, Header.HEIGHT - 20);
Margin = new MarginPadding
{
Top = 10,
Right = 10 + HORIZONTAL_OVERFLOW_PADDING,
};
}
[BackgroundDependencyLoader]
private void load()
{
Triangles.TriangleScale = 1.5f;
Text = "Create room";
}
}
}
}
| 34.985849 | 155 | 0.504989 | [
"MIT"
] | HDragonHR/osu | osu.Game/Screens/Multi/Multiplayer.cs | 14,413 | C# |
using System;
using System.Diagnostics;
using System.IO;
using Npgsql;
namespace Universe.Dashboard.DAL.Tests
{
class PgSqlDumper
{
// PGPASSWORD=pass psql -t -h localhost -p 5432 -U w3top -q -c "select 'Hello, ' || current_user;" -d w3top
public static void Dump(string connectionString, string fileName)
{
NpgsqlConnectionStringBuilder b = new NpgsqlConnectionStringBuilder(connectionString);
ProcessStartInfo si = new ProcessStartInfo("pg_dump", $"--inserts -h \"{b.Host}\" -U \"{b.Username}\" -p {b.Port} \"{b.Database}\"");
si.Environment["PGPASSWORD"] = b.Password;
si.RedirectStandardOutput = true;
string content;
using (var p = Process.Start(si))
{
p.WaitForExit();
content = p.StandardOutput.ReadToEnd();
if (p.ExitCode != 0)
throw new Exception($"Unable to dump PgSql DB. Exit Code is {p.ExitCode}");
}
try
{
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
}
catch
{
}
File.WriteAllText(fileName, content);
}
}
} | 32.512821 | 145 | 0.544953 | [
"MIT"
] | devizer/KernelManagementLab | Universe.Dashboard.DAL.Tests/PgSqlDumper.cs | 1,268 | C# |
// ReSharper disable All
using UnityEngine;
using System.Collections;
[AddComponentMenu("Camera-Control/3dsMax Camera Style")]
public class MouseHandler : MonoBehaviour
{
public Transform target;
public Vector3 targetOffset;
public float distance = 5.0f;
public float maxDistance = 20;
public float minDistance = .6f;
public float xSpeed = 200.0f;
public float ySpeed = 200.0f;
public int yMinLimit = -80;
public int yMaxLimit = 80;
public int zoomRate = 40;
public float panSpeed = 0.3f;
public float zoomDampening = 5.0f;
private float xDeg = 0.0f;
private float yDeg = 0.0f;
private float currentDistance;
private float desiredDistance;
private Quaternion currentRotation;
private Quaternion desiredRotation;
private Quaternion rotation;
private Vector3 position;
void Start() { Init(); }
void OnEnable() { Init(); }
public void Init()
{
//If there is no target, create a temporary target at 'distance' from the cameras current viewpoint
if (!target)
{
GameObject go = new GameObject("Cam Target");
go.transform.position = transform.position + (transform.forward * distance);
target = go.transform;
}
distance = Vector3.Distance(transform.position, target.position);
currentDistance = distance;
desiredDistance = distance;
//be sure to grab the current rotations as starting points.
position = transform.position;
rotation = transform.rotation;
currentRotation = transform.rotation;
desiredRotation = transform.rotation;
xDeg = Vector3.Angle(Vector3.right, transform.right);
yDeg = Vector3.Angle(Vector3.up, transform.up);
}
/*
* Camera logic on LateUpdate to only update after all character movement logic has been handled.
*/
void LateUpdate()
{
// If Control and Alt and Middle button? ZOOM!
if (Input.GetMouseButton(2) && Input.GetKey(KeyCode.LeftAlt) && Input.GetKey(KeyCode.LeftControl))
{
desiredDistance -= Input.GetAxis("Mouse Y") * Time.deltaTime * zoomRate * 0.125f * Mathf.Abs(desiredDistance);
}
// If middle mouse and left alt are selected? ORBIT
else if (Input.GetMouseButton(2) && Input.GetKey(KeyCode.LeftAlt))
{
xDeg += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
yDeg -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
////////OrbitAngle
//Clamp the vertical axis for the orbit
yDeg = ClampAngle(yDeg, yMinLimit, yMaxLimit);
// set camera rotation
desiredRotation = Quaternion.Euler(yDeg, xDeg, 0);
currentRotation = transform.rotation;
rotation = Quaternion.Lerp(currentRotation, desiredRotation, Time.deltaTime * zoomDampening);
transform.rotation = rotation;
}
// otherwise if middle mouse is selected, we pan by way of transforming the target in screenspace
else if (Input.GetMouseButton(2))
{
//grab the rotation of the camera so we can move in a psuedo local XY space
target.rotation = transform.rotation;
target.Translate(Vector3.right * -Input.GetAxis("Mouse X") * panSpeed);
target.Translate(transform.up * -Input.GetAxis("Mouse Y") * panSpeed, Space.World);
}
////////Orbit Position
// affect the desired Zoom distance if we roll the scrollwheel
desiredDistance -= Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * zoomRate * Mathf.Abs(desiredDistance);
//clamp the zoom min/max
//desiredDistance = Mathf.Clamp(desiredDistance, minDistance, maxDistance);
// For smoothing of the zoom, lerp distance
currentDistance = Mathf.Lerp(currentDistance, desiredDistance, Time.deltaTime * zoomDampening);
// calculate position based on the new currentDistance
position = target.position - (rotation * Vector3.forward * currentDistance + targetOffset);
transform.position = position;
}
private static float ClampAngle(float angle, float min, float max)
{
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp(angle, min, max);
}
} | 37.818966 | 122 | 0.639617 | [
"MIT"
] | MaxBondarchuk/Unity-Math-Graphs | Assets/Scripts/MouseHandler.cs | 4,389 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace VersionOne.SDK.APIClient.Tests.UtilityTests
{
[TestClass]
public class ModelsAndServicesTester
{
private IModelsAndServices _defaultTarget;
private IModelsAndServices _nonDefaultTarget;
[TestInitialize]
public void Setup()
{
_defaultTarget = new ModelsAndServices();
IConnectors connectors = new Connectors();
_nonDefaultTarget = new ModelsAndServices(connectors);
}
[TestCleanup]
public void TearDown()
{
_defaultTarget = null;
_nonDefaultTarget = null;
}
[TestMethod]
public void ServicesTest()
{
Assert.IsNotNull(_defaultTarget.Services);
Assert.IsNotNull(_defaultTarget.ServicesWithProxy);
Assert.IsNotNull(_nonDefaultTarget.Services);
Assert.IsNotNull(_nonDefaultTarget.ServicesWithProxy);
}
[TestMethod]
public void MetaModelTests()
{
Assert.IsNotNull(_defaultTarget.MetaModel);
Assert.IsNotNull(_defaultTarget.MetaModelWithProxy);
Assert.IsNotNull(_nonDefaultTarget.MetaModel);
Assert.IsNotNull(_nonDefaultTarget.MetaModelWithProxy);
}
[TestMethod]
public void ConfigTests()
{
Assert.IsNotNull(_defaultTarget.V1Configuration);
Assert.IsNotNull(_defaultTarget.V1ConfigurationWithProxy);
Assert.IsNotNull(_nonDefaultTarget.V1Configuration);
Assert.IsNotNull(_nonDefaultTarget.V1ConfigurationWithProxy);
}
}
}
| 31.092593 | 73 | 0.640262 | [
"BSD-3-Clause"
] | randu1459/VersionOne.SDK.NET.APIClient | APIClient.Tests/UtilityTests/ModelsAndServicesTester.cs | 1,681 | C# |
// Encog(tm) Artificial Intelligence Framework v2.5
// .Net Version
// http://www.heatonresearch.com/encog/
// http://code.google.com/p/encog-java/
//
// Copyright 2008-2010 by Heaton Research Inc.
//
// Released under the LGPL.
//
// This is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of
// the License, or (at your option) any later version.
//
// This software is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this software; if not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301 USA, or see the FSF site: http://www.fsf.org.
//
// Encog and Heaton Research are Trademarks of Heaton Research, Inc.
// For information on Heaton Research trademarks, visit:
//
// http://www.heatonresearch.com/copyright.html
#if logging
using log4net;
#endif
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Encog.MathUtil;
using Encog.Util;
namespace Encog.Parse.Tags.Read
{
/// <summary>
/// Base class used to read tags. This base class is used by both the
/// XML and HTML parsing.
/// </summary>
public class ReadTags
{
/// <summary>
/// The bullet character.
/// </summary>
public int CHAR_BULLET = 149;
/// <summary>
/// The bullet character.
/// </summary>
public int CHAR_TRADEMARK = 129;
/// <summary>
/// Maximum length string to read.
/// </summary>
public int MAX_LENGTH = 10000;
/// <summary>
/// A mapping of certain HTML encoded values to their actual
/// character values.
/// </summary>
private static IDictionary<String, char> charMap;
/// <summary>
/// The stream that we are parsing from.
/// </summary>
private PeekableInputStream source;
/// <summary>
/// The current HTML tag. Access this property if the read function returns
/// 0.
/// </summary>
private Tag tag = new Tag();
#if logging
/// <summary>
/// The logging object.
/// </summary>
private readonly ILog logger = LogManager.GetLogger(typeof(ReadTags));
#endif
/// <summary>
/// Are we locked, looking for an end tag? Such as the end of a
/// comment?
/// </summary>
private String lockedEndTag;
/// <summary>
/// Does a "fake" end-tag need to be added, because of a compound
/// tag (i.e. <br/>)? If so, this will hold a string for that tag.
/// </summary>
private String insertEndTag = null;
/// <summary>
/// The constructor should be passed an InputStream that we will parse from.
/// </summary>
/// <param name="istream">A stream to parse from.</param>
public ReadTags(Stream istream)
{
this.source = new PeekableInputStream(istream);
if (ReadTags.charMap == null)
{
ReadTags.charMap = new Dictionary<String, char>();
ReadTags.charMap["nbsp"] = ' ';
ReadTags.charMap["lt"] = '<';
ReadTags.charMap["gt"] = '>';
ReadTags.charMap["amp"] = '&';
ReadTags.charMap["quot"] = '\"';
ReadTags.charMap["bull"] = (char)CHAR_BULLET;
ReadTags.charMap["trade"] = (char)CHAR_TRADEMARK;
}
}
/// <summary>
/// Remove any whitespace characters that are next in the InputStream.
/// </summary>
protected void EatWhitespace()
{
while (char.IsWhiteSpace((char)this.source.Peek()))
{
this.source.Read();
}
}
/// <summary>
/// Return the last tag found, this is normally called just after the read
/// function returns a zero.
/// </summary>
public Tag LastTag
{
get
{
return this.tag;
}
}
/// <summary>
/// Checks to see if the next tag is the tag specified.
/// </summary>
/// <param name="name">The name of the tag desired.</param>
/// <param name="start">True if a starting tag is desired.</param>
/// <returns>True if the next tag matches these criteria.</returns>
public bool IsIt(String name, bool start)
{
if (!this.LastTag.Name.Equals(name))
{
return false;
}
if (start)
{
return this.LastTag.TagType == Tag.Type.BEGIN;
}
else
{
return this.LastTag.TagType == Tag.Type.END;
}
}
/// <summary>
/// Parse an attribute name, if one is present.
/// </summary>
/// <returns>Return the attribute name, or null if none present.</returns>
protected String ParseAttributeName()
{
EatWhitespace();
if ("\"\'".IndexOf((char)this.source.Peek()) == -1)
{
StringBuilder buffer = new StringBuilder();
while (!char.IsWhiteSpace((char)this.source.Peek())
&& (this.source.Peek() != '=')
&& (this.source.Peek() != '>')
&& (this.source.Peek() != -1))
{
int ch = ParseSpecialCharacter();
buffer.Append((char)ch);
}
return buffer.ToString();
}
else
{
return (ParseString());
}
}
/// <summary>
/// Parse any special characters
/// </summary>
/// <returns>The character that was parsed.</returns>
private char ParseSpecialCharacter()
{
char result = (char)this.source.Read();
int advanceBy = 0;
// is there a special character?
if (result == '&')
{
int ch = 0;
StringBuilder buffer = new StringBuilder();
// loop through and read special character
do
{
ch = this.source.Peek(advanceBy++);
if ((ch != '&') && (ch != ';') && !char.IsWhiteSpace((char)ch))
{
buffer.Append((char)ch);
}
} while ((ch != ';') && (ch != -1) && !char.IsWhiteSpace((char)ch));
String b = buffer.ToString().Trim().ToLower();
// did we find a special character?
if (b.Length > 0)
{
if (b[0] == '#')
{
try
{
result = (char)int.Parse(b.Substring(1));
}
catch (Exception)
{
advanceBy = 0;
}
}
else
{
if (ReadTags.charMap.ContainsKey(b))
{
result = ReadTags.charMap[b];
}
else
{
advanceBy = 0;
}
}
}
else
{
advanceBy = 0;
}
}
while (advanceBy > 0)
{
Read();
advanceBy--;
}
return result;
}
/// <summary>
/// Called to parse a double or single quote string.
/// </summary>
/// <returns>The string parsed.</returns>
protected String ParseString()
{
StringBuilder result = new StringBuilder();
EatWhitespace();
if ("\"\'".IndexOf((char)this.source.Peek()) != -1)
{
int delim = this.source.Read();
while ((this.source.Peek() != delim)
&& (this.source.Peek() != -1))
{
if (result.Length > MAX_LENGTH)
{
break;
}
int ch = ParseSpecialCharacter();
if ((ch == '\r') || (ch == '\n'))
{
continue;
}
result.Append((char)ch);
}
if ("\"\'".IndexOf((char)this.source.Peek()) != -1)
{
this.source.Read();
}
}
else
{
while (!char.IsWhiteSpace((char)this.source.Peek())
&& (this.source.Peek() != -1)
&& (this.source.Peek() != '>'))
{
result.Append(ParseSpecialCharacter());
}
}
return result.ToString();
}
/// <summary>
/// Called when a tag is detected. This method will parse the tag.
/// </summary>
protected void ParseTag()
{
this.tag.Clear();
this.insertEndTag = null;
StringBuilder tagName = new StringBuilder();
this.source.Read();
// Is it a comment?
if (this.source.Peek(TagConst.COMMENT_BEGIN))
{
this.source.Skip(TagConst.COMMENT_BEGIN.Length);
while (!this.source.Peek(TagConst.COMMENT_END))
{
int ch = this.source.Read();
if (ch != -1)
{
tagName.Append((char)ch);
}
else
{
break;
}
}
this.source.Skip(TagConst.COMMENT_END.Length);
this.tag.TagType = Tag.Type.COMMENT;
this.tag.Name = tagName.ToString();
return;
}
// Is it CDATA?
if (this.source.Peek(TagConst.CDATA_BEGIN))
{
this.source.Skip(TagConst.CDATA_BEGIN.Length);
while (!this.source.Peek(TagConst.CDATA_END))
{
int ch = this.source.Read();
if (ch != -1)
{
tagName.Append((char)ch);
}
else
{
break;
}
}
this.source.Skip(TagConst.CDATA_END.Length);
this.tag.TagType = Tag.Type.CDATA;
this.tag.Name = tagName.ToString();
return;
}
// Find the tag name
while (this.source.Peek() != -1)
{
// if this is the end of the tag, then stop
if (char.IsWhiteSpace((char)this.source.Peek())
|| (this.source.Peek() == '>'))
{
break;
}
// if this is both a begin and end tag then stop
if ((tagName.Length > 0) && (this.source.Peek() == '/'))
{
break;
}
tagName.Append((char)this.source.Read());
}
EatWhitespace();
if (tagName[0] == '/')
{
this.tag.Name = tagName.ToString().Substring(1);
this.tag.TagType = Tag.Type.END;
}
else
{
this.tag.Name = tagName.ToString();
this.tag.TagType = Tag.Type.BEGIN;
}
// get the attributes
while ((this.source.Peek() != '>') && (this.source.Peek() != -1))
{
String attributeName = ParseAttributeName();
String attributeValue = null;
if (attributeName.Equals("/"))
{
EatWhitespace();
if (this.source.Peek() == '>')
{
this.insertEndTag = this.tag.Name;
break;
}
}
// is there a value?
EatWhitespace();
if (this.source.Peek() == '=')
{
this.source.Read();
attributeValue = ParseString();
}
this.tag.SetAttribute(attributeName, attributeValue);
}
this.source.Read();
}
/// <summary>
/// Check to see if the ending tag is present.
/// </summary>
/// <param name="name">The type of end tag being sought.</param>
/// <returns>True if the ending tag was found.</returns>
private bool PeekEndTag(String name)
{
int i = 0;
// pass any whitespace
while ((this.source.Peek(i) != -1)
&& char.IsWhiteSpace((char)this.source.Peek(i)))
{
i++;
}
// is a tag beginning
if (this.source.Peek(i) != '<')
{
return false;
}
else
{
i++;
}
// pass any whitespace
while ((this.source.Peek(i) != -1)
&& char.IsWhiteSpace((char)this.source.Peek(i)))
{
i++;
}
// is it an end tag
if (this.source.Peek(i) != '/')
{
return false;
}
else
{
i++;
}
// pass any whitespace
while ((this.source.Peek(i) != -1)
&& char.IsWhiteSpace((char)this.source.Peek(i)))
{
i++;
}
// does the name match
for (int j = 0; j < name.Length; j++)
{
if (char.ToLower((char)this.source.Peek(i)) != char
.ToLower(name[j]))
{
return false;
}
i++;
}
return true;
}
/// <summary>
/// Read a single character from the HTML source, if this function returns
/// zero(0) then you should call getTag to see what tag was found. Otherwise
/// the value returned is simply the next character found.
/// </summary>
/// <returns>The character read, or zero if there is an HTML tag. If zero is
/// returned, then call getTag to get the next tag.</returns>
public int Read()
{
// handle inserting a "virtual" end tag
if (this.insertEndTag != null)
{
this.tag.Clear();
this.tag.Name = this.insertEndTag;
this.tag.TagType = Tag.Type.END;
this.insertEndTag = null;
return 0;
}
// handle locked end tag
if (this.lockedEndTag != null)
{
if (PeekEndTag(this.lockedEndTag))
{
this.lockedEndTag = null;
}
else
{
return this.source.Read();
}
}
// look for next tag
if (this.source.Peek() == '<')
{
ParseTag();
if ((this.tag.TagType == Tag.Type.BEGIN)
&& ((StringUtil.EqualsIgnoreCase(this.tag.Name, "script") )
|| (StringUtil.EqualsIgnoreCase(this.tag.Name, "style") )))
{
this.lockedEndTag = this.tag.Name.ToLower();
}
return 0;
}
else if (this.source.Peek() == '&')
{
return ParseSpecialCharacter();
}
else
{
return (this.source.Read());
}
}
/// <summary>
/// Read until we reach the next tag.
/// </summary>
/// <returns>True if a tag was found, false on EOF.</returns>
public bool ReadToTag()
{
int ch;
while ((ch = Read()) != -1)
{
if (ch == 0)
{
return true;
}
}
return false;
}
/// <summary>
/// Returns this object as a string.
/// </summary>
/// <returns>This object as a string.</returns>
public override String ToString()
{
StringBuilder result = new StringBuilder();
result.Append("[ReadTags: currentTag=");
if (this.tag != null)
{
result.Append(this.tag.ToString());
}
result.Append("]");
return result.ToString();
}
}
}
| 30.737478 | 84 | 0.427881 | [
"Apache-2.0"
] | MarcFletcher/OpenPokerAI | EncogFramework2.5/Parse/Tags/Read/ReadTags.cs | 17,797 | C# |
using Microsoft.Extensions.DependencyInjection;
using Okra.Builder;
using Okra.Lifetime;
using Okra.Navigation;
using Okra.Routing;
using Okra.State;
using System;
namespace Okra.DependencyInjection
{
public static class MvvmCoreServiceCollectionExtensions
{
public static IMvvmCoreBuilder AddMvvmCore(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
// TODO : These should be scoped!!!!
services.AddSingleton<INavigationManager, NavigationManager>();
services.AddSingleton<IRouteBuilder, RouteBuilder>();
services.AddSingleton<IViewRouter, ViewRouterProxy>();
services.AddSingleton<IOkraAppBuilder, OkraAppBuilder>();
services.AddScoped<IAppContainerFactory, AppContainerFactory>();
services.AddInjected<IAppContainer>();
services.AddInjected<IStateService>();
services.AddInjected<ILifetimeManager>();
return new MvvmCoreBuilder(services);
}
}
}
| 31.277778 | 84 | 0.666963 | [
"Apache-2.0"
] | OkraFramework/Okra.Core | src/Okra.Core/DependencyInjection/MvvmCoreServiceCollectionExtensions.cs | 1,128 | C# |
using System.Collections.Generic;
namespace GirLoader.Output;
public interface AccessorProvider
{
IEnumerable<Method> Methods { get; }
IEnumerable<Property> Properties { get; }
}
| 19 | 45 | 0.752632 | [
"MIT"
] | GirCore/gir.core | src/Generation/GirLoader/Output/AccessorProvider.cs | 192 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.