content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using UnityEngine;
namespace SS3D.Engine.Inventory
{
[Serializable]
public struct ItemSupply
{
[SerializeField] private ItemSupplyType type;
[SerializeField] private int drainRate;
[SerializeField] private int maxSupply;
[SerializeField] private int currentSupply;
public ItemSupplyType Type => type;
public int DrainRate => drainRate;
public int MaxSupply => maxSupply;
public int CurrentSupply => currentSupply;
public ItemSupply(ItemSupplyType type, int drainRate, int maxSupply, int currentSupply)
{
this.type = type;
this.drainRate = drainRate;
this.maxSupply = maxSupply;
this.currentSupply = currentSupply;
}
public ItemSupply WithNewSupplyValue(int newSupply)
{
return new ItemSupply(type, drainRate, maxSupply, newSupply);
}
}
} | 29.46875 | 95 | 0.640509 | [
"MIT"
] | CrazyMalk/SS3D | Assets/Engine/Inventory/ItemSupply.cs | 943 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace BioExcel.Visualizations.Common.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BioExcel.Visualizations.Common.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static System.Drawing.Bitmap about {
get {
object obj = ResourceManager.GetObject("about", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Auto Detect.
/// </summary>
internal static string AutoDetectString {
get {
return ResourceManager.GetString("AutoDetectString", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to http://blast2.cloudapp.net/BlastService.svc.
/// </summary>
internal static string AZURE_URI {
get {
return ResourceManager.GetString("AZURE_URI", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Microsoft Biology Foundation.
/// </summary>
internal static string CAPTION {
get {
return ResourceManager.GetString("CAPTION", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to http://mbf.codeplex.com.
/// </summary>
internal static string CodeplexURL {
get {
return ResourceManager.GetString("CodeplexURL", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Consensus Threshold.
/// </summary>
internal static string CONSENSUS_THRESHOLD {
get {
return ResourceManager.GetString("CONSENSUS_THRESHOLD", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to nr.
/// </summary>
internal static string DATABASE_NR {
get {
return ResourceManager.GetString("DATABASE_NR", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to nt.
/// </summary>
internal static string DATABASE_NT {
get {
return ResourceManager.GetString("DATABASE_NT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to em_rel.
/// </summary>
internal static string EM_REL {
get {
return ResourceManager.GetString("EM_REL", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The worksheet {0} is missing certain header information. Please select the genomic attributes and their corresponding columns in your selected worksheet.
/// </summary>
internal static string HEADER_SUBTEXT {
get {
return ResourceManager.GetString("HEADER_SUBTEXT", resourceCulture);
}
}
internal static System.Drawing.Bitmap Intersect_img1 {
get {
object obj = ResourceManager.GetObject("Intersect_img1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
internal static System.Drawing.Bitmap Intersect_Img2 {
get {
object obj = ResourceManager.GetObject("Intersect_Img2", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Intersect Inputs.
/// </summary>
internal static string INTERSECT_INPUT {
get {
return ResourceManager.GetString("INTERSECT_INPUT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Returns entire intervals from the first query that overlap the second query.
///The returned intervals are completely unchanged, and this option only filters
///out intervals that do not overlap with the second query..
/// </summary>
internal static string Intersect_OverlappingIntervals {
get {
return ResourceManager.GetString("Intersect_OverlappingIntervals", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Returns intervals that indicate the exact base pair overlap between the first
///query and the second query. The intervals returned are from the first query,
///and all fields besides start and end are guaranteed to remain unchanged..
/// </summary>
internal static string Intersect_OverlappingPiecesofIntervals {
get {
return ResourceManager.GetString("Intersect_OverlappingPiecesofIntervals", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Intervals with No overlap.
/// </summary>
internal static string INTERVAL_NO_OVERLAP {
get {
return ResourceManager.GetString("INTERVAL_NO_OVERLAP", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Non-overlapping pieces of intervals.
/// </summary>
internal static string INTERVAL_OVERLAP {
get {
return ResourceManager.GetString("INTERVAL_OVERLAP", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid .
/// </summary>
internal static string INVALID_TEXT {
get {
return ResourceManager.GetString("INVALID_TEXT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please choose Chromsome ID, Start and Stop columns.
/// </summary>
internal static string MANDATORY_COLUMNS {
get {
return ResourceManager.GetString("MANDATORY_COLUMNS", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Match Score.
/// </summary>
internal static string MATCH_SCORE {
get {
return ResourceManager.GetString("MATCH_SCORE", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please enter only positive values..
/// </summary>
internal static string MAX_COLUMN_ERROR {
get {
return ResourceManager.GetString("MAX_COLUMN_ERROR", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Merge Threshold.
/// </summary>
internal static string MERGE_THRESHOLD {
get {
return ResourceManager.GetString("MERGE_THRESHOLD", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid Minimum overlap value..
/// </summary>
internal static string MIN_OVERLAP_ERROR {
get {
return ResourceManager.GetString("MIN_OVERLAP_ERROR", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Select atleast {0} sheet(s) for alignment.
/// </summary>
internal static string MINIMUM_SELECT_HEADER {
get {
return ResourceManager.GetString("MINIMUM_SELECT_HEADER", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mismatch Score.
/// </summary>
internal static string MISMATCH_SCORE {
get {
return ResourceManager.GetString("MISMATCH_SCORE", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to nr.25.
/// </summary>
internal static string NR_25 {
get {
return ResourceManager.GetString("NR_25", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please choose one value per column.
/// </summary>
internal static string ONE_COLUMN {
get {
return ResourceManager.GetString("ONE_COLUMN", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overlapping Intervals.
/// </summary>
internal static string OVERLAPPING_INTERVALS {
get {
return ResourceManager.GetString("OVERLAPPING_INTERVALS", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Overlapping pieces of Intervals.
/// </summary>
internal static string OVERLAPPING_PIECES_OF_INTERVALS {
get {
return ResourceManager.GetString("OVERLAPPING_PIECES_OF_INTERVALS", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please select atleast {0} or more sheets..
/// </summary>
internal static string SELECT_SHEET_MESSAGE {
get {
return ResourceManager.GetString("SELECT_SHEET_MESSAGE", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Maximum number of sheets allowed to be selected: {0}.
/// </summary>
internal static string SHEET_SELECT_LIMIT {
get {
return ResourceManager.GetString("SHEET_SELECT_LIMIT", resourceCulture);
}
}
internal static System.Drawing.Bitmap Subtract_img1 {
get {
object obj = ResourceManager.GetObject("Subtract_img1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Subtract Inputs.
/// </summary>
internal static string SUBTRACT_INPUT {
get {
return ResourceManager.GetString("SUBTRACT_INPUT", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Returns intervals from the first query that have the intervals from the second
///query removed. Any overlapping base pairs are removed from the range of the interval.
///All fields besides start and end are guaranteed to remain unchanged..
/// </summary>
internal static string Subtract_WithNonOverlappingPiecesofInterval {
get {
return ResourceManager.GetString("Subtract_WithNonOverlappingPiecesofInterval", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Returns entire intervals from the first query that do not overlap the second query.
///The returned intervals are completely unchanged, and this option only filters out
///intervals that overlap with the second query..
/// </summary>
internal static string Subtract_WithNoOverlap {
get {
return ResourceManager.GetString("Subtract_WithNoOverlap", resourceCulture);
}
}
internal static System.Drawing.Bitmap Subtrtact_img2 {
get {
object obj = ResourceManager.GetObject("Subtrtact_img2", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to value.
/// </summary>
internal static string VALUE_TEXT {
get {
return ResourceManager.GetString("VALUE_TEXT", resourceCulture);
}
}
}
}
| 38.273418 | 206 | 0.564757 | [
"Apache-2.0"
] | jdm7dv/Microsoft-Biology-Foundation | archive/Changesets/beta/Source/BioExcel-48099/MBT_BioExcel/BioExcel.Visualizations.Common/Properties/Resources.Designer.cs | 15,120 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using WaveEngine.Common.Graphics;
using WaveEngine.Framework;
using WaveEngine.Framework.Graphics;
using WaveEngine.Framework.Services;
using WaveEngine.Web;
using WaveEngine.WebGL;
using WebAssembly;
namespace BetiJaiDemo.Web
{
public class Program
{
private static readonly Dictionary<string, WebSurface> AppCanvas = new Dictionary<string, WebSurface>();
private static MyApplication _application;
public static void DisplayZone(int id)
{
_application.DisplayZone(id);
}
public static void Main(string canvasId)
{
// Create app
_application = new MyApplication();
// Create Services
var windowsSystem = new WebWindowsSystem();
_application.Container.RegisterInstance(windowsSystem);
var document = (JSObject) Runtime.GetGlobalObject("document");
var canvas = (JSObject) document.Invoke("getElementById", canvasId);
var surface = (WebSurface) windowsSystem.CreateSurface(canvas);
AppCanvas[canvasId] = surface;
ConfigureGraphicsContext(_application, surface);
// Audio is currently unsupported
//var xaudio = new WaveEngine.XAudio2.XAudioDevice();
//application.Container.RegisterInstance(xaudio);
var notifier = new JavaScriptHotspotNotifier();
_application.Container.RegisterInstance<IHotspotNotifier>(notifier);
var clockTimer = Stopwatch.StartNew();
windowsSystem.Run(
() =>
{
Runtime.InvokeJS($"App.saveToLocalStorage('BetiJaiDemoStarting', '{DateTime.Now}');");
_application.Initialize();
Runtime.InvokeJS("WaveEngine.init();");
},
() =>
{
var gameTime = clockTimer.Elapsed;
clockTimer.Restart();
_application.UpdateFrame(gameTime);
_application.DrawFrame(gameTime);
});
}
public void UpdateCanvasSize(string canvasId)
{
if (AppCanvas.TryGetValue(canvasId, out var surface))
{
surface.RefreshSize();
}
}
private static void ConfigureGraphicsContext(Application application, Surface surface)
{
GraphicsContext graphicsContext = new WebGLGraphicsContext();
graphicsContext.CreateDevice();
var swapChainDescription = new SwapChainDescription
{
SurfaceInfo = surface.SurfaceInfo,
Width = surface.Width,
Height = surface.Height,
ColorTargetFormat = PixelFormat.R8G8B8A8_UNorm,
ColorTargetFlags = TextureFlags.RenderTarget | TextureFlags.ShaderResource,
DepthStencilTargetFormat = PixelFormat.D24_UNorm_S8_UInt,
DepthStencilTargetFlags = TextureFlags.DepthStencil,
SampleCount = TextureSampleCount.None,
IsWindowed = true,
RefreshRate = 60
};
var swapChain = graphicsContext.CreateSwapChain(swapChainDescription);
swapChain.VerticalSync = true;
var graphicsPresenter = application.Container.Resolve<GraphicsPresenter>();
var firstDisplay = new Display(surface, swapChain);
graphicsPresenter.AddDisplay("DefaultDisplay", firstDisplay);
application.Container.RegisterInstance(graphicsContext);
}
}
} | 37.06 | 112 | 0.608473 | [
"MIT"
] | gabrielgt/WaveEngine.Web.Learning | BetiJaiDemo.Web/Program.cs | 3,706 | C# |
//========= Copyright 2016-2021, HTC Corporation. All rights reserved. ===========
using UnityEngine;
using UnityEngine.EventSystems;
namespace HTC.UnityPlugin.Pointer3D
{
public interface ICanvasRaycastTarget
{
Canvas canvas { get; }
bool enabled { get; }
bool ignoreReversedGraphics { get; }
}
[AddComponentMenu("VIU/UI Pointer/Canvas Raycast Target", 6)]
[RequireComponent(typeof(Canvas))]
[DisallowMultipleComponent]
public class CanvasRaycastTarget : UIBehaviour, ICanvasRaycastTarget
{
private Canvas m_canvas;
[SerializeField]
private bool m_IgnoreReversedGraphics = true;
public virtual Canvas canvas { get { return m_canvas ?? (m_canvas = GetComponent<Canvas>()); } }
public bool ignoreReversedGraphics { get { return m_IgnoreReversedGraphics; } set { m_IgnoreReversedGraphics = value; } }
protected override void OnEnable()
{
base.OnEnable();
CanvasRaycastMethod.AddTarget(this);
}
protected override void OnDisable()
{
base.OnDisable();
CanvasRaycastMethod.RemoveTarget(this);
}
}
} | 29.925 | 129 | 0.642439 | [
"MIT"
] | CharlesCai123/Wearable-MultiCamera-System | Assets/HTC.UnityPlugin/Pointer3D/RaycastMethod/CanvasRaycastTarget.cs | 1,199 | C# |
using System.Linq.Expressions;
using Komair.Expressions.Abstract;
using Komair.Expressions.Mapping.Mapster.Configuration.Mappers.Expression.Abstract;
using Mapster;
namespace Komair.Expressions.Mapping.Mapster.Configuration.Mappers.Expression
{
internal class BinaryExpressionMapper : ExpressionMapperBase<BinaryExpression, BinaryExpressionNode>
{
public BinaryExpressionMapper(TypeAdapterConfig configuration) : base(configuration) { }
public override BinaryExpressionNode Map(BinaryExpression source)
{
var nodeType = source.NodeType;
var type = source.Type;
var left = source.Left.Adapt<ExpressionNodeBase>(Configuration);
var right = source.Right.Adapt<ExpressionNodeBase>(Configuration);
var result = new BinaryExpressionNode(nodeType, type)
{
Left = left,
Right = right
};
return result;
}
}
} | 37.074074 | 105 | 0.66034 | [
"MIT"
] | Yuck/Komair.Expressions.Serialization | src/Komair.Expressions.Mapping.Mapster/Configuration/Mappers/Expression/BinaryExpressionMapper.cs | 1,003 | C# |
/*$ preserve start $*/
/* ========================================================================================== */
/* FMOD Ex - DSP header file. Copyright (c), Firelight Technologies Pty, Ltd. 2004-2008. */
/* */
/* Use this header if you are interested in delving deeper into the FMOD software mixing / */
/* DSP engine. In this header you can find parameter structures for FMOD system reigstered */
/* DSP effects and generators. */
/* */
/* ========================================================================================== */
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace FMOD
{
/*$ preserve end $*/
/*
DSP callbacks
*/
public delegate RESULT DSP_CREATECALLBACK (ref DSP_STATE dsp_state);
public delegate RESULT DSP_RELEASECALLBACK (ref DSP_STATE dsp_state);
public delegate RESULT DSP_RESETCALLBACK (ref DSP_STATE dsp_state);
public delegate RESULT DSP_READCALLBACK (ref DSP_STATE dsp_state, IntPtr inbuffer, IntPtr outbuffer, uint length, int inchannels, int outchannels);
public delegate RESULT DSP_SETPOSITIONCALLBACK (ref DSP_STATE dsp_state, uint seeklen);
public delegate RESULT DSP_SETPARAMCALLBACK (ref DSP_STATE dsp_state, int index, float val);
public delegate RESULT DSP_GETPARAMCALLBACK (ref DSP_STATE dsp_state, int index, ref float val, StringBuilder valuestr);
public delegate RESULT DSP_DIALOGCALLBACK (ref DSP_STATE dsp_state, IntPtr hwnd, bool show);
/*
[ENUM]
[
[DESCRIPTION]
These definitions can be used for creating FMOD defined special effects or DSP units.
[REMARKS]
To get them to be active, first create the unit, then add it somewhere into the DSP network, either at the front of the network near the soundcard unit to affect the global output (by using System::getDSPHead), or on a single channel (using Channel::getDSPHead).
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
System::createDSPByType
]
*/
public enum DSP_TYPE :int
{
UNKNOWN, /* This unit was created via a non FMOD plugin so has an unknown purpose */
MIXER, /* This unit does nothing but take inputs and mix them together then feed the result to the soundcard unit. */
OSCILLATOR, /* This unit generates sine/square/saw/triangle or noise tones. */
LOWPASS, /* This unit filters _sound using a high quality, resonant lowpass filter algorithm but consumes more CPU Time. */
ITLOWPASS, /* This unit filters _sound using a resonant lowpass filter algorithm that is used in Impulse Tracker, but with limited cutoff range (0 to 8060hz). */
HIGHPASS, /* This unit filters _sound using a resonant highpass filter algorithm. */
ECHO, /* This unit produces an echo on the _sound and fades out at the desired rate. */
FLANGE, /* This unit produces a flange effect on the _sound. */
DISTORTION, /* This unit distorts the _sound. */
NORMALIZE, /* This unit normalizes or amplifies the _sound to a certain level. */
PARAMEQ, /* This unit attenuates or amplifies a selected frequency range. */
PITCHSHIFT, /* This unit bends the pitch of a _sound without changing the speed of playback. */
CHORUS, /* This unit produces a chorus effect on the _sound. */
REVERB, /* This unit produces a reverb effect on the _sound. */
VSTPLUGIN, /* This unit allows the use of Steinberg VST plugins */
WINAMPPLUGIN, /* This unit allows the use of Nullsoft Winamp plugins */
ITECHO, /* This unit produces an echo on the _sound and fades out at the desired rate as is used in Impulse Tracker. */
COMPRESSOR, /* This unit implements dynamic compression (linked multichannel, wideband) */
SFXREVERB, /* This unit implements SFX reverb */
LOWPASS_SIMPLE, /* This unit filters _sound using a simple lowpass with no resonance, but has flexible cutoff and is fast. */
DELAY, /* This unit produces different delays on individual channels of the _sound. */
TREMOLO, /* This unit produces a tremolo / chopper effect on the _sound. */
}
/*
[STRUCTURE]
[
[DESCRIPTION]
[REMARKS]
Members marked with [in] mean the user sets the value before passing it to the function.<br>
Members marked with [out] mean FMOD sets the value to be used after the function exits.<br>
<br>
The step parameter tells the gui or application that the parameter has a certain granularity.<br>
For example in the example of cutoff frequency with a range from 100.0 to 22050.0 you might only want the selection to be in 10hz increments. For this you would simply use 10.0 as the step value.<br>
For a boolean, you can use min = 0.0, max = 1.0, step = 1.0. This way the only possible values are 0.0 and 1.0.<br>
Some applications may detect min = 0.0, max = 1.0, step = 1.0 and replace a graphical slider bar with a checkbox instead.<br>
A step value of 1.0 would simulate integer values only.<br>
A step value of 0.0 would mean the full floating point range is accessable.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
System::createDSP
System::getDSP
]
*/
public struct DSP_PARAMETERDESC
{
public float min; /* [in] Minimum value of the parameter (ie 100.0). */
public float max; /* [in] Maximum value of the parameter (ie 22050.0). */
public float defaultval; /* [in] Default value of parameter. */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public char[] name; /* [in] Name of the parameter to be displayed (ie "Cutoff frequency"). */
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public char[] label; /* [in] Short string to be put next to value to denote the unit type (ie "hz"). */
public string description; /* [in] Description of the parameter to be displayed as a help item / tooltip for this parameter. */
}
/*
[STRUCTURE]
[
[DESCRIPTION]
Strcture to define the parameters for a DSP unit.
[REMARKS]
Members marked with [in] mean the user sets the value before passing it to the function.<br>
Members marked with [out] mean FMOD sets the value to be used after the function exits.<br>
<br>
There are 2 different ways to change a parameter in this architecture.<br>
One is to use DSP::setParameter / DSP::getParameter. This is platform independant and is dynamic, so new unknown plugins can have their parameters enumerated and used.<br>
The other is to use DSP::showConfigDialog. This is platform specific and requires a GUI, and will display a dialog box to configure the plugin.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
System::createDSP
System::getDSP
]
*/
public struct DSP_DESCRIPTION
{
[MarshalAs(UnmanagedType.ByValArray,SizeConst=32)]
public char[] name; /* [in] Name of the unit to be displayed in the network. */
public uint version; /* [in] Plugin writer's version number. */
public int channels; /* [in] Number of channels. Use 0 to process whatever number of channels is currently in the network. >0 would be mostly used if the unit is a unit that only generates _sound. */
public DSP_CREATECALLBACK create; /* [in] Create callback. This is called when DSP unit is created. Can be null. */
public DSP_RELEASECALLBACK release; /* [in] Release callback. This is called just before the unit is freed so the user can do any cleanup needed for the unit. Can be null. */
public DSP_RESETCALLBACK reset; /* [in] Reset callback. This is called by the user to reset any history buffers that may need resetting for a filter, when it is to be used or re-used for the first Time to its initial clean state. Use to avoid clicks or artifacts. */
public DSP_READCALLBACK read; /* [in] Read callback. Processing is done here. Can be null. */
public DSP_SETPOSITIONCALLBACK setposition; /* [in] Setposition callback. This is called if the unit wants to update its position info but not process data. Can be null. */
public int numparameters; /* [in] Number of parameters used in this filter. The user finds this with DSP::getNumParameters */
public DSP_PARAMETERDESC[] paramdesc; /* [in] Variable number of parameter structures. */
public DSP_SETPARAMCALLBACK setparameter; /* [in] This is called when the user calls DSP::setParameter. Can be null. */
public DSP_GETPARAMCALLBACK getparameter; /* [in] This is called when the user calls DSP::getParameter. Can be null. */
public DSP_DIALOGCALLBACK config; /* [in] This is called when the user calls DSP::showConfigDialog. Can be used to display a dialog to configure the filter. Can be null. */
public int configwidth; /* [in] Width of config dialog graphic if there is one. 0 otherwise.*/
public int configheight; /* [in] Height of config dialog graphic if there is one. 0 otherwise.*/
public IntPtr userdata; /* [in] Optional. Specify 0 to ignore. This is user data to be attached to the DSP unit during creation. Access via DSP::getUserData. */
}
/*
[STRUCTURE]
[
[DESCRIPTION]
DSP plugin structure that is passed into each callback.
[REMARKS]
Members marked with [in] mean the variable can be written to. The user can set the value.<br>
Members marked with [out] mean the variable is modified by FMOD and is for reading purposes only. Do not change this value.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3
[SEE_ALSO]
FMOD_DSP_DESCRIPTION
]
*/
public struct DSP_STATE
{
public IntPtr instance; /* [out] Handle to the DSP hand the user created. Not to be modified. C++ users cast to FMOD::DSP to use. */
public IntPtr plugindata; /* [in] Plugin writer created data the output author wants to attach to this object. */
public ushort speakermask; /* Specifies which speakers the DSP effect is active on */
};
/*
==============================================================================================================
FMOD built in effect parameters.
Use DSP::setParameter with these enums for the 'index' parameter.
==============================================================================================================
*/
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_OSCILLATOR filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_OSCILLATOR
{
TYPE, /* Waveform type. 0 = sine. 1 = square. 2 = sawup. 3 = sawdown. 4 = triangle. 5 = noise. */
RATE /* Frequency of the sinewave in hz. 1.0 to 22000.0. Default = 220.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_LOWPASS filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_LOWPASS
{
CUTOFF, /* Lowpass cutoff frequency in hz. 1.0 to 22000.0. Default = 5000.0. */
RESONANCE /* Lowpass resonance Q value. 1.0 to 10.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_ITLOWPASS filter.
This is different to the default FMOD_DSP_TYPE_ITLOWPASS filter in that it uses a different quality algorithm and is
the filter used to produce the correct sounding playback in .IT files.<br>
FMOD Ex's .IT playback uses this filter.<br>
[REMARKS]
Note! This filter actually has a limited cutoff frequency below the specified maximum, due to its limited design,
so for a more open range filter use FMOD_DSP_LOWPASS or if you don't mind not having resonance,
FMOD_DSP_LOWPASS_SIMPLE.<br>
The effective maximum cutoff is about 8060hz.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_ITLOWPASS
{
CUTOFF, /* Lowpass cutoff frequency in hz. 1.0 to 22000.0. Default = 5000.0/ */
RESONANCE /* Lowpass resonance Q value. 0.0 to 127.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_HIGHPASS filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_HIGHPASS
{
CUTOFF, /* Highpass cutoff frequency in hz. 10.0 to output 22000.0. Default = 5000.0. */
RESONANCE /* Highpass resonance Q value. 1.0 to 10.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_ECHO filter.
[REMARKS]
Note. Every Time the delay is changed, the plugin re-allocates the echo buffer. This means the echo will dissapear at that Time while it refills its new buffer.<br>
Larger echo delays result in larger amounts of memory allocated.<br>
<br>
'<i>maxchannels</i>' also dictates the amount of memory allocated. By default, the maxchannels value is 0. If FMOD is set to stereo, the echo unit will allocate enough memory for 2 channels. If it is 5.1, it will allocate enough memory for a 6 channel echo, etc.<br>
If the echo effect is only ever applied to the global mix (ie it was added with System::addDSP), then 0 is the value to set as it will be enough to handle all speaker modes.<br>
When the echo is added to a channel (ie Channel::addDSP) then the channel count that comes in could be anything from 1 to 8 possibly. It is only in this case where you might want to increase the channel count above the output's channel count.<br>
If a channel echo is set to a lower number than the _sound's channel count that is coming in, it will not echo the _sound.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_ECHO
{
DELAY, /* Echo delay in ms. 10 to 5000. Default = 500. */
DECAYRATIO, /* Echo decay per delay. 0 to 1. 1.0 = No decay, 0.0 = total decay. Default = 0.5. */
MAXCHANNELS, /* Maximum channels supported. 0 to 16. 0 = same as fmod's default output polyphony, 1 = mono, 2 = stereo etc. See remarks for more. Default = 0. It is suggested to leave at 0! */
DRYMIX, /* Volume of original signal to pass to output. 0.0 to 1.0. Default = 1.0. */
WETMIX /* Volume of echo signal to pass to output. 0.0 to 1.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_DELAY filter.
[REMARKS]
Note. Every Time MaxDelay is changed, the plugin re-allocates the delay buffer. This means the delay will dissapear at that Time while it refills its new buffer.<br>
A larger MaxDelay results in larger amounts of memory allocated.<br>
Channel delays above MaxDelay will be clipped to MaxDelay and the delay buffer will not be resized.<br>
<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_DELAY
{
CH0, /* Channel #0 Delay in ms. 0 to 10000. Default = 0. */
CH1, /* Channel #1 Delay in ms. 0 to 10000. Default = 0. */
CH2, /* Channel #2 Delay in ms. 0 to 10000. Default = 0. */
CH3, /* Channel #3 Delay in ms. 0 to 10000. Default = 0. */
CH4, /* Channel #4 Delay in ms. 0 to 10000. Default = 0. */
CH5, /* Channel #5 Delay in ms. 0 to 10000. Default = 0. */
CH6, /* Channel #6 Delay in ms. 0 to 10000. Default = 0. */
CH7, /* Channel #7 Delay in ms. 0 to 10000. Default = 0. */
CH8, /* Channel #8 Delay in ms. 0 to 10000. Default = 0. */
CH9, /* Channel #9 Delay in ms. 0 to 10000. Default = 0. */
CH10, /* Channel #10 Delay in ms. 0 to 10000. Default = 0. */
CH11, /* Channel #11 Delay in ms. 0 to 10000. Default = 0. */
CH12, /* Channel #12 Delay in ms. 0 to 10000. Default = 0. */
CH13, /* Channel #13 Delay in ms. 0 to 10000. Default = 0. */
CH14, /* Channel #14 Delay in ms. 0 to 10000. Default = 0. */
CH15, /* Channel #15 Delay in ms. 0 to 10000. Default = 0. */
MAXDELAY, /* Maximum delay in ms. 0 to 1000. Default = 10. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_FLANGE filter.
[REMARKS]
Flange is an effect where the signal is played twice at the same Time, and one copy slides back and forth creating a whooshing or flanging effect.<br>
As there are 2 copies of the same signal, by default each signal is given 50% mix, so that the total is not louder than the original unaffected signal.<br>
<br>
Flange depth is a percentage of a 10ms shift from the original signal. Anything above 10ms is not considered flange because to the ear it begins to 'echo' so 10ms is the highest value possible.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_FLANGE
{
DRYMIX, /* Volume of original signal to pass to output. 0.0 to 1.0. Default = 0.45. */
WETMIX, /* Volume of flange signal to pass to output. 0.0 to 1.0. Default = 0.55. */
DEPTH, /* Flange depth. 0.01 to 1.0. Default = 1.0. */
RATE /* Flange speed in hz. 0.0 to 20.0. Default = 0.1. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_TREMOLO filter.
[REMARKS]
The tremolo effect varies the amplitude of a _sound. Depending on the settings, this unit can produce a tremolo, chopper or auto-pan effect.<br>
<br>
The shape of the LFO (low freq. oscillator) can morphed between sine, triangle and sawtooth waves using the FMOD_DSP_TREMOLO_SHAPE and FMOD_DSP_TREMOLO_SKEW parameters.<br>
FMOD_DSP_TREMOLO_DUTY and FMOD_DSP_TREMOLO_SQUARE are useful for a chopper-type effect where the first controls the on-Time duration and second controls the flatness of the envelope.<br>
FMOD_DSP_TREMOLO_SPREAD varies the LFO phase between channels to get an auto-pan effect. This works best with a sine shape LFO.<br>
The LFO can be synchronized using the FMOD_DSP_TREMOLO_PHASE parameter which sets its instantaneous phase.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_TREMOLO
{
FREQUENCY, /* LFO frequency in Hz. 0.1 to 20. Default = 4. */
DEPTH, /* Tremolo depth. 0 to 1. Default = 0. */
SHAPE, /* LFO shape morph between triangle and sine. 0 to 1. Default = 0. */
SKEW, /* Time-skewing of LFO cycle. -1 to 1. Default = 0. */
DUTY, /* LFO on-Time. 0 to 1. Default = 0.5. */
SQUARE, /* Flatness of the LFO shape. 0 to 1. Default = 0. */
PHASE, /* Instantaneous LFO phase. 0 to 1. Default = 0. */
SPREAD /* Rotation / auto-pan effect. -1 to 1. Default = 0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_DISTORTION filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_DISTORTION
{
LEVEL /* Distortion value. 0.0 to 1.0. Default = 0.5. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_NORMALIZE filter.
[REMARKS]
Normalize amplifies the _sound based on the maximum peaks within the signal.<br>
For example if the maximum peaks in the signal were 50% of the bandwidth, it would scale the whole _sound by 2.<br>
The lower threshold value makes the normalizer ignores peaks below a certain point, to avoid over-amplification if a loud signal suddenly came in, and also to avoid amplifying to maximum things like background hiss.<br>
<br>
Because FMOD is a realtime audio processor, it doesn't have the luxury of knowing the peak for the whole _sound (ie it can't see into the future), so it has to process data as it comes in.<br>
To avoid very sudden changes in volume level based on small samples of new data, fmod fades towards the desired amplification which makes for smooth gain control. The fadetime parameter can control this.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_NORMALIZE
{
FADETIME, /* Time to ramp the silence to full in ms. 0.0 to 20000.0. Default = 5000.0. */
THRESHHOLD, /* Lower volume range threshold to ignore. 0.0 to 1.0. Default = 0.1. Raise higher to stop amplification of very quiet signals. */
MAXAMP /* Maximum amplification allowed. 1.0 to 100000.0. Default = 20.0. 1.0 = no amplifaction, higher values allow more boost. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_PARAMEQ filter.
[REMARKS]
Parametric EQ is a bandpass filter that attenuates or amplifies a selected frequency and its neighbouring frequencies.<br>
<br>
To create a multi-band EQ create multiple FMOD_DSP_TYPE_PARAMEQ units and set each unit to different frequencies, for example 1000hz, 2000hz, 4000hz, 8000hz, 16000hz with a range of 1 octave each.<br>
<br>
When a frequency has its gain set to 1.0, the _sound will be unaffected and represents the original signal exactly.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_PARAMEQ
{
CENTER, /* Frequency center. 20.0 to 22000.0. Default = 8000.0. */
BANDWIDTH, /* Octave range around the center frequency to filter. 0.2 to 5.0. Default = 1.0. */
GAIN /* Frequency Gain. 0.05 to 3.0. Default = 1.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_PITCHSHIFT filter.
[REMARKS]
This pitch shifting unit can be used to change the pitch of a _sound without speeding it up or slowing it down.<br>
It can also be used for Time stretching or scaling, for example if the pitch was doubled, and the frequency of the _sound was halved, the pitch of the _sound would _sound correct but it would be twice as slow.<br>
<br>
<b>Warning!</b> This filter is very computationally expensive! Similar to a vocoder, it requires several overlapping FFT and IFFT's to produce smooth output, and can require around 440mhz for 1 stereo 48khz signal using the default settings.<br>
Reducing the signal to mono will half the cpu usage, as will the overlap count.<br>
Reducing this will lower audio quality, but what settings to use are largely dependant on the _sound being played. A noisy polyphonic signal will need higher overlap and fft size compared to a speaking voice for example.<br>
<br>
This pitch shifter is based on the pitch shifter code at http://www.dspdimension.com, written by Stephan M. Bernsee.<br>
The original code is COPYRIGHT 1999-2003 Stephan M. Bernsee <smb@dspdimension.com>.<br>
<br>
'<i>maxchannels</i>' dictates the amount of memory allocated. By default, the maxchannels value is 0. If FMOD is set to stereo, the pitch shift unit will allocate enough memory for 2 channels. If it is 5.1, it will allocate enough memory for a 6 channel pitch shift, etc.<br>
If the pitch shift effect is only ever applied to the global mix (ie it was added with System::addDSP), then 0 is the value to set as it will be enough to handle all speaker modes.<br>
When the pitch shift is added to a channel (ie Channel::addDSP) then the channel count that comes in could be anything from 1 to 8 possibly. It is only in this case where you might want to increase the channel count above the output's channel count.<br>
If a channel pitch shift is set to a lower number than the _sound's channel count that is coming in, it will not pitch shift the _sound.<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_PITCHSHIFT
{
PITCH, /* Pitch value. 0.5 to 2.0. Default = 1.0. 0.5 = one octave down, 2.0 = one octave up. 1.0 does not change the pitch. */
FFTSIZE, /* FFT window size. 256, 512, 1024, 2048, 4096. Default = 1024. Increase this to reduce 'smearing'. This effect is a warbling _sound similar to when an mp3 is encoded at very low bitrates. */
OVERLAP, /* Window overlap. 1 to 32. Default = 4. Increase this to reduce 'tremolo' effect. Increasing it by a factor of 2 doubles the CPU usage. */
MAXCHANNELS /* Maximum channels supported. 0 to 16. 0 = same as fmod's default output polyphony, 1 = mono, 2 = stereo etc. See remarks for more. Default = 0. It is suggested to leave at 0! */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_CHORUS filter.
[REMARKS]
Chrous is an effect where the _sound is more 'spacious' due to 1 to 3 versions of the _sound being played along side the original signal but with the pitch of each copy modulating on a sine wave.<br>
This is a highly configurable chorus unit. It supports 3 taps, small and large delay times and also feedback.<br>
This unit also could be used to do a simple echo, or a flange effect.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_CHORUS
{
DRYMIX, /* Volume of original signal to pass to output. 0.0 to 1.0. Default = 0.5. */
WETMIX1, /* Volume of 1st chorus tap. 0.0 to 1.0. Default = 0.5. */
WETMIX2, /* Volume of 2nd chorus tap. This tap is 90 degrees out of phase of the first tap. 0.0 to 1.0. Default = 0.5. */
WETMIX3, /* Volume of 3rd chorus tap. This tap is 90 degrees out of phase of the second tap. 0.0 to 1.0. Default = 0.5. */
DELAY, /* Chorus delay in ms. 0.1 to 100.0. Default = 40.0 ms. */
RATE, /* Chorus modulation rate in hz. 0.0 to 20.0. Default = 0.8 hz. */
DEPTH, /* Chorus modulation depth. 0.0 to 1.0. Default = 0.03. */
FEEDBACK /* Chorus feedback. Controls how much of the wet signal gets fed back into the chorus buffer. 0.0 to 1.0. Default = 0.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_REVERB filter.
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_REVERB
{
ROOMSIZE, /* Roomsize. 0.0 to 1.0. Default = 0.5 */
DAMP, /* Damp. 0.0 to 1.0. Default = 0.5 */
WETMIX, /* Wet mix. 0.0 to 1.0. Default = 0.33 */
DRYMIX, /* Dry mix. 0.0 to 1.0. Default = 0.0 */
WIDTH, /* Width. 0.0 to 1.0. Default = 1.0 */
MODE /* Mode. 0 (normal), 1 (freeze). Default = 0 */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_ITECHO filter.<br>
This is effectively a software based echo filter that emulates the DirectX DMO echo effect. Impulse tracker files can support this, and FMOD will produce the effect on ANY platform, not just those that support DirectX effects!<br>
[REMARKS]
Note. Every Time the delay is changed, the plugin re-allocates the echo buffer. This means the echo will dissapear at that Time while it refills its new buffer.<br>
Larger echo delays result in larger amounts of memory allocated.<br>
<br>
For stereo signals only! This will not work on mono or multichannel signals. This is fine for .IT format purposes, and also if you use System::addDSP with a standard stereo output.<br>
[PLATFORMS]
Win32, Win64, Linux, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
System::addDSP
]
*/
public enum DSP_ITECHO
{
WETDRYMIX, /* Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from 0.0 through 100.0 (all wet). The default value is 50. */
FEEDBACK, /* Percentage of output fed back into input, in the range from 0.0 through 100.0. The default value is 50. */
LEFTDELAY, /* Delay for left channel, in milliseconds, in the range from 1.0 through 2000.0. The default value is 500 ms. */
RIGHTDELAY, /* Delay for right channel, in milliseconds, in the range from 1.0 through 2000.0. The default value is 500 ms. */
PANDELAY /* Value that specifies whether to swap left and right delays with each successive echo. The default value is zero, meaning no swap. Possible values are defined as 0.0 (equivalent to FALSE) and 1.0 (equivalent to TRUE). */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_COMPRESSOR unit.<br>
This is a simple linked multichannel software limiter that is uniform across the whole spectrum.<br>
[REMARKS]
The parameters are as follows:
Threshold: [-60dB to 0dB, default 0dB]
Attack Time: [10ms to 200ms, default 50ms]
Release Time: [20ms to 1000ms, default 50ms]
Gain Make Up: [0dB to +30dB, default 0dB]
<br>
The limiter is not guaranteed to catch every peak above the threshold level,
because it cannot apply gain reduction instantaneously - the Time delay is
determined by the attack Time. However setting the attack Time too short will
distort the _sound, so it is a compromise. High level peaks can be avoided by
using a short attack Time - but not too short, and setting the threshold a few
decibels below the critical level.
<br>
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3
[SEE_ALSO]
DSP::SetParameter
DSP::GetParameter
FMOD_DSP_TYPE
System::addDSP
]
*/
public enum DSP_COMPRESSOR
{
THRESHOLD, /* Threshold level (dB)in the range from -60 through 0. The default value is 50. */
ATTACK, /* Gain reduction attack Time (milliseconds), in the range from 10 through 200. The default value is 50. */
RELEASE, /* Gain reduction release Time (milliseconds), in the range from 20 through 1000. The default value is 50. */
GAINMAKEUP /* Make-up gain applied after limiting, in the range from 0.0 through 100.0. The default value is 50. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_SFXREVERB unit.<br>
[REMARKS]
This is a high quality I3DL2 based reverb which improves greatly on FMOD_DSP_REVERB.<br>
On top of the I3DL2 property set, "Dry Level" is also included to allow the dry mix to be changed.<br>
<br>
Currently FMOD_DSP_SFXREVERB_REFLECTIONSLEVEL, FMOD_DSP_SFXREVERB_REFLECTIONSDELAY and FMOD_DSP_SFXREVERB_REVERBDELAY are not enabled but will come in future versions.<br>
<br>
These properties can be set with presets in FMOD_REVERB_PRESETS.
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3
[SEE_ALSO]
DSP::SetParameter
DSP::GetParameter
FMOD_DSP_TYPE
System::addDSP
FMOD_REVERB_PRESETS
]
*/
public enum DSP_SFXREVERB
{
DRYLEVEL, /* Dry Level : Mix level of dry signal in output in mB. Ranges from -10000.0 to 0.0. Default is 0.0. */
ROOM, /* Room : Room effect level at low frequencies in mB. Ranges from -10000.0 to 0.0. Default is 0.0. */
ROOMHF, /* Room HF : Room effect high-frequency level re. low frequency level in mB. Ranges from -10000.0 to 0.0. Default is 0.0. */
ROOMROLLOFFFACTOR, /* Room Rolloff : Like DS3D flRolloffFactor but for room effect. Ranges from 0.0 to 10.0. Default is 10.0 */
DECAYTIME, /* Decay Time : Reverberation decay Time at low-frequencies in seconds. Ranges from 0.1 to 20.0. Default is 1.0. */
DECAYHFRATIO, /* Decay HF Ratio : High-frequency to low-frequency decay Time ratio. Ranges from 0.1 to 2.0. Default is 0.5. */
REFLECTIONSLEVEL, /* Reflections : Early reflections level relative to room effect in mB. Ranges from -10000.0 to 1000.0. Default is -10000.0. */
REFLECTIONSDELAY, /* Reflect Delay : Delay Time of first reflection in seconds. Ranges from 0.0 to 0.3. Default is 0.02. */
REVERBLEVEL, /* Reverb : Late reverberation level relative to room effect in mB. Ranges from -10000.0 to 2000.0. Default is 0.0. */
REVERBDELAY, /* Reverb Delay : Late reverberation delay Time relative to first reflection in seconds. Ranges from 0.0 to 0.1. Default is 0.04. */
DIFFUSION, /* Diffusion : Reverberation diffusion (echo density) in percent. Ranges from 0.0 to 100.0. Default is 100.0. */
DENSITY, /* Density : Reverberation density (modal density) in percent. Ranges from 0.0 to 100.0. Default is 100.0. */
HFREFERENCE, /* HF Reference : Reference high frequency in Hz. Ranges from 20.0 to 20000.0. Default is 5000.0. */
ROOMLF, /* Room LF : Room effect low-frequency level in mB. Ranges from -10000.0 to 0.0. Default is 0.0. */
LFREFERENCE /* LF Reference : Reference low-frequency in Hz. Ranges from 20.0 to 1000.0. Default is 250.0. */
}
/*
[ENUM]
[
[DESCRIPTION]
Parameter types for the FMOD_DSP_TYPE_LOWPASS_SIMPLE filter.<br>
This is a very simple low pass filter, based on two single-pole RC Time-constant modules.
The emphasis is on speed rather than accuracy, so this should not be used for task requiring critical filtering.<br>
[REMARKS]
[PLATFORMS]
Win32, Win64, Linux, Linux64, Macintosh, Xbox, Xbox360, PlayStation 2, GameCube, PlayStation Portable, PlayStation 3, Wii
[SEE_ALSO]
DSP::setParameter
DSP::getParameter
FMOD_DSP_TYPE
]
*/
public enum DSP_LOWPASS_SIMPLE
{
CUTOFF /* Lowpass cutoff frequency in hz. 10.0 to 22000.0. Default = 5000.0 */
}
/*$ preserve start $*/
}
/*$ preserve end $*/
| 51.455137 | 299 | 0.619803 | [
"BSD-2-Clause"
] | IndiegameGarden/Goatic | TTengine/MusicEngine/FMOD/fmod_dsp.cs | 39,569 | C# |
// MIT License - Copyright (c) Callum McGing
// This file is subject to the terms and conditions defined in
// LICENSE, which is part of this source code package
using System;
using LibreLancer;
using System.Runtime.InteropServices;
using ImGuiNET;
namespace LibreLancer.ImUI
{
public class ImGuiExt
{
[DllImport("cimgui", EntryPoint = "igBuildFontAtlas", CallingConvention = CallingConvention.Cdecl)]
public static extern void BuildFontAtlas(IntPtr atlas);
[DllImport("cimgui", EntryPoint = "igExtSplitterV", CallingConvention = CallingConvention.Cdecl)]
public static extern bool SplitterV(float thickness, ref float size1, ref float size2, float min_size1, float min_size2, float splitter_long_axis_size);
const string PADDING = " ";
public static string Pad(string s)
{
return PADDING + s;
}
public static bool ToggleButton(string text, bool v)
{
if (v) {
var style = ImGui.GetStyle();
ImGui.PushStyleColor(ImGuiCol.Button, style.Colors[(int)ImGuiCol.ButtonActive]);
}
var retval = ImGui.Button(text);
if(v) ImGui.PopStyleColor();
return retval;
}
const int ImDrawCornerFlags_All = 0xF;
public static unsafe void ToastText(string text, Color4 background, Color4 foreground)
{
var displaySize = (Vector2)(ImGui.GetIO().DisplaySize);
var textSize = (Vector2)ImGui.CalcTextSize(text);
var drawlist = ImGuiNative.igGetOverlayDrawList();
var textbytes = System.Text.Encoding.UTF8.GetBytes(text);
ImGuiNative.ImDrawList_AddRectFilled(
drawlist,
new Vector2(displaySize.X - textSize.X - 9, 2),
new Vector2(displaySize.X, textSize.Y + 9),
GetUint(background), 2, ImDrawCornerFlags_All
);
fixed (byte* ptr = textbytes)
{
ImGuiNative.ImDrawList_AddText(
drawlist,
new Vector2(displaySize.X - textSize.X - 3,2),
GetUint(foreground), ptr,
(byte*)0
);
}
}
public static unsafe uint GetUint(Color4 color)
{
uint a = 0;
var ptr = (byte*)&a;
ptr[0] = (byte)(color.R * 255);
ptr[1] = (byte)(color.G * 255);
ptr[2] = (byte)(color.B * 255);
ptr[3] = (byte)(color.A * 255);
return a;
}
[DllImport("cimgui", EntryPoint = "igExtSpinner", CallingConvention = CallingConvention.Cdecl)]
public static extern bool Spinner(string label, float radius, int thickness, uint color);
}
}
| 38.547945 | 160 | 0.58209 | [
"MIT"
] | lyzardiar/Librelancer | src/Editor/LibreLancer.ImUI/ImGuiExt.cs | 2,816 | C# |
using System;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Media;
using Windows.Graphics.Imaging;
using Windows.Storage.Streams;
namespace VGG19_Console_Demo_CS
{
class ImageNetClassList
{
public string[] classList { get; set; }
public ImageNetClassList()
{
classList = new string[] { "tench, Tinca tinca", "goldfish, Carassius auratus", "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias", "tiger shark, Galeocerdo cuvieri", "hammerhead, hammerhead shark", "electric ray, crampfish, numbfish, torpedo", "stingray", "cock", "hen", "ostrich, Struthio camelus", "brambling, Fringilla montifringilla", "goldfinch, Carduelis carduelis", "house finch, linnet, Carpodacus mexicanus", "junco, snowbird", "indigo bunting, indigo finch, indigo bird, Passerina cyanea", "robin, American robin, Turdus migratorius", "bulbul", "jay", "magpie", "chickadee", "water ouzel, dipper", "kite", "bald eagle, American eagle, Haliaeetus leucocephalus", "vulture", "great grey owl, great gray owl, Strix nebulosa", "European fire salamander, Salamandra salamandra", "common newt, Triturus vulgaris", "eft", "spotted salamander, Ambystoma maculatum", "axolotl, mud puppy, Ambystoma mexicanum", "bullfrog, Rana catesbeiana", "tree frog, tree-frog", "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui", "loggerhead, loggerhead turtle, Caretta caretta", "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea", "mud turtle", "terrapin", "box turtle, box tortoise", "banded gecko", "common iguana, iguana, Iguana iguana", "American chameleon, anole, Anolis carolinensis", "whiptail, whiptail lizard", "agama", "frilled lizard, Chlamydosaurus kingi", "alligator lizard", "Gila monster, Heloderma suspectum", "green lizard, Lacerta viridis", "African chameleon, Chamaeleo chamaeleon", "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis", "African crocodile, Nile crocodile, Crocodylus niloticus", "American alligator, Alligator mississipiensis", "triceratops", "thunder snake, worm snake, Carphophis amoenus", "ringneck snake, ring-necked snake, ring snake", "hognose snake, puff adder, sand viper", "green snake, grass snake", "king snake, kingsnake", "garter snake, grass snake", "water snake", "vine snake", "night snake, Hypsiglena torquata", "boa constrictor, Constrictor constrictor", "rock python, rock snake, Python sebae", "Indian cobra, Naja naja", "green mamba", "sea snake", "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus", "diamondback, diamondback rattlesnake, Crotalus adamanteus", "sidewinder, horned rattlesnake, Crotalus cerastes", "trilobite", "harvestman, daddy longlegs, Phalangium opilio", "scorpion", "black and gold garden spider, Argiope aurantia", "barn spider, Araneus cavaticus", "garden spider, Aranea diademata", "black widow, Latrodectus mactans", "tarantula", "wolf spider, hunting spider", "tick", "centipede", "black grouse", "ptarmigan", "ruffed grouse, partridge, Bonasa umbellus", "prairie chicken, prairie grouse, prairie fowl", "peacock", "quail", "partridge", "African grey, African gray, Psittacus erithacus", "macaw", "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita", "lorikeet", "coucal", "bee eater", "hornbill", "hummingbird", "jacamar", "toucan", "drake", "red-breasted merganser, Mergus serrator", "goose", "black swan, Cygnus atratus", "tusker", "echidna, spiny anteater, anteater", "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus", "wallaby, brush kangaroo", "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus", "wombat", "jellyfish", "sea anemone, anemone", "brain coral", "flatworm, platyhelminth", "nematode, nematode worm, roundworm", "conch", "snail", "slug", "sea slug, nudibranch", "chiton, coat-of-mail shell, sea cradle, polyplacophore", "chambered nautilus, pearly nautilus, nautilus", "Dungeness crab, Cancer magister", "rock crab, Cancer irroratus", "fiddler crab", "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica", "American lobster, Northern lobster, Maine lobster, Homarus americanus", "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish", "crayfish, crawfish, crawdad, crawdaddy", "hermit crab", "isopod", "white stork, Ciconia ciconia", "black stork, Ciconia nigra", "spoonbill", "flamingo", "little blue heron, Egretta caerulea", "American egret, great white heron, Egretta albus", "bittern", "crane", "limpkin, Aramus pictus", "European gallinule, Porphyrio porphyrio", "American coot, marsh hen, mud hen, water hen, Fulica americana", "bustard", "ruddy turnstone, Arenaria interpres", "red-backed sandpiper, dunlin, Erolia alpina", "redshank, Tringa totanus", "dowitcher", "oystercatcher, oyster catcher", "pelican", "king penguin, Aptenodytes patagonica", "albatross, mollymawk", "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus", "killer whale, killer, orca, grampus, sea wolf, Orcinus orca", "dugong, Dugong dugon", "sea lion", "Chihuahua", "Japanese spaniel", "Maltese dog, Maltese terrier, Maltese", "Pekinese, Pekingese, Peke", "Shih-Tzu", "Blenheim spaniel", "papillon", "toy terrier", "Rhodesian ridgeback", "Afghan hound, Afghan", "basset, basset hound", "beagle", "bloodhound, sleuthhound", "bluetick", "black-and-tan coonhound", "Walker hound, Walker foxhound", "English foxhound", "redbone", "borzoi, Russian wolfhound", "Irish wolfhound", "Italian greyhound", "whippet", "Ibizan hound, Ibizan Podenco", "Norwegian elkhound, elkhound", "otterhound, otter hound", "Saluki, gazelle hound", "Scottish deerhound, deerhound", "Weimaraner", "Staffordshire bullterrier, Staffordshire bull terrier", "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier", "Bedlington terrier", "Border terrier", "Kerry blue terrier", "Irish terrier", "Norfolk terrier", "Norwich terrier", "Yorkshire terrier", "wire-haired fox terrier", "Lakeland terrier", "Sealyham terrier, Sealyham", "Airedale, Airedale terrier", "cairn, cairn terrier", "Australian terrier", "Dandie Dinmont, Dandie Dinmont terrier", "Boston bull, Boston terrier", "miniature schnauzer", "giant schnauzer", "standard schnauzer", "Scotch terrier, Scottish terrier, Scottie", "Tibetan terrier, chrysanthemum dog", "silky terrier, Sydney silky", "soft-coated wheaten terrier", "West Highland white terrier", "Lhasa, Lhasa apso", "flat-coated retriever", "curly-coated retriever", "golden retriever", "Labrador retriever", "Chesapeake Bay retriever", "German short-haired pointer", "vizsla, Hungarian pointer", "English setter", "Irish setter, red setter", "Gordon setter", "Brittany spaniel", "clumber, clumber spaniel", "English springer, English springer spaniel", "Welsh springer spaniel", "cocker spaniel, English cocker spaniel, cocker", "Sussex spaniel", "Irish water spaniel", "kuvasz", "schipperke", "groenendael", "malinois", "briard", "kelpie", "komondor", "Old English sheepdog, bobtail", "Shetland sheepdog, Shetland sheep dog, Shetland", "collie", "Border collie", "Bouvier des Flandres, Bouviers des Flandres", "Rottweiler", "German shepherd, German shepherd dog, German police dog, alsatian", "Doberman, Doberman pinscher", "miniature pinscher", "Greater Swiss Mountain dog", "Bernese mountain dog", "Appenzeller", "EntleBucher", "boxer", "bull mastiff", "Tibetan mastiff", "French bulldog", "Great Dane", "Saint Bernard, St Bernard", "Eskimo dog, husky", "malamute, malemute, Alaskan malamute", "Siberian husky", "dalmatian, coach dog, carriage dog", "affenpinscher, monkey pinscher, monkey dog", "basenji", "pug, pug-dog", "Leonberg", "Newfoundland, Newfoundland dog", "Great Pyrenees", "Samoyed, Samoyede", "Pomeranian", "chow, chow chow", "keeshond", "Brabancon griffon", "Pembroke, Pembroke Welsh corgi", "Cardigan, Cardigan Welsh corgi", "toy poodle", "miniature poodle", "standard poodle", "Mexican hairless", "timber wolf, grey wolf, gray wolf, Canis lupus", "white wolf, Arctic wolf, Canis lupus tundrarum", "red wolf, maned wolf, Canis rufus, Canis niger", "coyote, prairie wolf, brush wolf, Canis latrans", "dingo, warrigal, warragal, Canis dingo", "dhole, Cuon alpinus", "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus", "hyena, hyaena", "red fox, Vulpes vulpes", "kit fox, Vulpes macrotis", "Arctic fox, white fox, Alopex lagopus", "grey fox, gray fox, Urocyon cinereoargenteus", "tabby, tabby cat", "tiger cat", "Persian cat", "Siamese cat, Siamese", "Egyptian cat", "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor", "lynx, catamount", "leopard, Panthera pardus", "snow leopard, ounce, Panthera uncia", "jaguar, panther, Panthera onca, Felis onca", "lion, king of beasts, Panthera leo", "tiger, Panthera tigris", "cheetah, chetah, Acinonyx jubatus", "brown bear, bruin, Ursus arctos", "American black bear, black bear, Ursus americanus, Euarctos americanus", "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus", "sloth bear, Melursus ursinus, Ursus ursinus", "mongoose", "meerkat, mierkat", "tiger beetle", "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle", "ground beetle, carabid beetle", "long-horned beetle, longicorn, longicorn beetle", "leaf beetle, chrysomelid", "dung beetle", "rhinoceros beetle", "weevil", "fly", "bee", "ant, emmet, pismire", "grasshopper, hopper", "cricket", "walking stick, walkingstick, stick insect", "cockroach, roach", "mantis, mantid", "cicada, cicala", "leafhopper", "lacewing, lacewing fly", "dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk", "damselfly", "admiral", "ringlet, ringlet butterfly", "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus", "cabbage butterfly", "sulphur butterfly, sulfur butterfly", "lycaenid, lycaenid butterfly", "starfish, sea star", "sea urchin", "sea cucumber, holothurian", "wood rabbit, cottontail, cottontail rabbit", "hare", "Angora, Angora rabbit", "hamster", "porcupine, hedgehog", "fox squirrel, eastern fox squirrel, Sciurus niger", "marmot", "beaver", "guinea pig, Cavia cobaya", "sorrel", "zebra", "hog, pig, grunter, squealer, Sus scrofa", "wild boar, boar, Sus scrofa", "warthog", "hippopotamus, hippo, river horse, Hippopotamus amphibius", "ox", "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis", "bison", "ram, tup", "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis", "ibex, Capra ibex", "hartebeest", "impala, Aepyceros melampus", "gazelle", "Arabian camel, dromedary, Camelus dromedarius", "llama", "weasel", "mink", "polecat, fitch, foulmart, foumart, Mustela putorius", "black-footed ferret, ferret, Mustela nigripes", "otter", "skunk, polecat, wood pussy", "badger", "armadillo", "three-toed sloth, ai, Bradypus tridactylus", "orangutan, orang, orangutang, Pongo pygmaeus", "gorilla, Gorilla gorilla", "chimpanzee, chimp, Pan troglodytes", "gibbon, Hylobates lar", "siamang, Hylobates syndactylus, Symphalangus syndactylus", "guenon, guenon monkey", "patas, hussar monkey, Erythrocebus patas", "baboon", "macaque", "langur", "colobus, colobus monkey", "proboscis monkey, Nasalis larvatus", "marmoset", "capuchin, ringtail, Cebus capucinus", "howler monkey, howler", "titi, titi monkey", "spider monkey, Ateles geoffroyi", "squirrel monkey, Saimiri sciureus", "Madagascar cat, ring-tailed lemur, Lemur catta", "indri, indris, Indri indri, Indri brevicaudatus", "Indian elephant, Elephas maximus", "African elephant, Loxodonta africana", "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens", "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca", "barracouta, snoek", "eel", "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch", "rock beauty, Holocanthus tricolor", "anemone fish", "sturgeon", "gar, garfish, garpike, billfish, Lepisosteus osseus", "lionfish", "puffer, pufferfish, blowfish, globefish", "abacus", "abaya", "academic gown, academic robe, judge's robe", "accordion, piano accordion, squeeze box", "acoustic guitar", "aircraft carrier, carrier, flattop, attack aircraft carrier", "airliner", "airship, dirigible", "altar", "ambulance", "amphibian, amphibious vehicle", "analog clock", "apiary, bee house", "apron", "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin", "assault rifle, assault gun", "backpack, back pack, knapsack, packsack, rucksack, haversack", "bakery, bakeshop, bakehouse", "balance beam, beam", "balloon", "ballpoint, ballpoint pen, ballpen, Biro", "Band Aid", "banjo", "bannister, banister, balustrade, balusters, handrail", "barbell", "barber chair", "barbershop", "barn", "barometer", "barrel, cask", "barrow, garden cart, lawn cart, wheelbarrow", "baseball", "basketball", "bassinet", "bassoon", "bathing cap, swimming cap", "bath towel", "bathtub, bathing tub, bath, tub", "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon", "beacon, lighthouse, beacon light, pharos", "beaker", "bearskin, busby, shako", "beer bottle", "beer glass", "bell cote, bell cot", "bib", "bicycle-built-for-two, tandem bicycle, tandem", "bikini, two-piece", "binder, ring-binder", "binoculars, field glasses, opera glasses", "birdhouse", "boathouse", "bobsled, bobsleigh, bob", "bolo tie, bolo, bola tie, bola", "bonnet, poke bonnet", "bookcase", "bookshop, bookstore, bookstall", "bottlecap", "bow", "bow tie, bow-tie, bowtie", "brass, memorial tablet, plaque", "brassiere, bra, bandeau", "breakwater, groin, groyne, mole, bulwark, seawall, jetty", "breastplate, aegis, egis", "broom", "bucket, pail", "buckle", "bulletproof vest", "bullet train, bullet", "butcher shop, meat market", "cab, hack, taxi, taxicab", "caldron, cauldron", "candle, taper, wax light", "cannon", "canoe", "can opener, tin opener", "cardigan", "car mirror", "carousel, carrousel, merry-go-round, roundabout, whirligig", "carpenter's kit, tool kit", "carton", "car wheel", "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM", "cassette", "cassette player", "castle", "catamaran", "CD player", "cello, violoncello", "cellular telephone, cellular phone, cellphone, cell, mobile phone", "chain", "chainlink fence", "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour", "chain saw, chainsaw", "chest", "chiffonier, commode", "chime, bell, gong", "china cabinet, china closet", "Christmas stocking", "church, church building", "cinema, movie theater, movie theatre, movie house, picture palace", "cleaver, meat cleaver, chopper", "cliff dwelling", "cloak", "clog, geta, patten, sabot", "cocktail shaker", "coffee mug", "coffeepot", "coil, spiral, volute, whorl, helix", "combination lock", "computer keyboard, keypad", "confectionery, confectionary, candy store", "container ship, containership, container vessel", "convertible", "corkscrew, bottle screw", "cornet, horn, trumpet, trump", "cowboy boot", "cowboy hat, ten-gallon hat", "cradle", "crane", "crash helmet", "crate", "crib, cot", "Crock Pot", "croquet ball", "crutch", "cuirass", "dam, dike, dyke", "desk", "desktop computer", "dial telephone, dial phone", "diaper, nappy, napkin", "digital clock", "digital watch", "dining table, board", "dishrag, dishcloth", "dishwasher, dish washer, dishwashing machine", "disk brake, disc brake", "dock, dockage, docking facility", "dogsled, dog sled, dog sleigh", "dome", "doormat, welcome mat", "drilling platform, offshore rig", "drum, membranophone, tympan", "drumstick", "dumbbell", "Dutch oven", "electric fan, blower", "electric guitar", "electric locomotive", "entertainment center", "envelope", "espresso maker", "face powder", "feather boa, boa", "file, file cabinet, filing cabinet", "fireboat", "fire engine, fire truck", "fire screen, fireguard", "flagpole, flagstaff", "flute, transverse flute", "folding chair", "football helmet", "forklift", "fountain", "fountain pen", "four-poster", "freight car", "French horn, horn", "frying pan, frypan, skillet", "fur coat", "garbage truck, dustcart", "gasmask, respirator, gas helmet", "gas pump, gasoline pump, petrol pump, island dispenser", "goblet", "go-kart", "golf ball", "golfcart, golf cart", "gondola", "gong, tam-tam", "gown", "grand piano, grand", "greenhouse, nursery, glasshouse", "grille, radiator grille", "grocery store, grocery, food market, market", "guillotine", "hair slide", "hair spray", "half track", "hammer", "hamper", "hand blower, blow dryer, blow drier, hair dryer, hair drier", "hand-held computer, hand-held microcomputer", "handkerchief, hankie, hanky, hankey", "hard disc, hard disk, fixed disk", "harmonica, mouth organ, harp, mouth harp", "harp", "harvester, reaper", "hatchet", "holster", "home theater, home theatre", "honeycomb", "hook, claw", "hoopskirt, crinoline", "horizontal bar, high bar", "horse cart, horse-cart", "hourglass", "iPod", "iron, smoothing iron", "jack-o'-lantern", "jean, blue jean, denim", "jeep, landrover", "jersey, T-shirt, tee shirt", "jigsaw puzzle", "jinrikisha, ricksha, rickshaw", "joystick", "kimono", "knee pad", "knot", "lab coat, laboratory coat", "ladle", "lampshade, lamp shade", "laptop, laptop computer", "lawn mower, mower", "lens cap, lens cover", "letter opener, paper knife, paperknife", "library", "lifeboat", "lighter, light, igniter, ignitor", "limousine, limo", "liner, ocean liner", "lipstick, lip rouge", "Loafer", "lotion", "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system", "loupe, jeweler's loupe", "lumbermill, sawmill", "magnetic compass", "mailbag, postbag", "mailbox, letter box", "maillot", "maillot, tank suit", "manhole cover", "maraca", "marimba, xylophone", "mask", "matchstick", "maypole", "maze, labyrinth", "measuring cup", "medicine chest, medicine cabinet", "megalith, megalithic structure", "microphone, mike", "microwave, microwave oven", "military uniform", "milk can", "minibus", "miniskirt, mini", "minivan", "missile", "mitten", "mixing bowl", "mobile home, manufactured home", "Model T", "modem", "monastery", "monitor", "moped", "mortar", "mortarboard", "mosque", "mosquito net", "motor scooter, scooter", "mountain bike, all-terrain bike, off-roader", "mountain tent", "mouse, computer mouse", "mousetrap", "moving van", "muzzle", "nail", "neck brace", "necklace", "nipple", "notebook, notebook computer", "obelisk", "oboe, hautboy, hautbois", "ocarina, sweet potato", "odometer, hodometer, mileometer, milometer", "oil filter", "organ, pipe organ", "oscilloscope, scope, cathode-ray oscilloscope, CRO", "overskirt", "oxcart", "oxygen mask", "packet", "paddle, boat paddle", "paddlewheel, paddle wheel", "padlock", "paintbrush", "pajama, pyjama, pj's, jammies", "palace", "panpipe, pandean pipe, syrinx", "paper towel", "parachute, chute", "parallel bars, bars", "park bench", "parking meter", "passenger car, coach, carriage", "patio, terrace", "pay-phone, pay-station", "pedestal, plinth, footstall", "pencil box, pencil case", "pencil sharpener", "perfume, essence", "Petri dish", "photocopier", "pick, plectrum, plectron", "pickelhaube", "picket fence, paling", "pickup, pickup truck", "pier", "piggy bank, penny bank", "pill bottle", "pillow", "ping-pong ball", "pinwheel", "pirate, pirate ship", "pitcher, ewer", "plane, carpenter's plane, woodworking plane", "planetarium", "plastic bag", "plate rack", "plow, plough", "plunger, plumber's helper", "Polaroid camera, Polaroid Land camera", "pole", "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria", "poncho", "pool table, billiard table, snooker table", "pop bottle, soda bottle", "pot, flowerpot", "potter's wheel", "power drill", "prayer rug, prayer mat", "printer", "prison, prison house", "projectile, missile", "projector", "puck, hockey puck", "punching bag, punch bag, punching ball, punchball", "purse", "quill, quill pen", "quilt, comforter, comfort, puff", "racer, race car, racing car", "racket, racquet", "radiator", "radio, wireless", "radio telescope, radio reflector", "rain barrel", "recreational vehicle, RV, R.V.", "reel", "reflex camera", "refrigerator, icebox", "remote control, remote", "restaurant, eating house, eating place, eatery", "revolver, six-gun, six-shooter", "rifle", "rocking chair, rocker", "rotisserie", "rubber eraser, rubber, pencil eraser", "rugby ball", "rule, ruler", "running shoe", "safe", "safety pin", "saltshaker, salt shaker", "sandal", "sarong", "sax, saxophone", "scabbard", "scale, weighing machine", "school bus", "schooner", "scoreboard", "screen, CRT screen", "screw", "screwdriver", "seat belt, seatbelt", "sewing machine", "shield, buckler", "shoe shop, shoe-shop, shoe store", "shoji", "shopping basket", "shopping cart", "shovel", "shower cap", "shower curtain", "ski", "ski mask", "sleeping bag", "slide rule, slipstick", "sliding door", "slot, one-armed bandit", "snorkel", "snowmobile", "snowplow, snowplough", "soap dispenser", "soccer ball", "sock", "solar dish, solar collector, solar furnace", "sombrero", "soup bowl", "space bar", "space heater", "space shuttle", "spatula", "speedboat", "spider web, spider's web", "spindle", "sports car, sport car", "spotlight, spot", "stage", "steam locomotive", "steel arch bridge", "steel drum", "stethoscope", "stole", "stone wall", "stopwatch, stop watch", "stove", "strainer", "streetcar, tram, tramcar, trolley, trolley car", "stretcher", "studio couch, day bed", "stupa, tope", "submarine, pigboat, sub, U-boat", "suit, suit of clothes", "sundial", "sunglass", "sunglasses, dark glasses, shades", "sunscreen, sunblock, sun blocker", "suspension bridge", "swab, swob, mop", "sweatshirt", "swimming trunks, bathing trunks", "swing", "switch, electric switch, electrical switch", "syringe", "table lamp", "tank, army tank, armored combat vehicle, armoured combat vehicle", "tape player", "teapot", "teddy, teddy bear", "television, television system", "tennis ball", "thatch, thatched roof", "theater curtain, theatre curtain", "thimble", "thresher, thrasher, threshing machine", "throne", "tile roof", "toaster", "tobacco shop, tobacconist shop, tobacconist", "toilet seat", "torch", "totem pole", "tow truck, tow car, wrecker", "toyshop", "tractor", "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi", "tray", "trench coat", "tricycle, trike, velocipede", "trimaran", "tripod", "triumphal arch", "trolleybus, trolley coach, trackless trolley", "trombone", "tub, vat", "turnstile", "typewriter keyboard", "umbrella", "unicycle, monocycle", "upright, upright piano", "vacuum, vacuum cleaner", "vase", "vault", "velvet", "vending machine", "vestment", "viaduct", "violin, fiddle", "volleyball", "waffle iron", "wall clock", "wallet, billfold, notecase, pocketbook", "wardrobe, closet, press", "warplane, military plane", "washbasin, handbasin, washbowl, lavabo, wash-hand basin", "washer, automatic washer, washing machine", "water bottle", "water jug", "water tower", "whiskey jug", "whistle", "wig", "window screen", "window shade", "Windsor tie", "wine bottle", "wing", "wok", "wooden spoon", "wool, woolen, woollen", "worm fence, snake fence, snake-rail fence, Virginia fence", "wreck", "yawl", "yurt", "web site, website, internet site, site", "comic book", "crossword puzzle, crossword", "street sign", "traffic light, traffic signal, stoplight", "book jacket, dust cover, dust jacket, dust wrapper", "menu", "plate", "guacamole", "consomme", "hot pot, hotpot", "trifle", "ice cream, icecream", "ice lolly, lolly, lollipop, popsicle", "French loaf", "bagel, beigel", "pretzel", "cheeseburger", "hotdog, hot dog, red hot", "mashed potato", "head cabbage", "broccoli", "cauliflower", "zucchini, courgette", "spaghetti squash", "acorn squash", "butternut squash", "cucumber, cuke", "artichoke, globe artichoke", "bell pepper", "cardoon", "mushroom", "Granny Smith", "strawberry", "orange", "lemon", "fig", "pineapple, ananas", "banana", "jackfruit, jak, jack", "custard apple", "pomegranate", "hay", "carbonara", "chocolate sauce, chocolate syrup", "dough", "meat loaf, meatloaf", "pizza, pizza pie", "potpie", "burrito", "red wine", "espresso", "cup", "eggnog", "alp", "bubble", "cliff, drop, drop-off", "coral reef", "geyser", "lakeside, lakeshore", "promontory, headland, head, foreland", "sandbar, sand bar", "seashore, coast, seacoast, sea-coast", "valley, vale", "volcano", "ballplayer, baseball player", "groom, bridegroom", "scuba diver", "rapeseed", "daisy", "yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum", "corn", "acorn", "hip, rose hip, rosehip", "buckeye, horse chestnut, conker", "coral fungus", "agaric", "gyromitra", "stinkhorn, carrion fungus", "earthstar", "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa", "bolete", "ear, spike, capitulum", "toilet tissue, toilet paper, bathroom tissue" };
}
}
class VGG19Test
{
private Vgg19Model ModelGen = new Vgg19Model();
private Vgg19ModelInput ModelInput = new Vgg19ModelInput();
private Vgg19ModelOutput ModelOutput = new Vgg19ModelOutput();
private VideoFrame cropped_vf = null;
ImageNetClassList classList = new ImageNetClassList();
private async Task LoadModel(string _onnxpath)
{
//Load a machine learning model
StorageFile modelFile = await StorageFile.GetFileFromPathAsync(_onnxpath);
ModelGen = await Vgg19Model.CreateVgg19Model(modelFile).ConfigureAwait(false);
}
public VGG19Test(string _onnxpath)
{
LoadModel(_onnxpath).Wait();
}
public async Task InferenceImage(string _iamgePath)
{
StorageFile imageFile = await StorageFile.GetFileFromPathAsync(_iamgePath);
using (IRandomAccessStream stream = await imageFile.OpenAsync(FileAccessMode.Read))
{
// Create the decoder from the stream
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
// Get the SoftwareBitmap representation of the file
SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();
VideoFrame vf = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);
await CropInputImageAsync(vf).ConfigureAwait(false);
ModelInput.data_0 = cropped_vf;
ModelOutput = await ModelGen.EvaluateAsync(ModelInput);
float maxProb = 0;
int maxIndex = 0;
for (int i = 0; i < ModelOutput.prob_1.Count; i++)
{
if (ModelOutput.prob_1[i] > maxProb)
{
maxIndex = i;
maxProb = ModelOutput.prob_1[i];
}
}
Console.WriteLine(string.Format("max {0}:{1}:{2}", maxIndex, classList.classList[maxIndex], maxProb));
}
}
private async Task CropInputImageAsync(VideoFrame inputVideoFrame)
{
bool useDX = inputVideoFrame.SoftwareBitmap == null;
BitmapBounds cropBounds = new BitmapBounds();
uint h = 224;
uint w = 224;
var frameHeight = useDX ? inputVideoFrame.Direct3DSurface.Description.Height : inputVideoFrame.SoftwareBitmap.PixelHeight;
var frameWidth = useDX ? inputVideoFrame.Direct3DSurface.Description.Width : inputVideoFrame.SoftwareBitmap.PixelWidth;
var requiredAR = ((float)224 / 224);
w = Math.Min((uint)(requiredAR * frameHeight), (uint)frameWidth);
h = Math.Min((uint)(frameWidth / requiredAR), (uint)frameHeight);
cropBounds.X = (uint)((frameWidth - w) / 2);
cropBounds.Y = 0;
cropBounds.Width = w;
cropBounds.Height = h;
cropped_vf = new VideoFrame(BitmapPixelFormat.Rgba8, 224, 224, BitmapAlphaMode.Ignore);
await inputVideoFrame.CopyToAsync(cropped_vf, cropBounds, null);
}
}
class Program
{
static void Main(string[] args)
{
VGG19Test vGG19Test = new VGG19Test(System.IO.Directory.GetCurrentDirectory() + "\\model.onnx");
string[] imageList = System.IO.Directory.GetFiles(System.IO.Directory.GetCurrentDirectory() + "\\test");
foreach (string str in imageList)
{
Console.WriteLine(str);
vGG19Test.InferenceImage(str).Wait();
}
Console.ReadLine();
}
}
}
| 290.151515 | 24,715 | 0.708094 | [
"MIT"
] | nkgami/WindowsML-VGG19-Samples | Samples/VGG19_Console_Demo_CS/VGG19_Console_Demo_CS/Program.cs | 28,727 | C# |
using System;
using System.Net;
using System.Web;
using Sitecore.Configuration;
using Sitecore.Pipelines;
using Sitecore.Pipelines.HttpRequest;
using Sitecore.SecurityModel;
using Sitecore.Sites;
using Unicorn.Configuration;
using Unicorn.ControlPanel.Pipelines.UnicornControlPanelRequest;
using Unicorn.ControlPanel.Responses;
using SecurityState = Unicorn.ControlPanel.Security.SecurityState;
namespace Unicorn.ControlPanel
{
/// <summary>
/// This is a httpRequestBegin pipeline processor that is effectively a sitecore-integrated HTTP handler.
/// It renders the Unicorn control panel UI if the current URL matches the activationUrl.
/// </summary>
public class UnicornControlPanelPipelineProcessor : HttpRequestProcessor
{
private readonly string _activationUrl;
private readonly string _activationSite;
public UnicornControlPanelPipelineProcessor(string activationUrl, string activationSite)
{
_activationUrl = activationUrl;
_activationSite = activationSite;
}
public override void Process(HttpRequestArgs args)
{
if (string.IsNullOrWhiteSpace(_activationUrl)) return;
if (args.Context.Request.RawUrl.StartsWith(_activationUrl, StringComparison.OrdinalIgnoreCase))
{
if (string.IsNullOrWhiteSpace(_activationSite))
{
ProcessRequest(args.Context);
args.Context.Response.End();
}
else
{
using (new SiteContextSwitcher(Factory.GetSite(_activationSite)))
{
ProcessRequest(args.Context);
args.Context.Response.End();
}
}
}
}
public virtual void ProcessRequest(HttpContext context)
{
context.Server.ScriptTimeout = 86400;
// workaround to allow streaming output without an exception in Sitecore 8.1 Update-3 and later
context.Response.Headers["X-Frame-Options"] = "SAMEORIGIN";
var verb = context.Request.QueryString["verb"];
var authProvider = UnicornConfigurationManager.AuthenticationProvider;
SecurityState securityState;
if (authProvider != null)
{
securityState = UnicornConfigurationManager.AuthenticationProvider.ValidateRequest(new HttpRequestWrapper(HttpContext.Current.Request));
}
else securityState = new SecurityState(false, false);
// this securitydisabler allows the control panel to execute unfettered when debug compilation is enabled but you are not signed into Sitecore
using (new SecurityDisabler())
{
var pipelineArgs = new UnicornControlPanelRequestPipelineArgs(verb, new HttpContextWrapper(context), securityState);
CorePipeline.Run("unicornControlPanelRequest", pipelineArgs, true);
if (pipelineArgs.Response == null)
{
pipelineArgs.Response = new PlainTextResponse("Not Found", HttpStatusCode.NotFound);
}
if (securityState.IsAllowed)
{
context.Response.AddHeader("X-Unicorn-Version", UnicornVersion.Current);
}
pipelineArgs.Response.Execute(new HttpResponseWrapper(context.Response));
}
}
}
}
| 31.945652 | 145 | 0.761824 | [
"MIT"
] | jorrit/Unicorn | src/Unicorn/ControlPanel/UnicornControlPanelPipelineProcessor.cs | 2,941 | C# |
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
namespace NRLS_APITest.Data
{
public class HttpContexts
{
public static HttpContext Valid_Create_Pointer
{
get
{
var context = new DefaultHttpContext();
context.Request.Scheme = "http";
context.Request.Host = new HostString("www.testhost.com");
context.Request.Path = new PathString("/testpath");
context.Request.Method = HttpMethods.Post;
context.Request.Headers["fromASID"] = "fromASID";
context.Request.Headers["toASID"] = "toASID";
return context;
}
}
public static HttpContext Valid_Delete_Pointer
{
get
{
var context = new DefaultHttpContext();
context.Request.Scheme = "http";
context.Request.Host = new HostString("www.testhost.com");
context.Request.Path = new PathString("/testpath");
context.Request.Method = HttpMethods.Delete;
context.Request.Headers["fromASID"] = "fromASID";
context.Request.Headers["toASID"] = "toASID";
context.Request.QueryString = QueryString.Create(new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("_id", "testId")
});
return context;
}
}
public static HttpContext Valid_ConditionalDelete
{
get
{
var context = new DefaultHttpContext();
context.Request.Scheme = "http";
context.Request.Host = new HostString("www.testhost.com");
context.Request.Path = new PathString("/testpath");
context.Request.Method = HttpMethods.Delete;
context.Request.Headers["fromASID"] = "fromASID";
context.Request.Headers["toASID"] = "toASID";
context.Request.QueryString = QueryString.Create(new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("identifier", "testSystem|testValue"),
new KeyValuePair<string, string>("subject", "https://demographics.spineservices.nhs.uk/STU3/Patient/2686033207")
});
return context;
}
}
public static HttpContext Invalid_ConditionalDelete_NoSearchValues
{
get
{
var context = new DefaultHttpContext();
context.Request.Scheme = "http";
context.Request.Host = new HostString("www.testhost.com");
context.Request.Path = new PathString("/testpath");
context.Request.Method = HttpMethods.Delete;
context.Request.Headers["fromASID"] = "fromASID";
context.Request.Headers["toASID"] = "toASID";
context.Request.QueryString = QueryString.Create(new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("identifier", ""),
new KeyValuePair<string, string>("subject", "")
});
return context;
}
}
}
}
| 39.714286 | 132 | 0.544964 | [
"Apache-2.0"
] | elementechemlyn/nrls-reference-implementation | NRLS-API/NRLS-APITest.Data/HttpContexts.cs | 3,338 | C# |
using System;
using System.Collections.Generic;
using Xunit;
namespace Coresian.UnitTests.Extensions
{
public class EnumerableTExtensionsUnitTests
{
[Theory, AutoNSubstituteData]
public void ForEachWorks(List<string> enumerable)
{
var result = new List<string>();
enumerable.ForEach(x => result.Add(x));
Assert.NotEmpty(result);
Assert.Equal(enumerable.Count, result.Count);
foreach(var r in enumerable)
Assert.Contains(result, x => x == r);
}
[Theory, AutoNSubstituteData]
public void ForEachWithExceptionWorks(List<string> enumerable)
{
var result = new List<string>();
Action action = () => enumerable.ForEach(x => throw new Exception());
Assert.Throws<Exception>(action);
}
}
}
| 31.344828 | 82 | 0.575358 | [
"MIT"
] | CodeConceptsUk/Coresian | Coresian.UnitTests/Extensions/EnumerableTExtensionsUnitTests.cs | 911 | C# |
namespace Simple.OData.Client.Tests
{
public class Activity
{
public long Id { get; set; }
public string Number { get; set; }
public string Title { get; set; }
public Option Option { get; set; }
public Ticket Ticket { get; set; }
}
public class Ticket
{
public long Id { get; set; }
public string Number { get; set; }
public string Title { get; set; }
}
public class Option
{
public long Id { get; set; }
public string Description { get; set; }
}
} | 18.516129 | 47 | 0.538328 | [
"MIT"
] | BISmb/Simple.OData.Client | src/Simple.OData.Client.UnitTests/Entities/Activity.cs | 576 | C# |
using Microsoft.Phone.Shell;
using PushSDK;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
using WPCordovaClassLib.Cordova.JSON;
namespace Cordova.Extension.Commands
{
public class PWTags : BaseCommand
{
private static NotificationService NotificationService
{
get { return ((PhonePushApplicationService)PhoneApplicationService.Current).NotificationService; }
}
public void SendTags(string options)
{
NotificationService.Tags.OnSendingComplete += (sender, args) => DispatchCommandResult(new PluginResult(PluginResult.Status.OK, JsonHelper.Serialize(args.Result)));
NotificationService.Tags.SendRequest(options);
}
}
}
| 32.5 | 176 | 0.691026 | [
"MIT"
] | hossain-rayhan/push-notifications-sdk | SDK Sample Projects/WP8-Phonegap/WP8-Phonegap/Plugins/PushWoosh/PWTags.cs | 782 | C# |
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
namespace Yandex.HtmlElements.Elements
{
public class Radio : TypifiedElement
{
public Radio(IWebElement element)
: base(element)
{ }
public IList<IWebElement> GetButtons()
{
String radioName = WrappedElement.GetAttribute("name");
String xpath;
if (radioName == null)
{
xpath = "self::* | following::input[@type = 'radio'] | preceding::input[@type = 'radio']";
}
else
{
xpath = string.Format(
"self::* | following::input[@type = 'radio' and @name = '{0}'] | " +
"preceding::input[@type = 'radio' and @name = '{0}']",
radioName);
}
return WrappedElement.FindElements(By.XPath(xpath));
}
public IWebElement GetSelectedButton()
{
foreach (IWebElement button in GetButtons())
{
if (button.Selected)
{
return button;
}
}
throw new NoSuchElementException("No selected button");
}
public bool HasSelectedButton()
{
foreach (IWebElement button in GetButtons())
{
if (button.Selected)
{
return true;
}
}
return false;
}
public void SelectByValue(string value)
{
foreach (IWebElement button in GetButtons())
{
string buttonValue = button.GetAttribute("value");
if (value == buttonValue)
{
SelectButton(button);
return;
}
}
throw new NoSuchElementException(string.Format("Cannot locate radio button with value: {0}", value));
}
public void SelectByIndex(int index)
{
IList<IWebElement> buttons = GetButtons();
if (index < 0 || index >= buttons.Count)
{
throw new NoSuchElementException(string.Format("Cannot locate radio button with index: {0}", index));
}
SelectButton(buttons[index]);
}
private void SelectButton(IWebElement button)
{
if (!button.Selected)
{
button.Click();
}
}
}
}
| 27.677419 | 117 | 0.465812 | [
"Apache-2.0"
] | HardNorth/htmlelements-dotnet | HtmlElements-dotNet/Elements/Radio.cs | 2,576 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace CleanArchitecture.Blazor.Application.Features.Wallets.Commands.Delete;
public class DeleteWalletCommandValidator : AbstractValidator<DeleteWalletCommand>
{
public DeleteWalletCommandValidator()
{
//TODO:Implementing DeleteWalletCommandValidator method
//ex. RuleFor(v => v.Id).NotNull().GreaterThan(0);
throw new System.NotImplementedException();
}
}
public class DeleteCheckedWalletsCommandValidator : AbstractValidator<DeleteCheckedWalletsCommand>
{
public DeleteCheckedWalletsCommandValidator()
{
//TODO:Implementing DeleteProductCommandValidator method
//ex. RuleFor(v => v.Id).NotNull().NotEmpty();
throw new System.NotImplementedException();
}
}
| 35.08 | 98 | 0.745724 | [
"Apache-2.0"
] | jccirs09/CleanArchitectureWithBlazorServer | src/Application/Features/Wallets/Commands/Delete/DeleteWalletCommandValidator.cs | 879 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NLog;
namespace Example.Mvc4.Net45.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var logger = LogManager.GetCurrentClassLogger();
logger.Trace("Trace message");
logger.Debug("Debug message");
logger.Info("Info message");
logger.Warn("Warn message");
logger.Error("Error message");
logger.Debug(new {
message = "Check out this object",
data = new List<string>() {
"Code A",
"Code B",
"Code C",
},
count = 3
});
logger.ErrorException("Error message with exception", new NotImplementedException());
logger.Fatal("Fatal message");
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
| 26.538462 | 97 | 0.522464 | [
"MIT"
] | sorenhl/Glimpse.NLog | Example.Mvc4.Net45/Controllers/HomeController.cs | 1,382 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the lightsail-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Lightsail.Model
{
/// <summary>
/// Container for the parameters to the DeleteInstance operation.
/// Deletes an Amazon Lightsail instance.
///
///
/// <para>
/// The <code>delete instance</code> operation supports tag-based access control via resource
/// tags applied to the resource identified by <code>instance name</code>. For more information,
/// see the <a href="https://lightsail.aws.amazon.com/ls/docs/en/articles/amazon-lightsail-controlling-access-using-tags">Lightsail
/// Dev Guide</a>.
/// </para>
/// </summary>
public partial class DeleteInstanceRequest : AmazonLightsailRequest
{
private bool? _forceDeleteAddOns;
private string _instanceName;
/// <summary>
/// Gets and sets the property ForceDeleteAddOns.
/// <para>
/// A Boolean value to indicate whether to delete the enabled add-ons for the disk.
/// </para>
/// </summary>
public bool ForceDeleteAddOns
{
get { return this._forceDeleteAddOns.GetValueOrDefault(); }
set { this._forceDeleteAddOns = value; }
}
// Check to see if ForceDeleteAddOns property is set
internal bool IsSetForceDeleteAddOns()
{
return this._forceDeleteAddOns.HasValue;
}
/// <summary>
/// Gets and sets the property InstanceName.
/// <para>
/// The name of the instance to delete.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string InstanceName
{
get { return this._instanceName; }
set { this._instanceName = value; }
}
// Check to see if InstanceName property is set
internal bool IsSetInstanceName()
{
return this._instanceName != null;
}
}
} | 33.395349 | 136 | 0.622214 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Lightsail/Generated/Model/DeleteInstanceRequest.cs | 2,872 | 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.
// 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("9b90da10-1eae-4cde-a1a0-660985d70686")]
// 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.*")]
| 37.12 | 84 | 0.742457 | [
"MIT"
] | AJH16/tokenizer | Tokenizer.Tests/Properties/AssemblyInfo.cs | 930 | C# |
using Autofac;
using Autofac.Extras.DynamicProxy;
using LiberisLabs.DogStatsD.Interceptors;
namespace LiberisLabs.DogStatsD.FunctionalTests
{
public class TestServiceFactory
{
public ITestService Create()
{
var builder = new ContainerBuilder();
builder.RegisterType<DogStatsdInterceptor>();
builder.RegisterType<TestService>()
.InterceptedBy(typeof(DogStatsdInterceptor))
.As<ITestService>()
.EnableInterfaceInterceptors();
var container = builder.Build();
var service = container.Resolve<ITestService>();
return service;
}
}
}
| 24.678571 | 60 | 0.620839 | [
"MIT"
] | LiberisLabs/DogStatsD.Interceptors | src/LiberisLabs.DogStatsD.FunctionalTests/TestServiceFactory.cs | 693 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Abp.Extensions;
namespace Ranallo.DocKeeper.Identity
{
public class ExternalLoginInfoHelper
{
public static (string name, string surname) GetNameAndSurnameFromClaims(List<Claim> claims)
{
string name = null;
string surname = null;
var givennameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName);
if (givennameClaim != null && !givennameClaim.Value.IsNullOrEmpty())
{
name = givennameClaim.Value;
}
var surnameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname);
if (surnameClaim != null && !surnameClaim.Value.IsNullOrEmpty())
{
surname = surnameClaim.Value;
}
if (name == null || surname == null)
{
var nameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);
if (nameClaim != null)
{
var nameSurName = nameClaim.Value;
if (!nameSurName.IsNullOrEmpty())
{
var lastSpaceIndex = nameSurName.LastIndexOf(' ');
if (lastSpaceIndex < 1 || lastSpaceIndex > (nameSurName.Length - 2))
{
name = surname = nameSurName;
}
else
{
name = nameSurName.Substring(0, lastSpaceIndex);
surname = nameSurName.Substring(lastSpaceIndex);
}
}
}
}
return (name, surname);
}
}
}
| 34.339623 | 99 | 0.484615 | [
"MIT"
] | alejsouza/DocKeeper | aspnet-core/src/Ranallo.DocKeeper.Web.Core/Identity/ExternalLoginInfoHelper.cs | 1,822 | C# |
/// <summary>
/// 任务处理,一般用在回调中
/// </summary>
public class Task
{
/// <summary>
/// 任务处理的代理
/// </summary>
public delegate void taskFunc(object para, object[] list);
private taskFunc cb;
private object para;
public Task(taskFunc cb)
{
this.cb = cb;
}
public Task(taskFunc cb, object para)
{
this.cb = cb;
this.para = para;
}
/// <summary>
/// 调度入口
/// </summary>
public void Go(params object[] list)
{
cb(this.para, list);
}
}
| 15.060606 | 60 | 0.561368 | [
"MIT"
] | 741645596/Lab | Assets/Scripts/dependence/Task.cs | 545 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using Azure.Core;
namespace Azure.ResourceManager.Network.Models
{
/// <summary> Result of the request to list VpnGateways. It contains a list of VpnGateways and a URL nextLink to get the next set of results. </summary>
public partial class ListVpnGatewaysResult
{
/// <summary> Initializes a new instance of ListVpnGatewaysResult. </summary>
internal ListVpnGatewaysResult()
{
Value = new ChangeTrackingList<VpnGateway>();
}
/// <summary> Initializes a new instance of ListVpnGatewaysResult. </summary>
/// <param name="value"> List of VpnGateways. </param>
/// <param name="nextLink"> URL to get the next set of operation list results if there are any. </param>
internal ListVpnGatewaysResult(IReadOnlyList<VpnGateway> value, string nextLink)
{
Value = value;
NextLink = nextLink;
}
/// <summary> List of VpnGateways. </summary>
public IReadOnlyList<VpnGateway> Value { get; }
/// <summary> URL to get the next set of operation list results if there are any. </summary>
public string NextLink { get; }
}
}
| 36.405405 | 156 | 0.662212 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/Models/ListVpnGatewaysResult.cs | 1,347 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Diagnostics.Runtime.Implementation;
using Microsoft.Diagnostics.Runtime.Utilities;
using Xunit;
namespace Microsoft.Diagnostics.Runtime.Tests
{
public class BinaryLocatorTests
{
public static readonly string WellKnownDac = "mscordacwks_X86_X86_4.6.96.00.dll";
public static readonly uint WellKnownDacTimeStamp = 0x55b96946;
public static readonly uint WellKnownDacImageSize = 0x006a8000;
public static readonly string WellKnownNativePdb = "clr.pdb";
public static readonly Guid WellKnownNativePdbGuid = new Guid("0350aa66-2d49-4425-ab28-9b43a749638d");
public static readonly int WellKnownNativePdbAge = 2;
internal static IBinaryLocator GetLocator()
{
return new SymbolServerLocator($"srv*{Helpers.TestWorkingDirectory}*http://msdl.microsoft.com/download/symbols");
}
[Fact(Skip ="Touches network, don't run regularly.")]
public void FindBinaryNegativeTest()
{
IBinaryLocator _locator = GetLocator();
string dac = _locator.FindBinary(WellKnownDac, WellKnownDacTimeStamp + 1, WellKnownDacImageSize + 1, false);
Assert.Null(dac);
}
[Fact(Skip = "Touches network, don't run regularly.")]
public async Task FindBinaryAsyncNegativeTest()
{
IBinaryLocator _locator = GetLocator();
List<Task<string>> tasks = new List<Task<string>>();
for (int i = 0; i < 10; i++)
tasks.Add(_locator.FindBinaryAsync(WellKnownDac, WellKnownDacTimeStamp + 1, WellKnownDacImageSize + 1, false));
// Ensure we got the same answer for everything.
foreach (Task<string> task in tasks)
{
string dac = await task;
Assert.Null(dac);
}
}
[Fact(Skip = "Touches network, don't run regularly.")]
public void FindBinaryTest()
{
IBinaryLocator _locator = GetLocator();
string dac = _locator.FindBinary(WellKnownDac, WellKnownDacTimeStamp, WellKnownDacImageSize, false);
Assert.NotNull(dac);
Assert.True(File.Exists(dac));
}
[Fact(Skip = "Touches network, don't run regularly.")]
public async Task FindBinaryAsyncTest()
{
IBinaryLocator _locator = GetLocator();
Task<string> first = _locator.FindBinaryAsync(WellKnownDac, WellKnownDacTimeStamp, WellKnownDacImageSize, false);
List<Task<string>> tasks = new List<Task<string>>();
for (int i = 0; i < 10; i++)
tasks.Add(_locator.FindBinaryAsync(WellKnownDac, WellKnownDacTimeStamp, WellKnownDacImageSize, false));
string dac = await first;
Assert.NotNull(dac);
Assert.True(File.Exists(dac));
using (Stream stream = File.OpenRead(dac))
{
PEImage peimage = new PEImage(stream);
Assert.True(peimage.IsValid);
}
// Ensure we got the same answer for everything.
foreach (Task<string> task in tasks)
{
string taskDac = await task;
Assert.Equal(dac, taskDac);
}
}
}
}
| 38.569892 | 127 | 0.627265 | [
"MIT"
] | swift-kim/clrmd | src/Microsoft.Diagnostics.Runtime.Tests/src/BinaryLocatorTests.cs | 3,589 | C# |
using Tyr.Agents;
namespace Tyr.StrategyAnalysis
{
public class SporeCrawler : Strategy
{
private static SporeCrawler Singleton = new SporeCrawler();
public static Strategy Get()
{
return Singleton;
}
public override bool Detect()
{
return Tyr.Bot.EnemyStrategyAnalyzer.Count(UnitTypes.SPORE_CRAWLER) + Tyr.Bot.EnemyStrategyAnalyzer.Count(UnitTypes.SPORE_CRAWLER_UPROOTED) > 0;
}
public override string Name()
{
return "SporeCrawler";
}
}
}
| 22.96 | 156 | 0.609756 | [
"MIT"
] | kblood/TyrSc2 | Tyr/StrategyAnalysis/SporeCrawler.cs | 576 | C# |
using System.Collections.Generic;
namespace Demo.Entity
{
public class Role : BaseEntity
{
public string Name { get; set; }
public string Description { get; set; }
public List<Permission> Permissions { get; set; }
}
}
| 21.333333 | 57 | 0.628906 | [
"MIT"
] | trungnguyendlu/demo-asp-net-core | Demo.Entity/Role.cs | 258 | C# |
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
[TestFixture]
public class Perf7
{
[TestCase]
public void ChangePriority_ThreadExecutor_ShouldWorkFast()
{
//Arange
const int items = 100_000;
IScheduler executor = new ThreadExecutor();
Stopwatch watch = new Stopwatch();
Dictionary<Priority, List<Task>> dict = new Dictionary<Priority, List<Task>>();
dict.Add(Priority.LOW, new List<Task>());
dict.Add(Priority.MEDIUM, new List<Task>());
dict.Add(Priority.HIGH, new List<Task>());
dict.Add(Priority.EXTREME, new List<Task>());
Priority[] priorities = new Priority[] { Priority.LOW, Priority.MEDIUM, Priority.HIGH, Priority.EXTREME };
Random rand = new Random();
//Act
for (int i = 0; i < items; i++)
{
Task task = new Task(i, rand.Next(0, 10000), priorities[rand.Next(0, 4)]);
dict[task.TaskPriority].Add(task);
executor.Execute(task);
}
dict[Priority.LOW] = dict[Priority.LOW].OrderByDescending(x => x.Id).ToList();
dict[Priority.MEDIUM] = dict[Priority.MEDIUM].OrderByDescending(x => x.Id).ToList();
dict[Priority.HIGH] = dict[Priority.HIGH].OrderByDescending(x => x.Id).ToList();
dict[Priority.EXTREME] = dict[Priority.EXTREME].OrderByDescending(x => x.Id).ToList();
//Act
Priority p1 = priorities[rand.Next(0, 4)];
Priority p2 = priorities[rand.Next(0, 4)];
int randomCount = rand.Next(5000, 6000);
List<Task> p2Tasks = dict[p2].Skip(randomCount - (randomCount / 2)).Take(randomCount).ToList();
List<Task> p1Tasks = dict[p1].Skip(randomCount - (randomCount / 2)).Take(randomCount).ToList();
watch.Start();
int min = Math.Min(p1Tasks.Count, p2Tasks.Count);
for (int i = 0; i < min; i++)
{
executor.ChangePriority(p1Tasks[i].Id, p2);
executor.ChangePriority(p2Tasks[i].Id, p1);
}
watch.Stop();
dict[p1].RemoveRange(randomCount - (randomCount / 2), randomCount);
dict[p2].RemoveRange(randomCount - (randomCount / 2), randomCount);
dict[p1].AddRange(p2Tasks);
dict[p2].AddRange(p1Tasks);
dict[p1] = dict[p1].OrderByDescending(x => x.Id).ToList();
dict[p2] = dict[p2].OrderByDescending(x => x.Id).ToList();
CollectionAssert.AreEqual(dict[p1], executor.GetByPriority(p1));
CollectionAssert.AreEqual(dict[p2], executor.GetByPriority(p2));
//Assert
Assert.Less(watch.ElapsedMilliseconds, 200);
}
}
| 34.461538 | 114 | 0.614583 | [
"Apache-2.0"
] | KostadinovK/Data-Structures | 12-Exam-Prep/Exam-20.05.2018/01-Scheduler/ThreadExecutorTest/Performance/Perf7.cs | 2,690 | C# |
using System.Reflection;
namespace UnityEditor.ShaderGraph
{
[Title("Math", "Round", "Truncate")]
public class TruncateNode : CodeFunctionNode
{
public TruncateNode()
{
name = "Truncate";
}
public override string documentationURL
{
get { return "https://github.com/Unity-Technologies/ShaderGraph/wiki/Truncate-Node"; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_Truncate", BindingFlags.Static | BindingFlags.NonPublic);
}
static string Unity_Truncate(
[Slot(0, Binding.None)] DynamicDimensionVector In,
[Slot(1, Binding.None)] out DynamicDimensionVector Out)
{
return
@"
{
Out = trunc(In);
}
";
}
}
}
| 23.805556 | 103 | 0.576429 | [
"BSD-2-Clause"
] | 1-10/VisualEffectGraphSample | GitHub/com.unity.shadergraph/Editor/Data/Nodes/Math/Round/TruncateNode.cs | 857 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TrackIt.UI.Controllers
{
public class PortalController : Controller
{
// GET: Portal
public ActionResult Index()
{
return View();
}
}
} | 18.235294 | 46 | 0.625806 | [
"MIT"
] | rolfintatu/trackIt | src/TrackIt.UI/Controllers/PortalController.cs | 312 | C# |
using Gestionale.Pages;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Gestionale.Data
{
public class Iscrizione
{
[Key]
public int Id { get; set; }
public DateTime DataIscrizione { get; set; }
public int? CorsiId { get; set; }
public Corso Corsi { get; set; }//FK
public virtual ICollection<Partecipante> Partecipanti { get; set; }
public Iscrizione() { }
public Iscrizione( int? corsiid )
{
DataIscrizione = DateTime.Now;
CorsiId = corsiid;
}
}
}
| 23.448276 | 75 | 0.616176 | [
"MIT"
] | FITSTIC/Hackathon_Team1_19_21 | Gestionale/Gestionale/Data/Iscrizione.cs | 682 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Domain
{
/// <summary>
/// KoubeiCateringDishDictionaryQueryModel Data Structure.
/// </summary>
public class KoubeiCateringDishDictionaryQueryModel : AlipayObject
{
/// <summary>
/// 业务字典类型. 定义如下: catetory 分类 ;unit 单位;spec 规格;virtual_category 虚拟类目。
/// </summary>
[JsonPropertyName("biz_type")]
public string BizType { get; set; }
/// <summary>
/// 字典的数据id
/// </summary>
[JsonPropertyName("dictionary_id")]
public string DictionaryId { get; set; }
/// <summary>
/// 字典的扩展json,根据不同的biz_type,设置商家的自定义字典表key以及value。如果字典类型为catetory, key为cateSort,cateType,level,parentCatetoryId(level传数字,cateType为dish或cook) ;如果字典类型为spec, key为specSort.。注意:如果是字符串拼接的方式,转移符\要替换为\\\ 。
/// </summary>
[JsonPropertyName("ext_info")]
public string ExtInfo { get; set; }
/// <summary>
/// 商户的支付宝user_id. 商户授权后,isv能获得
/// </summary>
[JsonPropertyName("merchant_id")]
public string MerchantId { get; set; }
/// <summary>
/// open 启动 stop 停用
/// </summary>
[JsonPropertyName("status")]
public string Status { get; set; }
}
}
| 31.707317 | 206 | 0.604615 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Domain/KoubeiCateringDishDictionaryQueryModel.cs | 1,542 | C# |
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Squadron;
namespace HotChocolate.Data.Projections.Spatial
{
public class DatabaseContext<T> : DbContext where T : class
{
private readonly PostgreSqlResource<PostgisConfig> _resource;
private readonly string _databaseName;
private bool _disposed;
public DatabaseContext(PostgreSqlResource<PostgisConfig> resource, string databaseName)
{
_resource = resource;
_databaseName = databaseName;
}
public DbSet<T> Data { get; set; } = default!;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(
_resource.GetConnectionString(_databaseName),
o => o.UseNetTopologySuite());
}
public override async ValueTask DisposeAsync()
{
await base.DisposeAsync();
if (!_disposed)
{
_disposed = true;
}
}
}
}
| 27.435897 | 95 | 0.616822 | [
"MIT"
] | AccountTechnologies/hotchocolate | src/HotChocolate/Spatial/test/Data.Projections.SqlServer.Tests/DatabaseContext.cs | 1,070 | C# |
using System;
using cm = System.ComponentModel.DataAnnotations;
namespace Bb.OptionServer.Repositories.Tables
{
[cm.Schema.Table("Environment", Schema = "dbo")]
public class EnvironmentTable : IPrimaryTable
{
public EnvironmentTable()
{
_mapping = DtoSqlManager.GetMapping(GetType());
Id = new FieldValue<Guid>() { Parent = this, Properties = _mapping.IndexByName[nameof(Id)] };
Name = new FieldValue<string>() { Parent = this, Properties = _mapping.IndexByName[nameof(Name)] };
GroupId = new FieldValue<Guid>() { Parent = this, Properties = _mapping.IndexByName[nameof(GroupId)] };
LastUpdate = new FieldValue<DateTimeOffset>() { Parent = this, Properties = _mapping.IndexByName[nameof(LastUpdate)] };
SecurityCoherence = new FieldValue<Guid>() { Parent = this, Properties = _mapping.IndexByName[nameof(SecurityCoherence)] };
}
[cm.Key]
[cm.Required]
public FieldValue<Guid> Id { get; }
[cm.Required]
[cm.MaxLength(50)]
public FieldValue<string> Name { get; }
[cm.Required]
public FieldValue<Guid> GroupId { get; }
[LastChangeDate]
public FieldValue<DateTimeOffset> LastUpdate { get; }
[SecurityCoherence]
public FieldValue<Guid> SecurityCoherence { get; }
private readonly ObjectMapping _mapping;
}
}
| 34.047619 | 135 | 0.637063 | [
"Apache-2.0"
] | Moleculars/OptionServer | Src/OptionServer/Black.Beard.OptionServer/Repositories/Tables/EnvironmentTable.cs | 1,432 | C# |
/* _BEGIN_TEMPLATE_
{
"id": "GILA_BOSS_54e",
"name": [
"同化效应",
"Assimilation"
],
"text": [
"法力值消耗减少(1)点。",
"Cost reduced by (1)."
],
"cardClass": "NEUTRAL",
"type": "ENCHANTMENT",
"cost": null,
"rarity": null,
"set": "GILNEAS",
"collectible": null,
"dbfId": 49030
}
_END_TEMPLATE_ */
namespace HREngine.Bots
{
class Sim_GILA_BOSS_54e : SimTemplate
{
}
} | 15.037037 | 41 | 0.566502 | [
"MIT"
] | chi-rei-den/Silverfish | cards/GILNEAS/GILA/Sim_GILA_BOSS_54e.cs | 436 | C# |
using N8T.Core.Domain;
using N8T.Infrastructure.EfCore;
namespace ProductService.Infrastructure.Data
{
public class Repository<TEntity> : RepositoryBase<MainDbContext, TEntity> where TEntity : EntityBase, IAggregateRoot
{
public Repository(MainDbContext dbContext) : base(dbContext)
{
}
}
}
| 25.230769 | 120 | 0.719512 | [
"MIT"
] | Aharonyan-Narek/clean-architecture-dotnet | samples/Product/ProductService.Infrastructure/Data/Repository.cs | 328 | C# |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
using System;
using System.Collections;
using System.Runtime.InteropServices;
using VR = UnityEngine.VR;
using XR = UnityEngine.XR;
/// <summary>
/// Add OVROverlay script to an object with a Quad mesh filter to have the quad
/// rendered as a TimeWarp overlay instead by drawing it into the eye buffer.
/// This will take full advantage of the display resolution and avoid double
/// resampling of the texture.
///
/// If the texture is dynamically generated, as for an interactive GUI or
/// animation, it must be explicitly triple buffered to avoid flickering
/// when it is referenced asynchronously by TimeWarp.
/// </summary>
public class OVROverlay : MonoBehaviour
{
public enum OverlayType
{
None, // Disabled the overlay
Underlay, // Eye buffers blend on top
Overlay, // Blends on top of the eye buffer
OverlayShowLod // Blends on top and colorizes texture level of detail
};
OverlayType currentOverlayType = OverlayType.Overlay;
#if !UNITY_ANDROID || UNITY_EDITOR
Texture texture;
#endif
IntPtr texId = IntPtr.Zero;
void Awake()
{
Debug.Log ("Overlay Awake");
// Getting the NativeTextureID/PTR synchronizes with the multithreaded renderer, which
// causes a problem on the first frame if this gets called after the OVRDisplay initialization,
// so do it in Awake() instead of Start().
texId = this.GetComponent<Renderer>().material.mainTexture.GetNativeTexturePtr();
#if !UNITY_ANDROID || UNITY_EDITOR
texture = this.GetComponent<Renderer>().material.mainTexture;
#endif
}
void Update()
{
#if !UNITY_ANDROID || UNITY_EDITOR
if (this.GetComponent<Renderer>().material.mainTexture != texture)
{
texId = this.GetComponent<Renderer>().material.mainTexture.GetNativeTexturePtr();
texture = this.GetComponent<Renderer>().material.mainTexture;
}
#endif
if (Input.GetKey (KeyCode.Joystick1Button0))
{
currentOverlayType = OverlayType.None;
}
else if (Input.GetKey (KeyCode.Joystick1Button1))
{
currentOverlayType = OverlayType.OverlayShowLod;
}
else
{
currentOverlayType = OverlayType.Overlay;
}
}
void OnRenderObject ()
{
// The overlay must be specified every eye frame, because it is positioned relative to the
// current head location. If frames are dropped, it will be time warped appropriately,
// just like the eye buffers.
if (currentOverlayType == OverlayType.None)
{
GetComponent<Renderer>().enabled = true; // use normal renderer
return;
}
bool overlay = (currentOverlayType == OverlayType.Overlay);
Transform camPose = Camera.current.transform;
Matrix4x4 modelToCamera = camPose.worldToLocalMatrix * transform.localToWorldMatrix;
Vector3 headPos = XR.InputTracking.GetLocalPosition(XR.XRNode.Head);
Quaternion headOrt = XR.InputTracking.GetLocalRotation(XR.XRNode.Head);
Matrix4x4 cameraToStart = Matrix4x4.TRS(headPos, headOrt, Vector3.one);
Matrix4x4 modelToStart = cameraToStart * modelToCamera;
OVRPose pose;
pose.position = modelToStart.GetColumn(3);
pose.orientation = Quaternion.LookRotation(modelToStart.GetColumn(2), modelToStart.GetColumn(1));
// Convert left-handed to right-handed.
pose.position.z = -pose.position.z;
pose.orientation.w = -pose.orientation.w;
Vector3 scale = transform.lossyScale;
for (int i = 0; i < 3; ++i)
scale[i] /= Camera.current.transform.lossyScale[i];
OVRPlugin.Bool result = OVRPlugin.SetOverlayQuad(overlay.ToBool(), texId, IntPtr.Zero, pose.ToPosef(), scale.ToVector3f());
GetComponent<Renderer>().enabled = (result == OVRPlugin.Bool.False); // render with the overlay plane instead of the normal renderer
}
}
| 35.195489 | 135 | 0.708609 | [
"Apache-2.0"
] | dadadau/LeapMotionCoreAssets | Assets/OVR/Moonlight/Scripts/OVROverlay.cs | 4,683 | C# |
// <copyright file="TestConsumer.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// 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.Threading.Tasks;
using MassTransit;
namespace OpenTelemetry.Contrib.Instrumentation.MassTransit.Tests
{
public class TestConsumer : IConsumer<TestMessage>
{
public Task Consume(ConsumeContext<TestMessage> context)
{
return Task.CompletedTask;
}
}
}
| 33.2 | 75 | 0.72992 | [
"Apache-2.0"
] | Austin-Tan/opentelemetry-dotnet-contrib | test/OpenTelemetry.Contrib.Instrumentation.MassTransit.Tests/TestConsumer.cs | 998 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Boligrafos;
namespace EjercicioNro33
{
class Program
{
static void Main(string[] args)
{
List<Boligrafo> miLista = new List<Boligrafo>();
Boligrafo Unboligrafo = new Boligrafo("blanco", "bic", 60);
Unboligrafo.Escribir(70);
if (Unboligrafo.RecargarTinta(90))
Console.WriteLine("Boligrafo Recargado");
else
Console.WriteLine("No se pudo recargar");
Unboligrafo.Escribir(30);
if (Unboligrafo.RecargarTinta())
Console.WriteLine("Boligrafo Recargado");
else
Console.WriteLine("No se pudo recargar");
miLista = miLista + Unboligrafo;
Boligrafo boligrafo2 = new Boligrafo("rojo", "Silvapen", 50);
miLista.Add(boligrafo2);
Console.WriteLine(" Muestro :");
Boligrafo.MostrarBoligrafos(miLista);
Console.ReadLine();
Console.WriteLine(" Sumo :");
Boligrafo Otrobligrafo = new Boligrafo("verde", "Parker", 60);
miLista = miLista + Otrobligrafo;
Boligrafo.MostrarBoligrafos(miLista);
Console.ReadLine();
Console.WriteLine(" Resto :");
Boligrafo BoligrafoTres = new Boligrafo(40, "verde", "Parker");
miLista = miLista - BoligrafoTres;
Boligrafo.MostrarBoligrafos(miLista);
Console.ReadLine();
}
}
}
| 32.98 | 76 | 0.562765 | [
"MIT"
] | ezequielfreire007/EjerciciosLab2 | EjercicioNro33/EjercicioNro33/Program.cs | 1,651 | C# |
#region copyright
// -------------------------------------------------------
// Copyright (C) Dmitriy Yukhanov [https://codestage.net]
// -------------------------------------------------------
#endregion
namespace CodeStage.Maintainer.Issues.Detectors
{
using Core.Scan;
internal interface IGameObjectBeginIssueDetector : IGameObjectBeginScanListener<DetectorResults>
{
}
} | 27.214286 | 97 | 0.553806 | [
"MIT"
] | rafaeldolfe/MasterServerChess | Assets/Plugins/CodeStage/Maintainer/Editor/Scripts/Modules/RecordsBased/Issues/Detectors/Interfaces/IGameObjectBeginIssueDetector.cs | 383 | C# |
using DataModel;
using FluentValidation;
using Infrastructure.Core.Queries;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace UsersService.Queries
{
public class GetUserQuery
{
public class Query : IQuery<Result>
{
public Guid Id { get; set; }
}
public class Result
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
public class Validator: AbstractValidator<Query>
{
public Validator()
{
RuleFor(query => query.Id).NotEmpty();
}
}
public class Handler : IQueryHandler<Query, Result>
{
private readonly DatabaseContext _db;
public Handler(DatabaseContext db)
{
_db = db;
}
public async Task<Result> Handle(Query query, CancellationToken cancellationToken)
{
var user = await GetUser(query.Id);
if (user is null)
{
throw new ArgumentNullException($"{nameof(user)} was not found by id '{query.Id}'");
}
return user;
}
private async Task<Result> GetUser(Guid id)
{
var query = from user in _db.Users
where user.Id == id
select new Result
{
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName
};
var result = await query.FirstOrDefaultAsync();
return result;
}
}
}
}
| 26.60274 | 104 | 0.477858 | [
"MIT"
] | GuilhermeStracini/NetCoreMicroservicesSample | Src/UsersService/Queries/GetUserQuery.cs | 1,944 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace LaundryManagementSystem.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.774194 | 151 | 0.586271 | [
"MIT"
] | Ash200042123/SWE-4202---OOC-I | LaundryManagementSystem/Properties/Settings.Designer.cs | 1,080 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Cdn;
using Aliyun.Acs.Cdn.Transform;
using Aliyun.Acs.Cdn.Transform.V20180510;
namespace Aliyun.Acs.Cdn.Model.V20180510
{
public class StopCdnDomainRequest : RpcAcsRequest<StopCdnDomainResponse>
{
public StopCdnDomainRequest()
: base("Cdn", "2018-05-10", "StopCdnDomain")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.Cdn.Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.Cdn.Endpoint.endpointRegionalType, null);
}
Method = MethodType.POST;
}
private string securityToken;
private string domainName;
private long? ownerId;
public string SecurityToken
{
get
{
return securityToken;
}
set
{
securityToken = value;
DictionaryUtil.Add(QueryParameters, "SecurityToken", value);
}
}
public string DomainName
{
get
{
return domainName;
}
set
{
domainName = value;
DictionaryUtil.Add(QueryParameters, "DomainName", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public override StopCdnDomainResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return StopCdnDomainResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 27.842105 | 134 | 0.679017 | [
"Apache-2.0"
] | pengweiqhca/aliyun-openapi-net-sdk | aliyun-net-sdk-cdn/Cdn/Model/V20180510/StopCdnDomainRequest.cs | 2,645 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Hosting;
using System.Web.Http.Routing;
using System.Web.Http.WebHost.Properties;
using System.Web.Routing;
namespace System.Web.Http.WebHost.Routing
{
internal class HostedHttpRouteCollection : HttpRouteCollection
{
private readonly RouteCollection _routeCollection;
public HostedHttpRouteCollection(RouteCollection routeCollection)
{
if (routeCollection == null)
{
throw Error.ArgumentNull("routeCollection");
}
_routeCollection = routeCollection;
}
/// <inheritdoc/>
public override string VirtualPathRoot
{
get { return HostingEnvironment.ApplicationVirtualPath; }
}
/// <inheritdoc/>
public override int Count
{
get { return _routeCollection.Count; }
}
/// <inheritdoc/>
public override IHttpRoute this[string name]
{
get
{
HttpWebRoute route = _routeCollection[name] as HttpWebRoute;
if (route != null)
{
return route.HttpRoute;
}
throw Error.KeyNotFound();
}
}
/// <inheritdoc/>
public override IHttpRoute this[int index]
{
get
{
HttpWebRoute route = _routeCollection[index] as HttpWebRoute;
if (route != null)
{
return route.HttpRoute;
}
throw Error.ArgumentOutOfRange("index", index, SRResources.RouteCollectionOutOfRange);
}
}
/// <inheritdoc/>
public override IHttpRouteData GetRouteData(HttpRequestMessage request)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
HttpContextBase httpContextBase = request.GetHttpContext();
if (httpContextBase == null)
{
httpContextBase = new HttpRequestMessageContextWrapper(VirtualPathRoot, request);
}
if (httpContextBase.GetHttpRequestMessage() == null)
{
httpContextBase.SetHttpRequestMessage(request);
}
RouteData routeData = _routeCollection.GetRouteData(httpContextBase);
if (routeData != null)
{
return new HostedHttpRouteData(routeData);
}
return null;
}
/// <inheritdoc/>
public override IHttpVirtualPathData GetVirtualPath(HttpRequestMessage request, string name, IDictionary<string, object> values)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
HttpContextBase httpContextBase = request.GetHttpContext();
if (httpContextBase == null)
{
httpContextBase = new HttpRequestMessageContextWrapper(VirtualPathRoot, request);
}
if (httpContextBase.GetHttpRequestMessage() == null)
{
httpContextBase.SetHttpRequestMessage(request);
}
IHttpRouteData routeData = request.GetRouteData();
if (routeData == null)
{
return null;
}
RequestContext requestContext = new RequestContext(httpContextBase, routeData.ToRouteData());
RouteValueDictionary routeValues = values != null ? new RouteValueDictionary(values) : new RouteValueDictionary();
VirtualPathData virtualPathData = _routeCollection.GetVirtualPath(requestContext, name, routeValues);
if (virtualPathData != null)
{
// If the route is not an HttpWebRoute, try getting a virtual path without the httproute key in the route value dictionary
// This ensures that httproute isn't picked up by non-WebAPI routes that might pollute the virtual path with httproute
if (!(virtualPathData.Route is HttpWebRoute))
{
if (routeValues.Remove(HttpWebRoute.HttpRouteKey))
{
VirtualPathData virtualPathDataWithoutHttpRouteValue = _routeCollection.GetVirtualPath(requestContext, name, routeValues);
if (virtualPathDataWithoutHttpRouteValue != null)
{
virtualPathData = virtualPathDataWithoutHttpRouteValue;
}
}
}
return new HostedHttpVirtualPathData(virtualPathData, routeData.Route);
}
return null;
}
/// <inheritdoc/>
public override IHttpRoute CreateRoute(string uriTemplate, IDictionary<string, object> defaults, IDictionary<string, object> constraints, IDictionary<string, object> dataTokens, HttpMessageHandler handler)
{
return new HostedHttpRoute(uriTemplate, defaults, constraints, dataTokens, handler);
}
/// <inheritdoc/>
public override void Add(string name, IHttpRoute route)
{
_routeCollection.Add(name, route.ToRoute());
}
/// <inheritdoc/>
public override void Clear()
{
_routeCollection.Clear();
}
/// <inheritdoc/>
public override bool Contains(IHttpRoute item)
{
foreach (RouteBase route in _routeCollection)
{
HttpWebRoute webRoute = route as HttpWebRoute;
if (webRoute != null && webRoute.HttpRoute == item)
{
return true;
}
}
return false;
}
/// <inheritdoc/>
public override bool ContainsKey(string name)
{
return _routeCollection[name] != null;
}
/// <inheritdoc/>
public override void CopyTo(IHttpRoute[] array, int arrayIndex)
{
throw NotSupportedByHostedRouteCollection();
}
/// <inheritdoc/>
public override void CopyTo(KeyValuePair<string, IHttpRoute>[] array, int arrayIndex)
{
throw NotSupportedByRouteCollection();
}
/// <inheritdoc/>
public override void Insert(int index, string name, IHttpRoute value)
{
throw NotSupportedByRouteCollection();
}
/// <inheritdoc/>
public override bool Remove(string name)
{
throw NotSupportedByRouteCollection();
}
/// <inheritdoc/>
public override IEnumerator<IHttpRoute> GetEnumerator()
{
// Here we only care about Web API routes.
return _routeCollection
.OfType<HttpWebRoute>()
.Select(httpWebRoute => httpWebRoute.HttpRoute)
.GetEnumerator();
}
/// <inheritdoc/>
public override bool TryGetValue(string name, out IHttpRoute route)
{
HttpWebRoute rt = _routeCollection[name] as HttpWebRoute;
if (rt != null)
{
route = rt.HttpRoute;
return true;
}
route = null;
return false;
}
private static NotSupportedException NotSupportedByRouteCollection()
{
return Error.NotSupported(SRResources.RouteCollectionNotSupported, typeof(HostedHttpRouteCollection).Name);
}
private static NotSupportedException NotSupportedByHostedRouteCollection()
{
return Error.NotSupported(SRResources.RouteCollectionUseDirectly, typeof(RouteCollection).Name);
}
}
}
| 32.743902 | 213 | 0.565736 | [
"Apache-2.0"
] | Icenium/aspnetwebstack | src/System.Web.Http.WebHost/Routing/HostedHttpRouteCollection.cs | 8,057 | C# |
using System.Collections.Generic;
using System.Linq;
using RepairR.Core.ProjectAggregate;
using RepairR.Core.ProjectAggregate.Specifications;
using Xunit;
namespace RepairR.UnitTests.Core.Specifications
{
public class IncompleteItemsSpecificationConstructor
{
[Fact]
public void FilterCollectionToOnlyReturnItemsWithIsDoneFalse()
{
var item1 = new ToDoItem();
var item2 = new ToDoItem();
var item3 = new ToDoItem();
item3.MarkComplete();
var items = new List<ToDoItem>() { item1, item2, item3 };
var spec = new IncompleteItemsSpec();
List<ToDoItem> filteredList = items
.Where(spec.WhereExpressions.First().Compile())
.ToList();
Assert.Contains(item1, filteredList);
Assert.Contains(item2, filteredList);
Assert.DoesNotContain(item3, filteredList);
}
}
}
| 29.875 | 70 | 0.626569 | [
"MIT"
] | AAimson/RepairR | tests/RepairR.UnitTests/Core/Specifications/IncompleteItemSpecificationsConstructor.cs | 958 | C# |
/*``The contents of this file are subject to the Erlang Public License,
* Version 1.1, (the "License"); you may not use this file except in
* compliance with the License. You should have received a copy of the
* Erlang Public License along with this software. If not, it can be
* retrieved via the world wide web at http://www.erlang.org/.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific language governing rights and limitations
* under the License.
*
* The Initial Developer of the Original Code is Ericsson Utvecklings AB.
* Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
* AB. All Rights Reserved.''
*
* Converted from Java to C# by Vlad Dumitrescu (vlad_Dumitrescu@hotmail.com)
*/
namespace Otp.Erlang
{
using System;
/*
* Provides a C# representation of Erlang floats and doubles. Erlang
* defines only one floating point numeric type, however this class
* and its subclass {@link Float} are used to provide
* representations corresponding to the C# types Double and Float.
**/
[Serializable]
public class Double:Erlang.Object
{
private double d;
/*
* Create an Erlang float from the given double value.
**/
public Double(double d)
{
this.d = d;
}
/*
* Create an Erlang float from a stream containing a double encoded
* in Erlang external format.
*
* @param buf the stream containing the encoded value.
*
* @exception DecodeException if the buffer does not
* contain a valid external representation of an Erlang float.
**/
public Double(OtpInputStream buf)
{
this.d = buf.read_double();
//System.Diagnostics.Debug.WriteLine("Double: " + this.d );
}
/*
* Get the value, as a double.
*
* @return the value of this object, as a double.
**/
public virtual double doubleValue()
{
return d;
}
/*
* Get the value, as a float.
*
* @return the value of this object, as a float.
*
* @exception RangeException if the value cannot be
* represented as a float.
**/
public virtual float floatValue()
{
float f = (float) d;
if (f != d)
{
throw new RangeException("Value too large for float: " + d);
}
return f;
}
/*
* Get the string representation of this double.
*
* @return the string representation of this double.
**/
public override System.String ToString()
{
return d.ToString();
}
/*
* Convert this double to the equivalent Erlang external representation.
*
* @param buf an output stream to which the encoded value should be
* written.
**/
public override void encode(OtpOutputStream buf)
{
buf.write_double(this.d);
}
/*
* Determine if two floats are equal. Floats are equal if they
* contain the same value.
*
* @param o the float to compare to.
*
* @return true if the floats have the same value.
**/
public override bool Equals(System.Object o)
{
if (!(o is Double))
return false;
Double d = (Double) o;
return this.d == d.d;
}
public override int GetHashCode()
{
return 1;
}
}
} | 24.676923 | 77 | 0.669576 | [
"MIT"
] | spoconnor/ElixirMessagingServer | DotNet/OTP.NET-2010/Otp/Erlang/Double.cs | 3,208 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the backup-2018-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Backup.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Backup.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListReportPlans operation
/// </summary>
public class ListReportPlansResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
ListReportPlansResponse response = new ListReportPlansResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("NextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ReportPlans", targetDepth))
{
var unmarshaller = new ListUnmarshaller<ReportPlan, ReportPlanUnmarshaller>(ReportPlanUnmarshaller.Instance);
response.ReportPlans = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValueException"))
{
return InvalidParameterValueExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException"))
{
return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonBackupException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static ListReportPlansResponseUnmarshaller _instance = new ListReportPlansResponseUnmarshaller();
internal static ListReportPlansResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListReportPlansResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 38.6 | 189 | 0.642919 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/Backup/Generated/Model/Internal/MarshallTransformations/ListReportPlansResponseUnmarshaller.cs | 4,632 | C# |
using System;
namespace q1
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 2;
int z = 3;
int j = 9;
int k = 6;
int area = x * x;
int a = (x * x) + (3 * x) - 4;
int b = (x + y) * z;
var c = (x + (3 * y)) / ((2 * x) - y);
var d = 1 / ((x * x) + x + 3);
var e = (x + y) / 7;
int f = 2 * b * c * 3;
var g = (3 * y) / (5 - z);
var h = area * (Math.Sqrt(area));
var i = ((x + 32) / (y - 32)) - (x - (2 - y));
var res = ((3 * i * j * k) + (k ^ 9)) / ((7 * i * k) - (5 * Math.Sqrt(j) + k));
Console.WriteLine("Problem A is: " + a);
Console.WriteLine("Problem B is: " + b);
Console.WriteLine("Problem C is: " + c);
Console.WriteLine("Problem E is: " + e);
Console.WriteLine("Problem F is: " + f);
Console.WriteLine("Problem G is: " + g);
Console.WriteLine("Problem H is: " + h);
Console.WriteLine("Problem I is: " + i);
Console.WriteLine("Problem j is: " + res);
}
}
}
| 33.972973 | 92 | 0.361177 | [
"MIT"
] | fatimabashir658/csharp | question 50/Program.cs | 1,259 | C# |
// Copyright (c) MudBlazor 2021
// MudBlazor licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using MudBlazor.Services;
using MudBlazor.Utilities;
using MudBlazor.Utilities.Exceptions;
namespace MudBlazor
{
public partial class MudSelect<T> : MudBaseInput<T>, IMudSelect, IMudShadowSelect
{
private HashSet<T> _selectedValues = new HashSet<T>();
private IEqualityComparer<T> _comparer;
private bool _dense;
private string multiSelectionText;
private bool? _selectAllChecked;
protected string Classname =>
new CssBuilder("mud-select")
.AddClass(Class)
.Build();
[Inject] private IKeyInterceptor _keyInterceptor { get; set; }
[Inject] IScrollManager ScrollManager { get; set; }
private string _elementId = "select_" + Guid.NewGuid().ToString().Substring(0, 8);
private Task SelectNextItem() => SelectAdjacentItem(+1);
private Task SelectPreviousItem() => SelectAdjacentItem(-1);
private async Task SelectAdjacentItem(int direction)
{
if (_items == null || _items.Count == 0)
return;
var index = _items.FindIndex(x => x.ItemId == (string)_activeItemId);
if (direction < 0 && index < 0)
index = 0;
MudSelectItem<T> item = null;
// the loop allows us to jump over disabled items until we reach the next non-disabled one
for (int i = 0; i < _items.Count; i++)
{
index += direction;
if (index < 0)
index = 0;
if (index >= _items.Count)
index = _items.Count - 1;
if (_items[index].Disabled)
continue;
item = _items[index];
if (!MultiSelection)
{
_selectedValues.Clear();
_selectedValues.Add(item.Value);
await SetValueAsync(item.Value, updateText: true);
HilightItem(item);
break;
}
else
{
// in multiselect mode don't select anything, just hilight.
// selecting is done by Enter
HilightItem(item);
break;
}
}
await _elementReference.SetText(Text);
if (item != null)
await ScrollManager.ScrollToListItemAsync(item.ItemId, direction, true);
}
private async Task SelectFirstItem(string startChar = null)
{
if (_items == null || _items.Count == 0)
return;
var items = _items.Where(x => !x.Disabled);
if (!string.IsNullOrWhiteSpace(startChar))
{
// find first item that starts with the letter
var currentItem = items.FirstOrDefault(x => x.ItemId == (string)_activeItemId);
if (currentItem != null &&
Converter.Set(currentItem.Value)?.ToLowerInvariant().StartsWith(startChar) == true)
{
// this will step through all items that start with the same letter if pressed multiple times
items = items.SkipWhile(x => x != currentItem).Skip(1);
}
items = items.Where(x => Converter.Set(x.Value)?.ToLowerInvariant().StartsWith(startChar) == true);
}
var item = items.FirstOrDefault();
if (item == null)
return;
if (!MultiSelection)
{
_selectedValues.Clear();
_selectedValues.Add(item.Value);
await SetValueAsync(item.Value, updateText: true);
HilightItem(item);
}
else
{
HilightItem(item);
}
await _elementReference.SetText(Text);
await ScrollManager.ScrollToListItemAsync(item.ItemId, -1, true);
}
private async Task SelectLastItem()
{
if (_items == null || _items.Count == 0)
return;
var item = _items.LastOrDefault(x => !x.Disabled);
if (item == null)
return;
if (!MultiSelection)
{
_selectedValues.Clear();
_selectedValues.Add(item.Value);
await SetValueAsync(item.Value, updateText: true);
HilightItem(item);
}
else
{
HilightItem(item);
}
await _elementReference.SetText(Text);
await ScrollManager.ScrollToListItemAsync(item.ItemId, 1, true);
}
/// <summary>
/// Add the MudSelectItems here
/// </summary>
[Parameter] public RenderFragment ChildContent { get; set; }
/// <summary>
/// User class names for the popover, separated by space
/// </summary>
[Parameter] public string PopoverClass { get; set; }
/// <summary>
/// If true, compact vertical padding will be applied to all Select items.
/// </summary>
[Parameter]
public bool Dense
{
get { return _dense; }
set { _dense = value; }
}
/// <summary>
/// The Open Select Icon
/// </summary>
[Parameter] public string OpenIcon { get; set; } = Icons.Material.Filled.ArrowDropDown;
/// <summary>
/// The Close Select Icon
/// </summary>
[Parameter] public string CloseIcon { get; set; } = Icons.Material.Filled.ArrowDropUp;
/// <summary>
/// If set to true and the MultiSelection option is set to true, a "select all" checkbox is added at the top of the list of items.
/// </summary>
[Parameter] public bool SelectAll { get; set; }
/// <summary>
/// Define the text of the Select All option.
/// </summary>
[Parameter] public string SelectAllText { get; set; } = "Select all";
/// <summary>
/// Fires when SelectedValues changes.
/// </summary>
[Parameter] public EventCallback<IEnumerable<T>> SelectedValuesChanged { get; set; }
/// <summary>
/// Function to define a customized multiselection text.
/// </summary>
[Parameter] public Func<List<string>, string> MultiSelectionTextFunc { get; set; }
/// <summary>
/// Parameter to define the delimited string separator.
/// </summary>
[Parameter] public string Delimiter { get; set; } = ", ";
/// <summary>
/// Set of selected values. If MultiSelection is false it will only ever contain a single value. This property is two-way bindable.
/// </summary>
[Parameter]
public IEnumerable<T> SelectedValues
{
get
{
if (_selectedValues == null)
_selectedValues = new HashSet<T>(_comparer);
return _selectedValues;
}
set
{
var set = value ?? new HashSet<T>(_comparer);
if (SelectedValues.Count() == set.Count() && _selectedValues.All(x => set.Contains(x)))
return;
_selectedValues = new HashSet<T>(set, _comparer);
SelectionChangedFromOutside?.Invoke(_selectedValues);
if (!MultiSelection)
SetValueAsync(_selectedValues.FirstOrDefault()).AndForget();
else
{
//Warning. Here the Converter was not set yet
if (MultiSelectionTextFunc != null)
{
SetCustomizedTextAsync(string.Join(Delimiter, SelectedValues.Select(x => Converter.Set(x))),
selectedConvertedValues: SelectedValues.Select(x => Converter.Set(x)).ToList(),
multiSelectionTextFunc: MultiSelectionTextFunc).AndForget();
}
else
{
SetTextAsync(string.Join(Delimiter, SelectedValues.Select(x => Converter.Set(x))), updateValue: false).AndForget();
}
}
SelectedValuesChanged.InvokeAsync(new HashSet<T>(SelectedValues, _comparer));
if (MultiSelection && typeof(T) == typeof(string))
SetValueAsync((T)(object)Text, updateText: false).AndForget();
}
}
/// <summary>
/// The Comparer to use for comparing selected values internally.
/// </summary>
[Parameter]
public IEqualityComparer<T> Comparer
{
get => _comparer;
set
{
_comparer = value;
// Apply comparer and refresh selected values
_selectedValues = new HashSet<T>(_selectedValues, _comparer);
SelectedValues = _selectedValues;
}
}
private Func<T, string> _toStringFunc = x => x?.ToString();
private MudInput<string> _elementReference;
/// <summary>
/// Defines how values are displayed in the drop-down list
/// </summary>
[Parameter]
public Func<T, string> ToStringFunc
{
get => _toStringFunc;
set
{
if (_toStringFunc == value)
return;
_toStringFunc = value;
Converter = new Converter<T>
{
SetFunc = _toStringFunc ?? (x => x?.ToString()),
//GetFunc = LookupValue,
};
}
}
public MudSelect()
{
Adornment = Adornment.End;
IconSize = Size.Medium;
}
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
if (firstRender && Value != null)
{
// we need to render the initial Value which is not possible without the items
// which supply the RenderFragment. So in this case, a second render is necessary
StateHasChanged();
}
UpdateSelectAllChecked();
lock (this)
{
if (_renderComplete != null)
{
_renderComplete.TrySetResult();
_renderComplete = null;
}
}
}
private Task WaitForRender()
{
Task t = null;
lock (this)
{
if (_renderComplete != null)
return _renderComplete.Task;
_renderComplete = new TaskCompletionSource();
t = _renderComplete.Task;
}
StateHasChanged();
return t;
}
private TaskCompletionSource _renderComplete;
/// <summary>
/// Returns whether or not the Value can be found in items. If not, the Select will display it as a string.
/// </summary>
protected bool CanRenderValue
{
get
{
if (Value == null)
return false;
if (!_shadowLookup.TryGetValue(Value, out var item))
return false;
return (item.ChildContent != null);
}
}
protected bool IsValueInList
{
get
{
if (Value == null)
return false;
return _shadowLookup.TryGetValue(Value, out var _);
}
}
protected RenderFragment GetSelectedValuePresenter()
{
if (Value == null)
return null;
if (!_shadowLookup.TryGetValue(Value, out var item))
return null; //<-- for now. we'll add a custom template to present values (set from outside) which are not on the list?
return item.ChildContent;
}
protected override Task UpdateValuePropertyAsync(bool updateText)
{
// For MultiSelection of non-string T's we don't update the Value!!!
if (typeof(T) == typeof(string) || !MultiSelection)
base.UpdateValuePropertyAsync(updateText);
return Task.CompletedTask;
}
protected override Task UpdateTextPropertyAsync(bool updateValue)
{
// when multiselection is true, we return
// a comma separated list of selected values
if (MultiSelectionTextFunc != null)
{
return MultiSelection
? SetCustomizedTextAsync(string.Join(Delimiter, SelectedValues.Select(x => Converter.Set(x))),
selectedConvertedValues: SelectedValues.Select(x => Converter.Set(x)).ToList(),
multiSelectionTextFunc: MultiSelectionTextFunc)
: base.UpdateTextPropertyAsync(updateValue);
}
else
{
return MultiSelection
? SetTextAsync(string.Join(Delimiter, SelectedValues.Select(x => Converter.Set(x))))
: base.UpdateTextPropertyAsync(updateValue);
}
}
internal event Action<ICollection<T>> SelectionChangedFromOutside;
/// <summary>
/// If true, multiple values can be selected via checkboxes which are automatically shown in the dropdown
/// </summary>
[Parameter] public bool MultiSelection { get; set; }
protected internal List<MudSelectItem<T>> _items = new();
protected Dictionary<T, MudSelectItem<T>> _valueLookup = new();
protected Dictionary<T, MudSelectItem<T>> _shadowLookup = new();
// note: this must be object to satisfy MudList
private object _activeItemId = null;
internal bool Add(MudSelectItem<T> item)
{
if (item == null)
return false;
bool? result = null;
if (!_items.Select(x => x.Value).Contains(item.Value))
{
_items.Add(item);
if (item.Value != null)
{
_valueLookup[item.Value] = item;
if (item.Value.Equals(Value) && !MultiSelection)
result = true;
}
}
UpdateSelectAllChecked();
if (result.HasValue == false)
{
result = item.Value?.Equals(Value);
}
return result == true;
}
internal void Remove(MudSelectItem<T> item)
{
_items.Remove(item);
if (item.Value != null)
_valueLookup.Remove(item.Value);
}
/// <summary>
/// Sets the maxheight the Select can have when open.
/// </summary>
[Parameter] public int MaxHeight { get; set; } = 300;
/// <summary>
/// Set the anchor origin point to determen where the popover will open from.
/// </summary>
[Parameter] public Origin AnchorOrigin { get; set; } = Origin.TopCenter;
/// <summary>
/// Sets the transform origin point for the popover.
/// </summary>
[Parameter] public Origin TransformOrigin { get; set; } = Origin.TopCenter;
/// <summary>
/// Sets the direction the Select menu should open.
/// </summary>
[ExcludeFromCodeCoverage]
[Obsolete("Use AnchorOrigin or TransformOrigin instead.", true)]
[Parameter] public Direction Direction { get; set; } = Direction.Bottom;
/// <summary>
/// If true, the Select menu will open either before or after the input (left/right).
/// </summary>
[ExcludeFromCodeCoverage]
[Obsolete("Use AnchorOrigin or TransformOrigin instead.", true)]
[Parameter] public bool OffsetX { get; set; }
/// <summary>
/// If true, the Select menu will open either before or after the input (top/bottom).
/// </summary>
/// [ExcludeFromCodeCoverage]
[Obsolete("Use AnchorOrigin or TransformOrigin instead.", true)]
[Parameter] public bool OffsetY { get; set; }
/// <summary>
/// If true, the Select's input will not show any values that are not defined in the dropdown.
/// This can be useful if Value is bound to a variable which is initialized to a value which is not in the list
/// and you want the Select to show the label / placeholder instead.
/// </summary>
[Parameter] public bool Strict { get; set; }
/// <summary>
/// Show clear button.
/// </summary>
[Parameter] public bool Clearable { get; set; } = false;
/// <summary>
/// If true, prevent scrolling while dropdown is open.
/// </summary>
[Parameter] public bool LockScroll { get; set; } = false;
/// <summary>
/// Button click event for clear button. Called after text and value has been cleared.
/// </summary>
[Parameter] public EventCallback<MouseEventArgs> OnClearButtonClick { get; set; }
internal bool _isOpen;
public string _currentIcon { get; set; }
public async Task SelectOption(int index)
{
if (index < 0 || index >= _items.Count)
{
if (!MultiSelection)
await CloseMenu();
return;
}
await SelectOption(_items[index].Value);
}
public async Task SelectOption(object obj)
{
var value = (T)obj;
if (MultiSelection)
{
// multi-selection: menu stays open
if (!_selectedValues.Contains(value))
_selectedValues.Add(value);
else
_selectedValues.Remove(value);
if (MultiSelectionTextFunc != null)
{
await SetCustomizedTextAsync(string.Join(Delimiter, SelectedValues.Select(x => Converter.Set(x))),
selectedConvertedValues: SelectedValues.Select(x => Converter.Set(x)).ToList(),
multiSelectionTextFunc: MultiSelectionTextFunc);
}
else
{
await SetTextAsync(string.Join(Delimiter, SelectedValues.Select(x => Converter.Set(x))), updateValue: false);
}
UpdateSelectAllChecked();
BeginValidate();
}
else
{
// single selection
_isOpen = false;
UpdateIcon();
if (EqualityComparer<T>.Default.Equals(Value, value))
{
StateHasChanged();
return;
}
await SetValueAsync(value);
_elementReference.SetText(Text).AndForget();
_selectedValues.Clear();
_selectedValues.Add(value);
HilightItemForValue(value);
}
await SelectedValuesChanged.InvokeAsync(SelectedValues);
if (MultiSelection && typeof(T) == typeof(string))
await SetValueAsync((T)(object)Text, updateText: false);
StateHasChanged();
}
private async void HilightItemForValue(T value)
{
if (value == null)
{
HilightItem(null);
return;
}
await WaitForRender();
_valueLookup.TryGetValue(value, out var item);
HilightItem(item);
}
private async void HilightItem(MudSelectItem<T> item)
{
_activeItemId = item?.ItemId;
// we need to make sure we are just after a render here or else there will be race conditions
await WaitForRender();
// Note: this is a hack but I found no other way to make the list hilight the currently hilighted item
// without the delay it always shows the previously hilighted item because the popup items don't exist yet
// they are only registered after they are rendered, so we need to render again!
await Task.Delay(1);
StateHasChanged();
}
private async Task HilightSelectedValue()
{
await WaitForRender();
if (MultiSelection)
HilightItem(_items.FirstOrDefault(x => !x.Disabled));
else
HilightItemForValue(Value);
}
private void UpdateSelectAllChecked()
{
if (MultiSelection && SelectAll)
{
var oldState = _selectAllChecked;
if (_selectedValues.Count == 0)
{
_selectAllChecked = false;
}
else if (_items.Count == _selectedValues.Count)
{
_selectAllChecked = true;
}
else
{
_selectAllChecked = null;
}
}
}
public async Task ToggleMenu()
{
if (Disabled || ReadOnly)
return;
if (_isOpen)
await CloseMenu(true);
else
await OpenMenu();
}
public async Task OpenMenu()
{
if (Disabled || ReadOnly)
return;
_isOpen = true;
UpdateIcon();
StateHasChanged();
await HilightSelectedValue();
//disable escape propagation: if selectmenu is open, only the select popover should close and underlying components should not handle escape key
await _keyInterceptor.UpdateKey(new() { Key = "Escape", StopDown = "Key+none" });
}
public async Task CloseMenu(bool focusAgain = true)
{
_isOpen = false;
UpdateIcon();
if (focusAgain == true)
{
StateHasChanged();
await OnBlur.InvokeAsync(new FocusEventArgs());
_elementReference.FocusAsync().AndForget(TaskOption.Safe);
StateHasChanged();
}
//enable escape propagation: the select popover was closed, now underlying components are allowed to handle escape key
await _keyInterceptor.UpdateKey(new() { Key = "Escape", StopDown = "none" });
}
private void UpdateIcon()
{
_currentIcon = !string.IsNullOrWhiteSpace(AdornmentIcon) ? AdornmentIcon : _isOpen ? CloseIcon : OpenIcon;
}
protected override void OnInitialized()
{
base.OnInitialized();
UpdateIcon();
}
protected override void OnParametersSet()
{
base.OnParametersSet();
UpdateIcon();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await _keyInterceptor.Connect(_elementId, new KeyInterceptorOptions()
{
//EnableLogging = true,
TargetClass = "mud-input-control",
Keys = {
new KeyOptions { Key=" ", PreventDown = "key+none" }, //prevent scrolling page, toggle open/close
new KeyOptions { Key="ArrowUp", PreventDown = "key+none" }, // prevent scrolling page, instead hilight previous item
new KeyOptions { Key="ArrowDown", PreventDown = "key+none" }, // prevent scrolling page, instead hilight next item
new KeyOptions { Key="Home", PreventDown = "key+none" },
new KeyOptions { Key="End", PreventDown = "key+none" },
new KeyOptions { Key="Escape" },
new KeyOptions { Key="Enter", PreventDown = "key+none" },
new KeyOptions { Key="NumpadEnter", PreventDown = "key+none" },
new KeyOptions { Key="a", PreventDown = "key+ctrl" }, // select all items instead of all page text
new KeyOptions { Key="A", PreventDown = "key+ctrl" }, // select all items instead of all page text
new KeyOptions { Key="/./", SubscribeDown = true, SubscribeUp = true }, // for our users
},
});
_keyInterceptor.KeyDown += HandleKeyDown;
_keyInterceptor.KeyUp += HandleKeyUp;
}
await base.OnAfterRenderAsync(firstRender);
}
public void CheckGenericTypeMatch(object select_item)
{
var itemT = select_item.GetType().GenericTypeArguments[0];
if (itemT != typeof(T))
throw new GenericTypeMismatchException("MudSelect", "MudSelectItem", typeof(T), itemT);
}
public override ValueTask FocusAsync()
{
return _elementReference.FocusAsync();
}
public override ValueTask SelectAsync()
{
return _elementReference.SelectAsync();
}
public override ValueTask SelectRangeAsync(int pos1, int pos2)
{
return _elementReference.SelectRangeAsync(pos1, pos2);
}
/// <summary>
/// Extra handler for clearing selection.
/// </summary>
protected async ValueTask SelectClearButtonClickHandlerAsync(MouseEventArgs e)
{
await SetValueAsync(default, false);
await SetTextAsync(default, false);
_selectedValues.Clear();
BeginValidate();
StateHasChanged();
await SelectedValuesChanged.InvokeAsync(_selectedValues);
await OnClearButtonClick.InvokeAsync(e);
}
protected async Task SetCustomizedTextAsync(string text, bool updateValue = true,
List<string> selectedConvertedValues = null,
Func<List<string>, string> multiSelectionTextFunc = null)
{
// The Text property of the control is updated
Text = multiSelectionTextFunc?.Invoke(selectedConvertedValues);
// The comparison is made on the multiSelectionText variable
if (multiSelectionText != text)
{
multiSelectionText = text;
if (!string.IsNullOrWhiteSpace(multiSelectionText))
Touched = true;
if (updateValue)
await UpdateValuePropertyAsync(false);
await TextChanged.InvokeAsync(multiSelectionText);
}
}
/// <summary>
/// Custom checked icon.
/// </summary>
[Parameter] public string CheckedIcon { get; set; } = Icons.Material.Filled.CheckBox;
/// <summary>
/// Custom unchecked icon.
/// </summary>
[Parameter] public string UncheckedIcon { get; set; } = Icons.Material.Filled.CheckBoxOutlineBlank;
/// <summary>
/// Custom indeterminate icon.
/// </summary>
[Parameter] public string IndeterminateIcon { get; set; } = Icons.Material.Filled.IndeterminateCheckBox;
/// <summary>
/// The checkbox icon reflects the select all option's state
/// </summary>
protected string SelectAllCheckBoxIcon
{
get
{
return _selectAllChecked.HasValue ? _selectAllChecked.Value ? CheckedIcon : UncheckedIcon : IndeterminateIcon;
}
}
internal async void HandleKeyDown(KeyboardEventArgs obj)
{
if (Disabled || ReadOnly)
return;
var key = obj.Key.ToLowerInvariant();
if (_isOpen && key.Length == 1 && key != " " && !(obj.CtrlKey || obj.ShiftKey || obj.AltKey || obj.MetaKey))
{
await SelectFirstItem(key);
return;
}
switch (obj.Key)
{
case "Tab":
await CloseMenu(false);
break;
case "ArrowUp":
if (obj.AltKey == true)
{
await CloseMenu();
break;
}
else if (_isOpen == false)
{
await OpenMenu();
break;
}
else
{
await SelectPreviousItem();
break;
}
case "ArrowDown":
if (obj.AltKey == true)
{
await OpenMenu();
break;
}
else if (_isOpen == false)
{
await OpenMenu();
break;
}
else
{
await SelectNextItem();
break;
}
case " ":
await ToggleMenu();
break;
case "Escape":
await CloseMenu(true);
break;
case "Home":
await SelectFirstItem();
break;
case "End":
await SelectLastItem();
break;
case "Enter":
case "NumpadEnter":
var index = _items.FindIndex(x => x.ItemId == (string)_activeItemId);
if (!MultiSelection)
{
if (!_isOpen)
{
await OpenMenu();
return;
}
// this also closes the menu
await SelectOption(index);
break;
}
else
{
if (_isOpen == false)
{
await OpenMenu();
break;
}
else
{
await SelectOption(index);
await _elementReference.SetText(Text);
break;
}
}
case "a":
case "A":
if (obj.CtrlKey == true)
{
if (MultiSelection)
{
await SelectAllClickAsync();
//If we didn't add delay, it won't work.
await WaitForRender();
await Task.Delay(1);
StateHasChanged();
//It only works when selecting all, not render unselect all.
//UpdateSelectAllChecked();
}
}
break;
}
OnKeyDown.InvokeAsync(obj).AndForget();
}
internal void HandleKeyUp(KeyboardEventArgs obj)
{
OnKeyUp.InvokeAsync(obj).AndForget();
}
[ExcludeFromCodeCoverage]
[Obsolete("Use Clear instead.", true)]
public Task ClearAsync() => Clear();
/// <summary>
/// Clear the selection
/// </summary>
public async Task Clear()
{
await SetValueAsync(default, false);
await SetTextAsync(default, false);
_selectedValues.Clear();
BeginValidate();
StateHasChanged();
await SelectedValuesChanged.InvokeAsync(_selectedValues);
}
private async Task SelectAllClickAsync()
{
// Manage the fake tri-state of a checkbox
if (!_selectAllChecked.HasValue)
_selectAllChecked = true;
else if (_selectAllChecked.Value)
_selectAllChecked = false;
else
_selectAllChecked = true;
// Define the items selection
if (_selectAllChecked.Value == true)
await SelectAllItems();
else
await Clear();
}
private async Task SelectAllItems()
{
if (!MultiSelection)
return;
var selectedValues = new HashSet<T>(_items.Where(x => !x.Disabled && x.Value != null).Select(x => x.Value), _comparer);
_selectedValues = new HashSet<T>(selectedValues, _comparer);
if (MultiSelectionTextFunc != null)
{
await SetCustomizedTextAsync(string.Join(Delimiter, SelectedValues.Select(x => Converter.Set(x))),
selectedConvertedValues: SelectedValues.Select(x => Converter.Set(x)).ToList(),
multiSelectionTextFunc: MultiSelectionTextFunc);
}
else
{
await SetTextAsync(string.Join(Delimiter, SelectedValues.Select(x => Converter.Set(x))), updateValue: false);
}
UpdateSelectAllChecked();
_selectedValues = selectedValues; // need to force selected values because Blazor overwrites it under certain circumstances due to changes of Text or Value
BeginValidate();
await SelectedValuesChanged.InvokeAsync(SelectedValues);
if (MultiSelection && typeof(T) == typeof(string))
SetValueAsync((T)(object)Text, updateText: false).AndForget();
}
public void RegisterShadowItem(MudSelectItem<T> item)
{
if (item == null || item.Value == null)
return;
_shadowLookup[item.Value] = item;
}
public void UnregisterShadowItem(MudSelectItem<T> item)
{
if (item == null || item.Value == null)
return;
_shadowLookup.Remove(item.Value);
}
private void OnLostFocus(FocusEventArgs obj)
{
if (_isOpen)
{
// when the menu is open we immediately get back the focus if we lose it (i.e. because of checkboxes in multi-select)
// otherwise we can't receive key strokes any longer
_elementReference.FocusAsync().AndForget(TaskOption.Safe);
}
}
}
}
| 36.846875 | 167 | 0.50776 | [
"MIT"
] | A6blpka/MudBlazor | src/MudBlazor/Components/Select/MudSelect.razor.cs | 35,375 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Internal.Metadata.NativeFormat.Writer;
using Cts = Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.Metadata
{
partial class Transform<TPolicy>
{
private Dictionary<NamespaceKey, NamespaceDefinition> _namespaceDefs = new Dictionary<NamespaceKey, NamespaceDefinition>();
private NamespaceDefinition HandleNamespaceDefinition(Cts.ModuleDesc parentScope, string namespaceString)
{
Debug.Assert(namespaceString != null);
NamespaceDefinition result;
NamespaceKey key = new NamespaceKey(parentScope, namespaceString);
if (_namespaceDefs.TryGetValue(key, out result))
{
return result;
}
if (namespaceString.Length == 0)
{
var rootNamespace = new NamespaceDefinition
{
Name = null,
};
_namespaceDefs.Add(key, rootNamespace);
ScopeDefinition rootScope = HandleScopeDefinition(parentScope);
rootScope.RootNamespaceDefinition = rootNamespace;
rootNamespace.ParentScopeOrNamespace = rootScope;
return rootNamespace;
}
string currentNamespaceName = String.Empty;
NamespaceDefinition currentNamespace = HandleNamespaceDefinition(parentScope, currentNamespaceName);
foreach (var segment in namespaceString.Split('.'))
{
string nextNamespaceName = currentNamespaceName;
if (nextNamespaceName.Length > 0)
nextNamespaceName = nextNamespaceName + '.';
nextNamespaceName += segment;
NamespaceDefinition nextNamespace;
key = new NamespaceKey(parentScope, nextNamespaceName);
if (!_namespaceDefs.TryGetValue(key, out nextNamespace))
{
nextNamespace = new NamespaceDefinition
{
Name = HandleString(segment.Length == 0 ? null : segment),
ParentScopeOrNamespace = currentNamespace
};
_namespaceDefs.Add(key, nextNamespace);
currentNamespace.NamespaceDefinitions.Add(nextNamespace);
}
currentNamespace = nextNamespace;
currentNamespaceName = nextNamespaceName;
}
return currentNamespace;
}
private Dictionary<NamespaceKey, NamespaceReference> _namespaceRefs = new Dictionary<NamespaceKey, NamespaceReference>();
private NamespaceReference HandleNamespaceReference(Cts.ModuleDesc parentScope, string namespaceString)
{
NamespaceReference result;
NamespaceKey key = new NamespaceKey(parentScope, namespaceString);
if (_namespaceRefs.TryGetValue(key, out result))
{
return result;
}
ScopeReference scope = HandleScopeReference(parentScope);
NamespaceReference rootNamespace;
key = new NamespaceKey(parentScope, null);
if (!_namespaceRefs.TryGetValue(key, out rootNamespace))
{
rootNamespace = new NamespaceReference
{
Name = null,
ParentScopeOrNamespace = scope,
};
_namespaceRefs.Add(key, rootNamespace);
}
NamespaceReference currentNamespace = rootNamespace;
string currentNamespaceName = String.Empty;
foreach (var segment in namespaceString.Split('.'))
{
string nextNamespaceName = currentNamespaceName;
if (nextNamespaceName.Length > 0)
nextNamespaceName = nextNamespaceName + '.';
nextNamespaceName += segment;
NamespaceReference nextNamespace;
key = new NamespaceKey(parentScope, nextNamespaceName);
if (!_namespaceRefs.TryGetValue(key, out nextNamespace))
{
nextNamespace = new NamespaceReference
{
Name = HandleString(segment.Length == 0 ? null : segment),
ParentScopeOrNamespace = currentNamespace
};
_namespaceRefs.Add(key, nextNamespace);
}
currentNamespace = nextNamespace;
currentNamespaceName = nextNamespaceName;
}
return currentNamespace;
}
}
internal struct NamespaceKey : IEquatable<NamespaceKey>
{
public readonly Cts.ModuleDesc Module;
public readonly string Namespace;
public NamespaceKey(Cts.ModuleDesc module, string namespaceName)
{
Module = module;
Namespace = namespaceName;
}
public bool Equals(NamespaceKey other)
{
return Module == other.Module && Namespace == other.Namespace;
}
public override bool Equals(object obj)
{
if (obj is NamespaceKey)
return Equals((NamespaceKey)obj);
return false;
}
public override int GetHashCode()
{
return Namespace != null ? Namespace.GetHashCode() : 0;
}
}
}
| 37.493421 | 131 | 0.582383 | [
"MIT"
] | LaudateCorpus1/corert | src/ILCompiler.MetadataTransform/src/ILCompiler/Metadata/Transform.Namespace.cs | 5,699 | C# |
using System;
using System.Collections.Generic;
namespace RomanToInteger
{
class Program
{
static void Main(string[] args)
{
// Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
// Symbol Value
// I 1
// V 5
// X 10
// L 50
// C 100
// D 500
// M 1000
//Input: s = "III"
//Output: 3
//
//Input: s = "LVIII"
//Output: 58
string s = "LVIII";
int result = 0;
var dic = new Dictionary<char, int>
{
{'I',1 },{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000} //VI = 6
};
for (int i = 0; i < s.Length; i++)
{
if (i + 1 < s.Length && dic[s[i]] < dic[s[i + 1]])
{
result -= dic[s[i]];
}
else
{
result += dic[s[i]];
}
}
Console.WriteLine(result);
}
}
}
| 25.02 | 97 | 0.310951 | [
"MIT"
] | besirgunduz/AlgorithmCoding | RomanToInteger/Program.cs | 1,253 | C# |
// <auto-generated>
// 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.
// </auto-generated>
namespace Microsoft.Azure.Management.Compute
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for VirtualMachinesOperations.
/// </summary>
public static partial class VirtualMachinesOperationsExtensions
{
/// <summary>
/// Gets all the virtual machines under the specified subscription for the
/// specified location.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// The location for which virtual machines under the subscription are queried.
/// </param>
public static IPage<VirtualMachine> ListByLocation(this IVirtualMachinesOperations operations, string location)
{
return operations.ListByLocationAsync(location).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the virtual machines under the specified subscription for the
/// specified location.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// The location for which virtual machines under the subscription are queried.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListByLocationAsync(this IVirtualMachinesOperations operations, string location, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByLocationWithHttpMessagesAsync(location, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
public static VirtualMachineCaptureResult Capture(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters)
{
return operations.CaptureAsync(resourceGroupName, vmName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachineCaptureResult> CaptureAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CaptureWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to create or update a virtual machine. Please note some
/// properties can be set only during virtual machine creation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
public static VirtualMachine CreateOrUpdate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, vmName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to create or update a virtual machine. Please note some
/// properties can be set only during virtual machine creation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachine> CreateOrUpdateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Virtual Machine operation.
/// </param>
public static VirtualMachine Update(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineUpdate parameters)
{
return operations.UpdateAsync(resourceGroupName, vmName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachine> UpdateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineUpdate parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Delete(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.DeleteAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Retrieves information about the model view or the instance view of a
/// virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='expand'>
/// The expand expression to apply on the operation. Possible values include:
/// 'instanceView'
/// </param>
public static VirtualMachine Get(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, InstanceViewTypes? expand = default(InstanceViewTypes?))
{
return operations.GetAsync(resourceGroupName, vmName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves information about the model view or the instance view of a
/// virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='expand'>
/// The expand expression to apply on the operation. Possible values include:
/// 'instanceView'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachine> GetAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, InstanceViewTypes? expand = default(InstanceViewTypes?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, vmName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieves information about the run-time state of a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static VirtualMachineInstanceView InstanceView(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.InstanceViewAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves information about the run-time state of a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachineInstanceView> InstanceViewAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.InstanceViewWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Converts virtual machine disks from blob-based to managed disks. Virtual
/// machine must be stop-deallocated before invoking this operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void ConvertToManagedDisks(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.ConvertToManagedDisksAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Converts virtual machine disks from blob-based to managed disks. Virtual
/// machine must be stop-deallocated before invoking this operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ConvertToManagedDisksAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.ConvertToManagedDisksWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Shuts down the virtual machine and releases the compute resources. You are
/// not billed for the compute resources that this virtual machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Deallocate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.DeallocateAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Shuts down the virtual machine and releases the compute resources. You are
/// not billed for the compute resources that this virtual machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeallocateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeallocateWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Sets the OS state of the virtual machine to generalized. It is recommended
/// to sysprep the virtual machine before performing this operation.
/// <br>For Windows, please refer to [Create a managed image of a
/// generalized VM in
/// Azure](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/capture-image-resource).<br>For
/// Linux, please refer to [How to create an image of a virtual machine or
/// VHD](https://docs.microsoft.com/en-us/azure/virtual-machines/linux/capture-image).
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Generalize(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.GeneralizeAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Sets the OS state of the virtual machine to generalized. It is recommended
/// to sysprep the virtual machine before performing this operation.
/// <br>For Windows, please refer to [Create a managed image of a
/// generalized VM in
/// Azure](https://docs.microsoft.com/en-us/azure/virtual-machines/windows/capture-image-resource).<br>For
/// Linux, please refer to [How to create an image of a virtual machine or
/// VHD](https://docs.microsoft.com/en-us/azure/virtual-machines/linux/capture-image).
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GeneralizeAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.GeneralizeWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Lists all of the virtual machines in the specified resource group. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<VirtualMachine> List(this IVirtualMachinesOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the virtual machines in the specified resource group. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListAsync(this IVirtualMachinesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the virtual machines in the specified subscription. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='statusOnly'>
/// statusOnly=true enables fetching run time status of all Virtual Machines in
/// the subscription.
/// </param>
public static IPage<VirtualMachine> ListAll(this IVirtualMachinesOperations operations, string statusOnly = default(string))
{
return operations.ListAllAsync(statusOnly).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the virtual machines in the specified subscription. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='statusOnly'>
/// statusOnly=true enables fetching run time status of all Virtual Machines in
/// the subscription.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListAllAsync(this IVirtualMachinesOperations operations, string statusOnly = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(statusOnly, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all available virtual machine sizes to which the specified virtual
/// machine can be resized.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static IEnumerable<VirtualMachineSize> ListAvailableSizes(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.ListAvailableSizesAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all available virtual machine sizes to which the specified virtual
/// machine can be resized.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<VirtualMachineSize>> ListAvailableSizesAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAvailableSizesWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to power off (stop) a virtual machine. The virtual machine
/// can be restarted with the same provisioned resources. You are still charged
/// for this virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='skipShutdown'>
/// The parameter to request non-graceful VM shutdown. True value for this flag
/// indicates non-graceful shutdown whereas false indicates otherwise. Default
/// value for this flag is false if not specified
/// </param>
public static void PowerOff(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, bool? skipShutdown = false)
{
operations.PowerOffAsync(resourceGroupName, vmName, skipShutdown).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to power off (stop) a virtual machine. The virtual machine
/// can be restarted with the same provisioned resources. You are still charged
/// for this virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='skipShutdown'>
/// The parameter to request non-graceful VM shutdown. True value for this flag
/// indicates non-graceful shutdown whereas false indicates otherwise. Default
/// value for this flag is false if not specified
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PowerOffAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, bool? skipShutdown = false, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PowerOffWithHttpMessagesAsync(resourceGroupName, vmName, skipShutdown, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// The operation to reapply a virtual machine's state.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Reapply(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.ReapplyAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to reapply a virtual machine's state.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ReapplyAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.ReapplyWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Restart(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.RestartAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task RestartAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.RestartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Start(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.StartAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task StartAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.StartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Shuts down the virtual machine, moves it to a new node, and powers it back
/// on.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void Redeploy(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.RedeployAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Shuts down the virtual machine, moves it to a new node, and powers it back
/// on.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task RedeployAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.RedeployWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Reimages the virtual machine which has an ephemeral OS disk back to its
/// initial state.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='tempDisk'>
/// Specifies whether to reimage temp disk. Default value: false. Note: This
/// temp disk reimage parameter is only supported for VM/VMSS with Ephemeral OS
/// disk.
/// </param>
public static void Reimage(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, bool? tempDisk = default(bool?))
{
operations.ReimageAsync(resourceGroupName, vmName, tempDisk).GetAwaiter().GetResult();
}
/// <summary>
/// Reimages the virtual machine which has an ephemeral OS disk back to its
/// initial state.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='tempDisk'>
/// Specifies whether to reimage temp disk. Default value: false. Note: This
/// temp disk reimage parameter is only supported for VM/VMSS with Ephemeral OS
/// disk.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ReimageAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, bool? tempDisk = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.ReimageWithHttpMessagesAsync(resourceGroupName, vmName, tempDisk, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// The operation to retrieve SAS URIs for a virtual machine's boot diagnostic
/// logs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='sasUriExpirationTimeInMinutes'>
/// Expiration duration in minutes for the SAS URIs with a value between 1 to
/// 1440 minutes. <br><br>NOTE: If not specified, SAS URIs will be
/// generated with a default expiration duration of 120 minutes.
/// </param>
public static RetrieveBootDiagnosticsDataResult RetrieveBootDiagnosticsData(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, int? sasUriExpirationTimeInMinutes = default(int?))
{
return operations.RetrieveBootDiagnosticsDataAsync(resourceGroupName, vmName, sasUriExpirationTimeInMinutes).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to retrieve SAS URIs for a virtual machine's boot diagnostic
/// logs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='sasUriExpirationTimeInMinutes'>
/// Expiration duration in minutes for the SAS URIs with a value between 1 to
/// 1440 minutes. <br><br>NOTE: If not specified, SAS URIs will be
/// generated with a default expiration duration of 120 minutes.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RetrieveBootDiagnosticsDataResult> RetrieveBootDiagnosticsDataAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, int? sasUriExpirationTimeInMinutes = default(int?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RetrieveBootDiagnosticsDataWithHttpMessagesAsync(resourceGroupName, vmName, sasUriExpirationTimeInMinutes, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to perform maintenance on a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void PerformMaintenance(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.PerformMaintenanceAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to perform maintenance on a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PerformMaintenanceAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.PerformMaintenanceWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// The operation to simulate the eviction of spot virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void SimulateEviction(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.SimulateEvictionAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to simulate the eviction of spot virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task SimulateEvictionAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.SimulateEvictionWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Assess patches on the VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static VirtualMachineAssessPatchesResult AssessPatches(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.AssessPatchesAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Assess patches on the VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachineAssessPatchesResult> AssessPatchesAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.AssessPatchesWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Run command on the VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Run command operation.
/// </param>
public static RunCommandResult RunCommand(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, RunCommandInput parameters)
{
return operations.RunCommandAsync(resourceGroupName, vmName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Run command on the VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Run command operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RunCommandResult> RunCommandAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, RunCommandInput parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RunCommandWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
public static VirtualMachineCaptureResult BeginCapture(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters)
{
return operations.BeginCaptureAsync(resourceGroupName, vmName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Captures the VM by copying virtual hard disks of the VM and outputs a
/// template that can be used to create similar VMs.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Capture Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachineCaptureResult> BeginCaptureAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineCaptureParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCaptureWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to create or update a virtual machine. Please note some
/// properties can be set only during virtual machine creation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
public static VirtualMachine BeginCreateOrUpdate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, vmName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to create or update a virtual machine. Please note some
/// properties can be set only during virtual machine creation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Create Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachine> BeginCreateOrUpdateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachine parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Virtual Machine operation.
/// </param>
public static VirtualMachine BeginUpdate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineUpdate parameters)
{
return operations.BeginUpdateAsync(resourceGroupName, vmName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to update a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update Virtual Machine operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachine> BeginUpdateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, VirtualMachineUpdate parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginDelete(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.BeginDeleteAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to delete a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Converts virtual machine disks from blob-based to managed disks. Virtual
/// machine must be stop-deallocated before invoking this operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginConvertToManagedDisks(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.BeginConvertToManagedDisksAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Converts virtual machine disks from blob-based to managed disks. Virtual
/// machine must be stop-deallocated before invoking this operation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginConvertToManagedDisksAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginConvertToManagedDisksWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Shuts down the virtual machine and releases the compute resources. You are
/// not billed for the compute resources that this virtual machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginDeallocate(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.BeginDeallocateAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Shuts down the virtual machine and releases the compute resources. You are
/// not billed for the compute resources that this virtual machine uses.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeallocateAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeallocateWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// The operation to power off (stop) a virtual machine. The virtual machine
/// can be restarted with the same provisioned resources. You are still charged
/// for this virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='skipShutdown'>
/// The parameter to request non-graceful VM shutdown. True value for this flag
/// indicates non-graceful shutdown whereas false indicates otherwise. Default
/// value for this flag is false if not specified
/// </param>
public static void BeginPowerOff(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, bool? skipShutdown = false)
{
operations.BeginPowerOffAsync(resourceGroupName, vmName, skipShutdown).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to power off (stop) a virtual machine. The virtual machine
/// can be restarted with the same provisioned resources. You are still charged
/// for this virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='skipShutdown'>
/// The parameter to request non-graceful VM shutdown. True value for this flag
/// indicates non-graceful shutdown whereas false indicates otherwise. Default
/// value for this flag is false if not specified
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginPowerOffAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, bool? skipShutdown = false, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginPowerOffWithHttpMessagesAsync(resourceGroupName, vmName, skipShutdown, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// The operation to reapply a virtual machine's state.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginReapply(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.BeginReapplyAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to reapply a virtual machine's state.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginReapplyAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginReapplyWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginRestart(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.BeginRestartAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to restart a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginRestartAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginRestartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginStart(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.BeginStartAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to start a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginStartAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginStartWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Shuts down the virtual machine, moves it to a new node, and powers it back
/// on.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginRedeploy(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.BeginRedeployAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Shuts down the virtual machine, moves it to a new node, and powers it back
/// on.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginRedeployAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginRedeployWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Reimages the virtual machine which has an ephemeral OS disk back to its
/// initial state.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='tempDisk'>
/// Specifies whether to reimage temp disk. Default value: false. Note: This
/// temp disk reimage parameter is only supported for VM/VMSS with Ephemeral OS
/// disk.
/// </param>
public static void BeginReimage(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, bool? tempDisk = default(bool?))
{
operations.BeginReimageAsync(resourceGroupName, vmName, tempDisk).GetAwaiter().GetResult();
}
/// <summary>
/// Reimages the virtual machine which has an ephemeral OS disk back to its
/// initial state.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='tempDisk'>
/// Specifies whether to reimage temp disk. Default value: false. Note: This
/// temp disk reimage parameter is only supported for VM/VMSS with Ephemeral OS
/// disk.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginReimageAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, bool? tempDisk = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginReimageWithHttpMessagesAsync(resourceGroupName, vmName, tempDisk, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// The operation to perform maintenance on a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static void BeginPerformMaintenance(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
operations.BeginPerformMaintenanceAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// The operation to perform maintenance on a virtual machine.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginPerformMaintenanceAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginPerformMaintenanceWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Assess patches on the VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
public static VirtualMachineAssessPatchesResult BeginAssessPatches(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName)
{
return operations.BeginAssessPatchesAsync(resourceGroupName, vmName).GetAwaiter().GetResult();
}
/// <summary>
/// Assess patches on the VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VirtualMachineAssessPatchesResult> BeginAssessPatchesAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginAssessPatchesWithHttpMessagesAsync(resourceGroupName, vmName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Run command on the VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Run command operation.
/// </param>
public static RunCommandResult BeginRunCommand(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, RunCommandInput parameters)
{
return operations.BeginRunCommandAsync(resourceGroupName, vmName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Run command on the VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='vmName'>
/// The name of the virtual machine.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Run command operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RunCommandResult> BeginRunCommandAsync(this IVirtualMachinesOperations operations, string resourceGroupName, string vmName, RunCommandInput parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginRunCommandWithHttpMessagesAsync(resourceGroupName, vmName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all the virtual machines under the specified subscription for the
/// specified location.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<VirtualMachine> ListByLocationNext(this IVirtualMachinesOperations operations, string nextPageLink)
{
return operations.ListByLocationNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all the virtual machines under the specified subscription for the
/// specified location.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListByLocationNextAsync(this IVirtualMachinesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByLocationNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the virtual machines in the specified resource group. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<VirtualMachine> ListNext(this IVirtualMachinesOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the virtual machines in the specified resource group. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListNextAsync(this IVirtualMachinesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the virtual machines in the specified subscription. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<VirtualMachine> ListAllNext(this IVirtualMachinesOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the virtual machines in the specified subscription. Use the
/// nextLink property in the response to get the next page of virtual machines.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<VirtualMachine>> ListAllNextAsync(this IVirtualMachinesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 48.8125 | 307 | 0.564938 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/compute/Microsoft.Azure.Management.Compute/src/Generated/VirtualMachinesOperationsExtensions.cs | 86,691 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.vod.Transform;
using Aliyun.Acs.vod.Transform.V20170321;
namespace Aliyun.Acs.vod.Model.V20170321
{
public class ListTranscodeTaskRequest : RpcAcsRequest<ListTranscodeTaskResponse>
{
public ListTranscodeTaskRequest()
: base("vod", "2017-03-21", "ListTranscodeTask", "vod", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null);
}
Method = MethodType.POST;
}
private long? resourceOwnerId;
private string startTime;
private int? pageSize;
private string resourceOwnerAccount;
private string endTime;
private string videoId;
private long? ownerId;
private int? pageNo;
public long? ResourceOwnerId
{
get
{
return resourceOwnerId;
}
set
{
resourceOwnerId = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString());
}
}
public string StartTime
{
get
{
return startTime;
}
set
{
startTime = value;
DictionaryUtil.Add(QueryParameters, "StartTime", value);
}
}
public int? PageSize
{
get
{
return pageSize;
}
set
{
pageSize = value;
DictionaryUtil.Add(QueryParameters, "PageSize", value.ToString());
}
}
public string ResourceOwnerAccount
{
get
{
return resourceOwnerAccount;
}
set
{
resourceOwnerAccount = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value);
}
}
public string EndTime
{
get
{
return endTime;
}
set
{
endTime = value;
DictionaryUtil.Add(QueryParameters, "EndTime", value);
}
}
public string VideoId
{
get
{
return videoId;
}
set
{
videoId = value;
DictionaryUtil.Add(QueryParameters, "VideoId", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public int? PageNo
{
get
{
return pageNo;
}
set
{
pageNo = value;
DictionaryUtil.Add(QueryParameters, "PageNo", value.ToString());
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override ListTranscodeTaskResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return ListTranscodeTaskResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 22.16092 | 134 | 0.644969 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-vod/Vod/Model/V20170321/ListTranscodeTaskRequest.cs | 3,856 | C# |
using System.Management.Automation;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.UserProfiles;
using PnP.PowerShell.Commands.Base;
using System.Linq;
namespace PnP.PowerShell.Commands.UserProfiles
{
[Cmdlet(VerbsCommon.Set, "UserProfileProperty")]
public class SetUserProfileProperty : PnPAdminCmdlet
{
[Parameter(Mandatory = true, ParameterSetName = ParameterAttribute.AllParameterSets)]
public string Account;
[Parameter(Mandatory = true, ParameterSetName = ParameterAttribute.AllParameterSets)]
public string PropertyName;
[Parameter(Mandatory = true, ParameterSetName = "Single")]
[AllowEmptyString]
[AllowNull]
public string Value;
[Parameter(Mandatory = true,ParameterSetName = "Multi")]
[AllowEmptyString]
[AllowNull]
public string[] Values;
protected override void ExecuteCmdlet()
{
var peopleManager = new PeopleManager(ClientContext);
var result = Tenant.EncodeClaim(Account);
ClientContext.ExecuteQueryRetry();
if (ParameterSetName == "Single")
{
peopleManager.SetSingleValueProfileProperty(result.Value, PropertyName, Value);
}
else
{
peopleManager.SetMultiValuedProfileProperty(result.Value, PropertyName, Values.ToList());
}
ClientContext.ExecuteQueryRetry();
}
}
} | 30.653061 | 105 | 0.653795 | [
"MIT"
] | JimmyHang/powershell | src/Commands/UserProfiles/SetUserProfileProperty.cs | 1,504 | C# |
using System;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.Callbacks;
public class PostBuildActions
{
[PostProcessBuild]
public static void OnPostProcessBuild(BuildTarget target, string targetPath)
{
var path = Path.Combine(targetPath, "Build/UnityLoader.js");
var text = File.ReadAllText(path);
text = text.Replace("UnityLoader.SystemInfo.mobile", "false");
File.WriteAllText(path, text);
}
} | 29.117647 | 80 | 0.709091 | [
"MIT"
] | AkioUnity/SevenStar | Assets/Editor/PostBuildActions.cs | 497 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.AspNetCore.Mvc.ApplicationModels
{
/// <summary>
/// Allows customization of the <see cref="ParameterModel"/>.
/// </summary>
/// <remarks>
/// To use this interface, create an <see cref="System.Attribute"/> class which implements the interface and
/// place it on an action method parameter.
///
/// <see cref="IParameterModelConvention"/> customizations run after
/// <see cref="IActionModelConvention"/> customizations.
/// </remarks>
public interface IParameterModelConvention
{
/// <summary>
/// Called to apply the convention to the <see cref="ParameterModel"/>.
/// </summary>
/// <param name="parameter">The <see cref="ParameterModel"/>.</param>
void Apply(ParameterModel parameter);
}
}
| 37.88 | 112 | 0.657867 | [
"MIT"
] | 48355746/AspNetCore | src/Mvc/Mvc.Core/src/ApplicationModels/IParameterModelConvention.cs | 947 | C# |
using LogicMonitor.Api.Alerts;
using LogicMonitor.Api.Attributes;
using LogicMonitor.Api.Extensions;
using LogicMonitor.Api.LogicModules;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace LogicMonitor.Api.Devices
{
/// <summary>
/// A Device (also known as a Host)
/// </summary>
[DataContract]
public class Device : NamedItem, IHasCustomProperties, IPatchable
{
/// <summary>
/// The autoBalanced CollectorGroup id
/// </summary>
[DataMember(Name = "autoBalancedCollectorGroupId")]
public int AutoBalancedCollectorGroupId { get; set; }
/// <summary>
/// The alert disable status
/// </summary>
[DataMember(Name = "alertDisableStatus")]
public AlertDisableStatus AlertDisableStatus { get; set; }
/// <summary>
/// The alert disable status
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "alertingDisabledOn")]
public AlertingDisabledOn AlertingDisabledOn { get; set; }
/// <summary>
/// The alert status
/// </summary>
[DataMember(Name = "alertStatusPriority")]
public int AlertStatusPriority { get; set; }
/// <summary>
/// The alert status
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "alertStatus")]
public AlertStatus AlertStatus { get; set; }
/// <summary>
/// Whether the ancestorHasDisabledLogicModule
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "ancestorHasDisabledLogicModule")]
public bool AncestorHasDisabledLogicModule { get; set; }
/// <summary>
/// The auto properties
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "autoProperties")]
public List<Property> AutoProperties { get; set; }
/// <summary>
/// The time that the auto-properties were assigned in seconds since the Epoch
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "autoPropsAssignedOn")]
public long? AutoPropertiesAssignedOnSeconds { get; set; }
/// <summary>
/// The time that the auto-properties were updated
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "autoPropsUpdatedOn")]
public long? AutoPropertiesUpdatedOnSeconds { get; set; }
/// <summary>
/// The device AWS status
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "awsState")]
public AwsState AwsState { get; set; }
/// <summary>
/// The device Azure status
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "azureState")]
public AzureState AzureState { get; set; }
/// <summary>
/// The device GCP status
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "gcpState")]
public AzureState GcpState { get; set; }
/// <summary>
/// Whether the device can use remote session
/// </summary>
[DataMember(Name = "canUseRemoteSession")]
public bool CanUseRemoteSession { get; set; }
/// <summary>
/// The Collector description
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "collectorDescription")]
public string CollectorDescription { get; set; }
/// <summary>
/// When the device was created
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "createdOn")]
public long? CreatedOnSeconds { get; set; }
/// <summary>
/// The Current Collector's ID
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "currentCollectorId")]
public int CurrentCollectorId { get; set; }
/// <summary>
/// Custom properties
/// </summary>
[DataMember(Name = "customProperties")]
public List<Property> CustomProperties { get; set; }
/// <summary>
/// The device status
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "deletedTimeInMs")]
public long DeletedTimeinMs { get; set; }
/// <summary>
/// The device type
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "deviceType")]
public DeviceType DeviceType { get; set; }
/// <summary>
/// Whether alerting is effectively enabled
/// </summary>
[DataMember(Name = "disableAlerting")]
public bool IsAlertingDisabled { get; set; }
/// <summary>
/// The display name
/// </summary>
[DataMember(Name = "displayName")]
public string DisplayName { get; set; }
/// <summary>
/// Whether alerting is effectively enabled
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "effectiveAlertEnabled")]
public bool EffectiveAlertEnabled { get; set; }
/// <summary>
/// Whether Netflow is enabled
/// </summary>
[DataMember(Name = "enableNetflow")]
public bool EnableNetflow { get; set; }
/// <summary>
/// Whether the device has an active instance
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "hasActiveInstance")]
public bool HasActiveInstance { get; set; }
/// <summary>
/// Whether the device has a disabled sub-resource
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "hasDisabledSubResource")]
public bool HasDisabledSubResource { get; set; }
/// <summary>
/// Whether the device has more (?)
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "hasMore")]
public bool HasMore { get; set; }
/// <summary>
/// The device type (usually Host)
/// </summary>
[DataMember(Name = "hostGroupIds")]
public string DeviceGroupIdsString { get; set; }
/// <summary>
/// The device status
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "hostStatus")]
public Level DeviceStatus { get; set; }
/// <summary>
/// Inherited properties
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "inheritedProperties")]
public List<Property> InheritedProperties { get; set; }
/// <summary>
/// The instances
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "instance")]
public List<DeviceDataSourceInstanceSummary> Instances { get; set; }
/// <summary>
/// The last time that raw data was received for the device
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "lastDataTime")]
public long? LastDataTimeSeconds { get; set; }
/// <summary>
/// The last time that raw data was received for the device
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "lastRawDataTime")]
public long? LastRawDataTimeSeconds { get; set; }
/// <summary>
/// The device's configured URL
/// </summary>
[DataMember(Name = "link")]
public string Link { get; set; }
/// <summary>
/// Whether the device has a disabled sub-resource
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "manualDiscoveryFlags")]
public ManualDiscoveryFlags ManualDiscoveryFlags { get; set; }
/// <summary>
/// The Netflow Collector Id
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "netflowCollectorId")]
public int NetflowCollectorId { get; set; }
/// <summary>
/// The Netflow Collector description
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "netflowCollectorDescription")]
public string NetflowCollectorDescription { get; set; }
/// <summary>
/// The Netflow Collector Group Id
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "netflowCollectorGroupId")]
public int NetflowCollectorGroupId { get; set; }
/// <summary>
/// The Netflow Collector Group name
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "netflowCollectorGroupName")]
public string NetflowCollectorGroupName { get; set; }
/// <summary>
/// The preferred Collector Id
/// </summary>
[DataMember(Name = "preferredCollectorId")]
public int PreferredCollectorId { get; set; }
/// <summary>
/// The preferred CollectorGroup Id
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "preferredCollectorGroupId")]
public int PreferredCollectorGroupId { get; set; }
/// <summary>
/// The preferred CollectorGroup Id
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "preferredCollectorGroupName")]
public string PreferredCollectorGroupName { get; set; }
/// <summary>
/// The ID of the related device
/// </summary>
[DataMember(Name = "relatedDeviceId")]
public int RelatedDeviceId { get; set; }
/// <summary>
/// The Scan config ID
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "scanConfigId")]
public int ScanConfigId { get; set; }
/// <summary>
/// Whether the device is currently in SDT
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "sdtStatus")]
public SdtStatus SdtStatus { get; set; }
/// <summary>
/// The device's system properties
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "systemProperties")]
public List<Property> SystemProperties { get; set; }
/// <summary>
/// The time in Ms before the device will be deleted
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "toDeleteTimeInMs")]
public long ToDeleteTimeinMs { get; set; }
/// <summary>
/// Uptime in seconds
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "upTimeInSeconds")]
public int UptimeInSeconds { get; set; }
/// <summary>
/// The last time that the device was updated in seconds since the Epoch
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "updatedOn")]
public long? UpdatedOnSeconds { get; set; }
/// <summary>
/// LoadBalance CollectorGroupId
/// </summary>
[DataMember(Name = "loadBalanceCollectorGroupId")]
public int LoadBalanceCollectorGroupId { get; set; }
/// <summary>
/// User Permission
/// </summary>
[SantabaReadOnly]
[DataMember(Name = "userPermission")]
public UserPermission UserPermission { get; set; }
/// <summary>
/// The UTC DateTime that the auto-properties were assigned
/// </summary>
[IgnoreDataMember]
public DateTime? AutoPropertiesAssignedOnUtc => AutoPropertiesAssignedOnSeconds?.ToNullableDateTimeUtc();
/// <summary>
/// The UTC DateTime that the auto-properties were updated
/// </summary>
[IgnoreDataMember]
public DateTime? AutoPropertiesUpdatedOnUtc => AutoPropertiesUpdatedOnSeconds?.ToNullableDateTimeUtc();
/// <summary>
/// The UTC DateTime that the device was created in the system
/// </summary>
[IgnoreDataMember]
public DateTime? CreatedOnUtc => CreatedOnSeconds?.ToNullableDateTimeUtc();
/// <summary>
/// The UTC DateTime that raw data was last received
/// </summary>
[IgnoreDataMember]
public DateTime? LastRawDataUtc => LastRawDataTimeSeconds?.ToNullableDateTimeUtc();
/// <summary>
/// The UTC DateTime that data was last received
/// </summary>
[IgnoreDataMember]
public DateTime? LastDataUtc => LastDataTimeSeconds?.ToNullableDateTimeUtc();
/// <summary>
/// The UTC DateTime that the device was updated in the system
/// </summary>
[IgnoreDataMember]
public DateTime? UpdatedOnUtc => UpdatedOnSeconds?.ToNullableDateTimeUtc();
/// <inheritdoc />
public string Endpoint() => "device/devices";
/// <inheritdoc />
public override string ToString() => $"{Id} : {(!string.IsNullOrWhiteSpace(DisplayName) ? DisplayName : Name)}";
}
} | 27.636364 | 114 | 0.6642 | [
"MIT"
] | tdicks/LogicMonitor.Api | LogicMonitor.Api/Devices/Device.cs | 10,944 | C# |
using System.Collections.Generic;
using Ertis.Core.Models.Resources;
using ErtisAuth.Core.Models.Identity;
using Newtonsoft.Json;
namespace ErtisAuth.Core.Models.Users
{
public class User : MembershipBoundedResource, IUtilizer, IHasSysInfo
{
#region Properties
[JsonProperty("firstname")]
public string FirstName { get; set; }
[JsonProperty("lastname")]
public string LastName { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("email_address")]
public string EmailAddress { get; set; }
[JsonProperty("role")]
public string Role { get; set; }
[JsonProperty("permissions")]
public IEnumerable<string> Permissions { get; set; }
[JsonProperty("forbidden")]
public IEnumerable<string> Forbidden { get; set; }
[JsonProperty("sys")]
public SysModel Sys { get; set; }
[JsonIgnore]
public Utilizer.UtilizerType UtilizerType => Utilizer.UtilizerType.User;
#endregion
}
} | 23.634146 | 74 | 0.714138 | [
"MIT"
] | ertugrulozcan/ErtisAuth | ErtisAuth.Core/Models/Users/User.cs | 969 | C# |
// MIT License
//
// Copyright (c) Y2 Corporation
using System;
namespace Y2.Ft4222.Core
{
/// <summary>
/// I2C Master Flag
/// </summary>
[Flags]
public enum I2cMasterFlags
{
/// <summary>
/// No specific flag
/// </summary>
None = Iot.Device.Ft4222.I2cMasterFlag.None,
/// <summary>
/// Send start
/// </summary>
Start = Iot.Device.Ft4222.I2cMasterFlag.Start,
/// <summary>
/// Repeated start
/// </summary>
RepeatedStart = Iot.Device.Ft4222.I2cMasterFlag.RepeatedStart,
/// <summary>
/// Send stop
/// </summary>
Stop = Iot.Device.Ft4222.I2cMasterFlag.Stop,
/// <summary>
/// Start condition followed by a stop condition
/// </summary>
StartAndStop = Iot.Device.Ft4222.I2cMasterFlag.StartAndStop,
}
}
| 21.95122 | 70 | 0.543333 | [
"MIT"
] | y2cjp/Y2.Ft4222.Core | src/I2cMasterFlags.cs | 902 | C# |
using System;
namespace Atata
{
public interface IVerificationProvider<TOwner>
{
/// <summary>
/// Gets a value indicating whether the verification is a negation verification.
/// </summary>
bool IsNegation { get; }
/// <summary>
/// Gets or sets the verification strategy.
/// </summary>
IVerificationStrategy Strategy { get; set; }
/// <summary>
/// Gets the owner object.
/// </summary>
TOwner Owner { get; }
/// <summary>
/// Gets the text describing the kind of the verification.
/// </summary>
string VerificationKind { get; }
/// <summary>
/// Gets or sets the timeout.
/// </summary>
// TODO: Should be non-nullable.
TimeSpan? Timeout { get; set; }
/// <summary>
/// Gets or sets the retry interval.
/// </summary>
// TODO: Should be non-nullable.
TimeSpan? RetryInterval { get; set; }
/// <summary>
/// Gets the should text.
/// </summary>
/// <returns>Either <c>"should"</c> or <c>"should not"</c>.</returns>
string GetShouldText();
/// <summary>
/// Gets the retry options.
/// </summary>
/// <returns>The <see cref="RetryOptions"/> instance.</returns>
RetryOptions GetRetryOptions();
/// <summary>
/// Reports the failure.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
void ReportFailure(string message, Exception exception = null);
}
}
| 29.355932 | 89 | 0.512125 | [
"Apache-2.0"
] | atata-framework/atata | src/Atata/Verification/IVerificationProvider`1.cs | 1,734 | C# |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using ICSharpCode.ILSpy.Controls;
using Mono.Cecil;
namespace ICSharpCode.ILSpy
{
/// <summary>
/// Interaction logic for OpenFromGacDialog.xaml
/// </summary>
public partial class OpenFromGacDialog : Window
{
ObservableCollection<GacEntry> gacEntries = new ObservableCollection<GacEntry>();
ObservableCollection<GacEntry> filteredEntries = new ObservableCollection<GacEntry>();
Predicate<GacEntry> filterMethod = _ => true;
volatile bool cancelFetchThread;
public OpenFromGacDialog()
{
InitializeComponent();
listView.ItemsSource = filteredEntries;
SortableGridViewColumn.SetCurrentSortColumn(listView, nameColumn);
SortableGridViewColumn.SetSortDirection(listView, ColumnSortDirection.Ascending);
new Thread(new ThreadStart(FetchGacContents)).Start();
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
cancelFetchThread = true;
}
#region Fetch Gac Contents
sealed class GacEntry
{
readonly AssemblyNameReference r;
readonly string fileName;
string formattedVersion;
public GacEntry(AssemblyNameReference r, string fileName)
{
this.r = r;
this.fileName = fileName;
}
public string FullName {
get { return r.FullName; }
}
public string ShortName {
get { return r.Name; }
}
public string FileName {
get { return fileName; }
}
public Version Version {
get { return r.Version; }
}
public string FormattedVersion {
get {
if (formattedVersion == null)
formattedVersion = Version.ToString();
return formattedVersion;
}
}
public string Culture {
get { return r.Culture; }
}
public string PublicKeyToken {
get {
StringBuilder s = new StringBuilder();
foreach (byte b in r.PublicKeyToken)
s.Append(b.ToString("x2"));
return s.ToString();
}
}
public override string ToString()
{
return r.FullName;
}
}
void FetchGacContents()
{
HashSet<string> fullNames = new HashSet<string>();
UpdateProgressBar(pg => { pg.Visibility = System.Windows.Visibility.Visible; pg.IsIndeterminate = true; });
var list = GacInterop.GetGacAssemblyFullNames().TakeWhile(_ => !cancelFetchThread).ToList();
UpdateProgressBar(pg => { pg.IsIndeterminate = false; pg.Maximum = list.Count; });
foreach (var r in list) {
if (cancelFetchThread)
break;
if (fullNames.Add(r.FullName)) { // filter duplicates
var file = GacInterop.FindAssemblyInNetGac(r);
if (file != null) {
var entry = new GacEntry(r, file);
UpdateProgressBar(pg => { pg.Value = pg.Value + 1; AddNewEntry(entry); });
}
}
}
UpdateProgressBar(pg => { pg.Visibility = System.Windows.Visibility.Hidden; });
}
void UpdateProgressBar(Action<ProgressBar> updateAction)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => updateAction(gacReadingProgressBar)));
}
void AddNewEntry(GacEntry entry)
{
gacEntries.Add(entry);
if (filterMethod(entry))
filteredEntries.Add(entry);
}
#endregion
void FilterTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string filterString = filterTextBox.Text.Trim();
if (filterString.Length == 0)
filterMethod = _ => true;
else {
var elements = filterString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
filterMethod = entry => elements.All(el => Contains(entry.FullName, el) || Contains(entry.FormattedVersion, el));
}
filteredEntries.Clear();
filteredEntries.AddRange(gacEntries.Where(entry => filterMethod(entry)));
}
static bool Contains(string s, string subString)
{
return s.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0;
}
void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
okButton.IsEnabled = listView.SelectedItems.Count > 0;
}
void OKButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
Close();
}
public string[] SelectedFileNames {
get {
return listView.SelectedItems.OfType<GacEntry>().Select(e => e.FileName).ToArray();
}
}
}
} | 29.741935 | 117 | 0.716197 | [
"MIT"
] | 0x53A/ILSpy | ILSpy/OpenFromGacDialog.xaml.cs | 5,534 | C# |
using Newtonsoft.Json;
namespace TradingBotPrj.Models
{
public partial class ErrorModel
{
[JsonProperty("code")]
public long Code { get; set; }
[JsonProperty("msg")]
public string Msg { get; set; }
}
}
| 17.785714 | 39 | 0.590361 | [
"MIT"
] | SnnK/binance-trader | TradingBotPrj/Models/ErrorModel.cs | 251 | C# |
using System.Collections.Generic;
using UnityEngine;
namespace Surrogates
{
public class SystemBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
public static List<T> Instances { get; private set; }
// public static Vector3[] arrayS = new Vector3[5];
BatchSystem system;
protected virtual void OnEnable()
{
if (Instances == null)
Instances = new List<T>();
system = BatchSystem.Get<T>();
Instances.Add(this as T);
}
protected virtual void OnDisable()
{
var end = Instances.Count - 1;
var index = Instances.IndexOf(this as T);
Instances[index] = Instances[end];
Instances.RemoveAt(end);
}
}
} | 27.964286 | 75 | 0.564496 | [
"MIT"
] | simonwittber/surrogates | SurrogateBatch/Runtime/SystemBehaviour.cs | 783 | C# |
using System;
using System.Runtime.CompilerServices;
using Xamarin.Forms;
using XF.Material.Forms.Resources.Typography;
namespace XF.Material.Forms.UI
{
public class MaterialLabel : Label
{
public const string MaterialLineHeightPropertyName = "MaterialLineHeight";
public static readonly BindableProperty LetterSpacingProperty = BindableProperty.Create(nameof(LetterSpacing), typeof(double), typeof(MaterialLabel), 0.0);
public static new readonly BindableProperty LineHeightProperty = BindableProperty.Create(MaterialLineHeightPropertyName, typeof(double), typeof(MaterialLabel), 1.4);
public static readonly BindableProperty TypeScaleProperty = BindableProperty.Create(nameof(TypeScale), typeof(MaterialTypeScale), typeof(MaterialLabel), MaterialTypeScale.None);
private bool _fontFamilyChanged;
private bool _fontSizeChanged;
private bool _letterSpacingChanged;
private bool _fontAttributeChanged;
/// <summary>
/// Gets or sets the letter spacing of this label's text.
/// </summary>
public double LetterSpacing
{
get => (double)this.GetValue(LetterSpacingProperty);
set => this.SetValue(LetterSpacingProperty, value);
}
/// <summary>
/// Gets or sets the multiplier that determines the line height of this label.
/// </summary>
public new double LineHeight
{
get => (double)this.GetValue(LineHeightProperty);
set => this.SetValue(LineHeightProperty, value);
}
/// <summary>
/// Gets or sets the type scale used for this label.
/// </summary>
public MaterialTypeScale TypeScale
{
get => (MaterialTypeScale)this.GetValue(TypeScaleProperty);
set => this.SetValue(TypeScaleProperty, value);
}
protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
base.OnPropertyChanged(propertyName);
switch (propertyName)
{
case nameof(this.TypeScale):
this.OnTypeScaleChanged(this.TypeScale);
break;
case nameof(this.FontSize):
_fontSizeChanged = true;
break;
case nameof(this.FontFamily):
_fontFamilyChanged = true;
break;
case nameof(this.LetterSpacing):
_letterSpacingChanged = true;
break;
case nameof(this.FontAttributes):
_fontAttributeChanged = true;
break;
}
}
protected virtual void OnTypeScaleChanged(MaterialTypeScale materialTypeScale)
{
if (materialTypeScale == MaterialTypeScale.None)
{
return;
}
if (!_letterSpacingChanged)
{
var letterSpacingKey = $"Material.LetterSpacing.{materialTypeScale.ToString()}";
this.LetterSpacing = Convert.ToDouble(Application.Current.Resources[letterSpacingKey]);
}
if (!_fontFamilyChanged)
{
var fontFamilyKey = $"Material.FontFamily.{materialTypeScale.ToString()}";
this.FontFamily = Application.Current.Resources[fontFamilyKey]?.ToString();
}
if (!_fontSizeChanged)
{
var fontSizeKey = $"Material.FontSize.{materialTypeScale.ToString()}";
this.FontSize = Convert.ToDouble(Application.Current.Resources[fontSizeKey]);
}
if (_fontAttributeChanged) return;
switch (materialTypeScale)
{
case MaterialTypeScale.H6:
case MaterialTypeScale.Subtitle2:
case MaterialTypeScale.Button:
this.FontAttributes = FontAttributes.Bold;
break;
}
}
}
} | 38.11215 | 185 | 0.591957 | [
"MIT"
] | eceowl/XF-Material-Library | XF.Material/XF.Material.Forms/UI/MaterialLabel.cs | 4,080 | C# |
using Uno.UI.Web;
using System;
using System.Collections.Generic;
using System.Text;
namespace Windows.UI.Xaml.Controls
{
public partial class WebViewNavigationFailedEventArgs
{
public Uri Uri { get; internal set; }
public WebErrorStatus WebErrorStatus { get; internal set; }
}
}
| 22.142857 | 67 | 0.716129 | [
"Apache-2.0"
] | 06needhamt/uno | src/Uno.UI/UI/Xaml/Controls/WebView/WebViewNavigationFailedEventArgs.cs | 312 | C# |
namespace Rancher.DotNet.Models
{
public interface IRequestObject
{
string name { get; set; }
string description { get; set; }
}
}
| 17.777778 | 40 | 0.6 | [
"Apache-2.0"
] | writeameer/RancherDotNet | src/RancherDotNet/Models/IRequestObject.cs | 162 | C# |
using System;
using System.Collections.Generic;
using Mapbox.Map;
using Mapbox.Unity.Utilities;
using Mapbox.Utils;
using UnityEngine;
namespace Mapbox.Unity.Map.TileProviders
{
public class QuadTreeTileProvider : AbstractTileProvider
{
private static readonly int HIT_POINTS_COUNT = 4;
private Plane _groundPlane;
private bool _shouldUpdate;
private CameraBoundsTileProviderOptions _cbtpOptions;
//private List<UnwrappedTileId> _toRemove;
//private HashSet<UnwrappedTileId> _tilesToRequest;
private Vector2dBounds _viewPortWebMercBounds;
#region Tile decision and raycasting fields
private HashSet<UnwrappedTileId> _tiles;
private HashSet<CanonicalTileId> _canonicalTiles;
private Ray _ray00;
private Ray _ray01;
private Ray _ray10;
private Ray _ray11;
private Vector3[] _hitPnt = new Vector3[HIT_POINTS_COUNT];
private Vector2d[] _hitPntGeoPos = new Vector2d[HIT_POINTS_COUNT];
private bool _isFirstLoad;
#endregion
public override void OnInitialized()
{
_tiles = new HashSet<UnwrappedTileId>();
_canonicalTiles = new HashSet<CanonicalTileId>();
_cbtpOptions = (CameraBoundsTileProviderOptions)_options;
if (_cbtpOptions.camera == null)
{
_cbtpOptions.camera = Camera.main;
}
_cbtpOptions.camera.transform.hasChanged = false;
_groundPlane = new Plane(Vector3.up, 0);
_shouldUpdate = true;
_currentExtent.activeTiles = new HashSet<UnwrappedTileId>();
}
public override void UpdateTileExtent()
{
if (!_shouldUpdate)
{
return;
}
//update viewport in case it was changed by switching zoom level
_viewPortWebMercBounds = getcurrentViewPortWebMerc();
_currentExtent.activeTiles = GetWithWebMerc(_viewPortWebMercBounds, _map.AbsoluteZoom);
OnExtentChanged();
}
public HashSet<UnwrappedTileId> GetWithWebMerc(Vector2dBounds bounds, int zoom)
{
_tiles.Clear();
_canonicalTiles.Clear();
if (bounds.IsEmpty()) { return _tiles; }
//stay within WebMerc bounds
Vector2d swWebMerc = new Vector2d(Math.Max(bounds.SouthWest.x, -Utils.Constants.WebMercMax), Math.Max(bounds.SouthWest.y, -Utils.Constants.WebMercMax));
Vector2d neWebMerc = new Vector2d(Math.Min(bounds.NorthEast.x, Utils.Constants.WebMercMax), Math.Min(bounds.NorthEast.y, Utils.Constants.WebMercMax));
//UnityEngine.Debug.LogFormat("swWebMerc:{0}/{1} neWebMerc:{2}/{3}", swWebMerc.x, swWebMerc.y, neWebMerc.x, neWebMerc.y);
UnwrappedTileId swTile = WebMercatorToTileId(swWebMerc, zoom);
UnwrappedTileId neTile = WebMercatorToTileId(neWebMerc, zoom);
//UnityEngine.Debug.LogFormat("swTile:{0} neTile:{1}", swTile, neTile);
for (int x = swTile.X; x <= neTile.X; x++)
{
for (int y = neTile.Y; y <= swTile.Y; y++)
{
UnwrappedTileId uwtid = new UnwrappedTileId(zoom, x, y);
//hack: currently too many tiles are created at lower zoom levels
//investigate formulas, this worked before
if (!_canonicalTiles.Contains(uwtid.Canonical))
{
//Debug.LogFormat("TileCover.GetWithWebMerc: {0}/{1}/{2}", zoom, x, y);
_tiles.Add(uwtid);
_canonicalTiles.Add(uwtid.Canonical);
}
}
}
return _tiles;
}
public UnwrappedTileId WebMercatorToTileId(Vector2d webMerc, int zoom)
{
var tileCount = Math.Pow(2, zoom);
var dblX = webMerc.x / Utils.Constants.WebMercMax;
var dblY = webMerc.y / Utils.Constants.WebMercMax;
int x = (int)Math.Floor((1 + dblX) / 2 * tileCount);
int y = (int)Math.Floor((1 - dblY) / 2 * tileCount);
return new UnwrappedTileId(zoom, x, y);
}
private Vector2dBounds getcurrentViewPortWebMerc(bool useGroundPlane = true)
{
if (useGroundPlane)
{
// rays from camera to groundplane: lower left and upper right
_ray00 = _cbtpOptions.camera.ViewportPointToRay(new Vector3(0, 0));
_ray01 = _cbtpOptions.camera.ViewportPointToRay(new Vector3(0, 1));
_ray10 = _cbtpOptions.camera.ViewportPointToRay(new Vector3(1, 0));
_ray11 = _cbtpOptions.camera.ViewportPointToRay(new Vector3(1, 1));
_hitPnt[0] = getGroundPlaneHitPoint(_ray00);
_hitPnt[1] = getGroundPlaneHitPoint(_ray01);
_hitPnt[2] = getGroundPlaneHitPoint(_ray10);
_hitPnt[3] = getGroundPlaneHitPoint(_ray11);
}
// Find min max bounding box.
// TODO : Find a better way of doing this.
double minLat = double.MaxValue;
double minLong = double.MaxValue;
double maxLat = double.MinValue;
double maxLong = double.MinValue;
for (int pointIndex = 0; pointIndex < HIT_POINTS_COUNT; ++pointIndex)
{
_hitPntGeoPos[pointIndex] = _map.WorldToGeoPosition(_hitPnt[pointIndex]);
}
for (int i = 0; i < HIT_POINTS_COUNT; i++)
{
if (_hitPnt[i] == Vector3.zero)
{
continue;
}
else
{
if (minLat > _hitPntGeoPos[i].x)
{
minLat = _hitPntGeoPos[i].x;
}
if (minLong > _hitPntGeoPos[i].y)
{
minLong = _hitPntGeoPos[i].y;
}
if (maxLat < _hitPntGeoPos[i].x)
{
maxLat = _hitPntGeoPos[i].x;
}
if (maxLong < _hitPntGeoPos[i].y)
{
maxLong = _hitPntGeoPos[i].y;
}
}
}
Vector2d hitPntSWGeoPos = new Vector2d(minLat, minLong);
Vector2d hitPntNEGeoPos = new Vector2d(maxLat, maxLong);
Vector2dBounds tileBounds = new Vector2dBounds(Conversions.LatLonToMeters(hitPntSWGeoPos), Conversions.LatLonToMeters(hitPntNEGeoPos)); // Bounds debugging.
#if UNITY_EDITOR
Debug.DrawLine(_cbtpOptions.camera.transform.position, _map.GeoToWorldPosition(hitPntSWGeoPos), Color.blue);
Debug.DrawLine(_cbtpOptions.camera.transform.position, _map.GeoToWorldPosition(hitPntNEGeoPos), Color.red);
#endif
return tileBounds;
}
private Vector3 getGroundPlaneHitPoint(Ray ray)
{
float distance;
if (!_groundPlane.Raycast(ray, out distance)) { return Vector3.zero; }
return ray.GetPoint(distance);
}
public virtual void Update()
{
if (_cbtpOptions != null && _cbtpOptions.camera != null && _cbtpOptions.camera.transform.hasChanged)
{
UpdateTileExtent();
_cbtpOptions.camera.transform.hasChanged = false;
}
}
public override bool Cleanup(UnwrappedTileId tile)
{
return (!_currentExtent.activeTiles.Contains(tile));
}
}
}
| 30.835821 | 161 | 0.71039 | [
"Apache-2.0"
] | Noobay/mapbox-unity-sdk | sdkproject/Assets/Mapbox/Unity/Map/TileProviders/QuadTreeTileProvider.cs | 6,198 | C# |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.S3.Model.Internal.MarshallTransformations
{
/// <summary>
/// Delete Bucket Policy Request Marshaller
/// </summary>
public class DeleteBucketPolicyRequestMarshaller : IMarshaller<IRequest, DeleteBucketPolicyRequest>
{
public IRequest Marshall(DeleteBucketPolicyRequest deleteBucketPolicyRequest)
{
IRequest request = new DefaultRequest(deleteBucketPolicyRequest, "AmazonS3");
request.HttpMethod = "DELETE";
var uriResourcePath = string.Concat("/", S3Transforms.ToStringValue(deleteBucketPolicyRequest.BucketName));
request.Parameters.Add("policy", null);
request.CanonicalResource = S3Transforms.GetCanonicalResource(uriResourcePath, request.Parameters);
request.ResourcePath = S3Transforms.FormatResourcePath(uriResourcePath, request.Parameters);
request.UseQueryString = true;
return request;
}
}
}
| 36.755556 | 119 | 0.706771 | [
"Apache-2.0"
] | virajs/aws-sdk-net | AWSSDK_DotNet35/Amazon.S3/Model/Internal/MarshallTransformations/DeleteBucketPolicyRequestMarshaller.cs | 1,654 | C# |
// <copyright file="FilterAttribute.cs" company="Arm">
// Copyright (c) Arm. All rights reserved.
// </copyright>
namespace MbedCloudSDK.Common.Filter
{
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
/// <summary>
/// Filter Attribute
/// </summary>
public class FilterAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="FilterAttribute"/> class.
/// Create new instance of Query attribute.
/// </summary>
/// <param name="value">Value for the query attribute.</param>
/// <param name="filterOperator">Operator for the query attribute.</param>
[JsonConstructor]
public FilterAttribute(string value, FilterOperator filterOperator = FilterOperator.Equals)
{
Value = value;
FilterOperator = filterOperator;
}
/// <summary>
/// Initializes a new instance of the <see cref="FilterAttribute"/> class.
/// Create new instance of Query attribute.
/// </summary>
/// <param name="value">Value for the query attribute as datetime.</param>
/// <param name="filterOperator">Operator for the query attribute.</param>
public FilterAttribute(DateTime value, FilterOperator filterOperator = FilterOperator.Equals)
{
Value = value.ToString("yyyy-MM-dd'T'HH:mm:ss.fffZ");
FilterOperator = filterOperator;
}
/// <summary>
/// Gets or sets attribute value.
/// </summary>
public string Value { get; set; }
/// <summary>
/// Gets or sets operator for the query.
/// </summary>
public FilterOperator FilterOperator { get; set; }
/// <summary>
/// Gets Json representaion of Filter Attribute
/// </summary>
/// <returns>JObject of Filter Attribute</returns>
public JObject FilterAttributeJson
{
get
{
return new JObject(new JProperty(Filter.QueryOperatorToString(FilterOperator), Value));
}
}
/// <summary>
/// Get the suffix for the query string
/// </summary>
/// <returns>Suffix of query string</returns>
public string GetSuffix()
{
switch (FilterOperator)
{
case FilterOperator.Equals:
return string.Empty;
case FilterOperator.NotEqual:
return "__neq";
case FilterOperator.LessOrEqual:
return "__lte";
case FilterOperator.GreaterOrEqual:
return "__gte";
case FilterOperator.In:
return "__in";
case FilterOperator.NotIn:
return "__nin";
default:
return string.Empty;
}
}
}
} | 33.568182 | 103 | 0.549425 | [
"Apache-2.0"
] | ARMmbed/mbed-cloud-sdk-dotnet | src/Legacy/Common/Filter/FilterAttribute.cs | 2,954 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Npgsql;
namespace RepoDb.PostgreSql.UnitTests
{
[TestClass]
public class DbSettingTest
{
[TestInitialize]
public void Initialize()
{
PostgreSqlBootstrap.Initialize();
}
[TestMethod]
public void TestPostgreSqlDbSettingAreTableHintsSupportedProperty()
{
// Setup
var setting = DbSettingMapper.Get<NpgsqlConnection>();
// Assert
Assert.IsFalse(setting.AreTableHintsSupported);
}
[TestMethod]
public void TestPostgreSqlDbSettingClosingQuoteProperty()
{
// Setup
var setting = DbSettingMapper.Get<NpgsqlConnection>();
// Assert
Assert.AreEqual("\"", setting.ClosingQuote);
}
[TestMethod]
public void TestPostgreSqlDbSettingAverageableTypeProperty()
{
// Setup
var setting = DbSettingMapper.Get<NpgsqlConnection>();
// Assert
Assert.AreEqual(typeof(double), setting.AverageableType);
}
[TestMethod]
public void TestPostgreSqlDbSettingDefaultSchemaProperty()
{
// Setup
var setting = DbSettingMapper.Get<NpgsqlConnection>();
// Assert
Assert.AreEqual("public", setting.DefaultSchema);
}
[TestMethod]
public void TestPostgreSqlDbSettingIsDirectionSupportedProperty()
{
// Setup
var setting = DbSettingMapper.Get<NpgsqlConnection>();
// Assert
Assert.IsTrue(setting.IsDirectionSupported);
}
[TestMethod]
public void TestPostgreSqlDbSettingIsExecuteReaderDisposableProperty()
{
// Setup
var setting = DbSettingMapper.Get<NpgsqlConnection>();
// Assert
Assert.IsTrue(setting.IsExecuteReaderDisposable);
}
[TestMethod]
public void TestPostgreSqlDbSettingIsMultiStatementExecutableProperty()
{
// Setup
var setting = DbSettingMapper.Get<NpgsqlConnection>();
// Assert
Assert.IsTrue(setting.IsMultiStatementExecutable);
}
[TestMethod]
public void TestPostgreSqlDbSettingIsUseUpsertProperty()
{
// Setup
var setting = DbSettingMapper.Get<NpgsqlConnection>();
// Assert
Assert.IsFalse(setting.IsUseUpsert);
}
[TestMethod]
public void TestPostgreSqlDbSettingOpeningQuoteProperty()
{
// Setup
var setting = DbSettingMapper.Get<NpgsqlConnection>();
// Assert
Assert.AreEqual("\"", setting.OpeningQuote);
}
[TestMethod]
public void TestPostgreSqlDbSettingParameterPrefixProperty()
{
// Setup
var setting = DbSettingMapper.Get<NpgsqlConnection>();
// Assert
Assert.AreEqual("@", setting.ParameterPrefix);
}
}
}
| 26.982759 | 79 | 0.577955 | [
"Apache-2.0"
] | Ashrafnet/RepoDB | RepoDb.PostgreSql/RepoDb.PostgreSql.UnitTests/DbSettingTest.cs | 3,132 | C# |
/// Credit GXMark, alexzzzz, CaoMengde777, TroyDavis
/// Original Sourced from (GXMark) - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/page-2#post-1834806 (with corrections)
/// Scaling fixed for non overlay canvases (alexzzzz) - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/#post-1780612
/// Canvas border fix (CaoMengde777) - http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/#post-1781658
/// Canvas reset position fix (TroyDavis)- http://forum.unity3d.com/threads/scripts-useful-4-6-scripts-collection.264161/#post-1782214
using System;
using UnityEngine.EventSystems;
namespace UnityEngine.UI.Extensions
{
/// <summary>
/// Includes a few fixes of my own, mainly to tidy up duplicates, remove unneeded stuff and testing. (nothing major, all the crew above did the hard work!)
/// </summary>
[RequireComponent(typeof(RectTransform))]
[AddComponentMenu("UI/Extensions/UI Window Base")]
public class UIWindowBase : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
private bool _isDragging = false;
public static bool ResetCoords = false;
private Vector3 m_originalCoods = Vector3.zero;
private Canvas m_canvas;
private RectTransform m_canvasRectTransform;
[Tooltip("Number of pixels of the window that must stay inside the canvas view.")]
public int KeepWindowInCanvas = 5;
[Tooltip("The transform that is moved when dragging, can be left empty in which case its own transform is used.")]
public RectTransform RootTransform = null;
// Use this for initialization
void Start()
{
if (RootTransform == null)
{
RootTransform = GetComponent<RectTransform>();
}
m_originalCoods = RootTransform.position;
m_canvas = GetComponentInParent<Canvas>();
m_canvasRectTransform = m_canvas.GetComponent<RectTransform>();
}
void Update()
{
if (ResetCoords)
resetCoordinatePosition();
}
public void OnDrag(PointerEventData eventData)
{
if (_isDragging)
{
var delta = ScreenToCanvas(eventData.position) - ScreenToCanvas(eventData.position - eventData.delta);
RootTransform.localPosition += delta;
}
}
//Note, the begin drag and end drag aren't actually needed to control the drag. However, I'd recommend keeping it in case you want to do something else when dragging starts and stops
public void OnBeginDrag(PointerEventData eventData)
{
if (eventData.pointerCurrentRaycast.gameObject == null)
return;
if (eventData.pointerCurrentRaycast.gameObject.name == name)
{
_isDragging = true;
}
}
public void OnEndDrag(PointerEventData eventData)
{
_isDragging = false;
}
void resetCoordinatePosition()
{
RootTransform.position = m_originalCoods;
ResetCoords = false;
}
private Vector3 ScreenToCanvas(Vector3 screenPosition)
{
Vector3 localPosition;
Vector2 min;
Vector2 max;
var canvasSize = m_canvasRectTransform.sizeDelta;
if (m_canvas.renderMode == RenderMode.ScreenSpaceOverlay || (m_canvas.renderMode == RenderMode.ScreenSpaceCamera && m_canvas.worldCamera == null))
{
localPosition = screenPosition;
min = Vector2.zero;
max = canvasSize;
}
else
{
var ray = m_canvas.worldCamera.ScreenPointToRay(screenPosition);
var plane = new Plane(m_canvasRectTransform.forward, m_canvasRectTransform.position);
float distance;
if (plane.Raycast(ray, out distance) == false)
{
throw new Exception("Is it practically possible?");
};
var worldPosition = ray.origin + ray.direction * distance;
localPosition = m_canvasRectTransform.InverseTransformPoint(worldPosition);
min = -Vector2.Scale(canvasSize, m_canvasRectTransform.pivot);
max = Vector2.Scale(canvasSize, Vector2.one - m_canvasRectTransform.pivot);
}
// keep window inside canvas
localPosition.x = Mathf.Clamp(localPosition.x, min.x + KeepWindowInCanvas, max.x - KeepWindowInCanvas);
localPosition.y = Mathf.Clamp(localPosition.y, min.y + KeepWindowInCanvas, max.y - KeepWindowInCanvas);
return localPosition;
}
}
} | 39.836066 | 191 | 0.626337 | [
"MIT"
] | AustinDreak/Dieselpunk-Audio-Player | Assets/com.unity.uiextensions/Runtime/Scripts/UIWindowBase.cs | 4,862 | C# |
using System.Linq;
using System.Threading.Tasks;
using CodeMash.Client;
using CodeMash.Repository;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MongoDB.Driver;
namespace CodeMash.Core.Tests
{
[TestClass]
public class UpdateOneTests : DatabaseTestBase
{
[TestInitialize]
public override void SetUp()
{
base.SetUp();
var client = new CodeMashClient(ApiKey, ProjectId);
Repository = new CodeMashRepository<SdkEntity>(client);
}
[TestCleanup]
public override void TearDown()
{
if (InsertedRecords != null && InsertedRecords.Any())
{
if (InsertedRecords.ContainsKey(TestContext.TestName))
{
Repository.DeleteOne(InsertedRecords[TestContext.TestName]);
}
}
}
[TestMethod]
public void Can_update_one()
{
var insertedRecord = InsertRecord();
var updateDefinition = Builders<SdkEntity>.Update.Set(x => x.Number, 13);
var updateResult = Repository.UpdateOne(x => x.Id == insertedRecord.Id, updateDefinition);
var updatedRecordFromDb = Repository.FindOne(x => x.Id == insertedRecord.Id);
Assert.IsTrue(updateResult.IsAcknowledged);
Assert.AreEqual(updateResult.ModifiedCount, 1);
Assert.AreEqual(updateResult.MatchedCount, 1);
updatedRecordFromDb.ShouldBe<SdkEntity>();
Assert.AreEqual(updatedRecordFromDb.Notes, insertedRecord.Notes);
Assert.AreEqual(updatedRecordFromDb.Number, 13);
}
[TestMethod]
public async Task Can_update_one_async()
{
var insertedRecord = InsertRecord();
var updateDefinition = Builders<SdkEntity>.Update.Set(x => x.Number, 13);
var updateResult = await Repository.UpdateOneAsync(x => x.Id == insertedRecord.Id, updateDefinition);
var updatedRecordFromDb = await Repository.FindOneAsync(x => x.Id == insertedRecord.Id);
Assert.IsTrue(updateResult.IsAcknowledged);
Assert.AreEqual(updateResult.ModifiedCount, 1);
Assert.AreEqual(updateResult.MatchedCount, 1);
updatedRecordFromDb.ShouldBe<SdkEntity>();
Assert.AreEqual(updatedRecordFromDb.Notes, insertedRecord.Notes);
Assert.AreEqual(updatedRecordFromDb.Number, 13);
}
}
} | 35.90411 | 113 | 0.59443 | [
"MIT"
] | codemash-io/CodeMash.Net | src/CodeMash.Core.Tests/DatabaseTests/Update/UpdateOneTests.cs | 2,621 | C# |
// Instance generated by TankLibHelper.InstanceBuilder
// ReSharper disable All
namespace TankLib.STU.Types {
[STUAttribute(0x33B3D2B6)]
public class STU_33B3D2B6 : STUUXDependencyObject {
[STUFieldAttribute(0xADE95629, "m_items", ReaderType = typeof(EmbeddedInstanceFieldReader))]
public STU_E1D44942[] m_items;
}
}
| 31.454545 | 100 | 0.745665 | [
"MIT"
] | Mike111177/OWLib | TankLib/STU/Types/STU_33B3D2B6.cs | 346 | C# |
using System;
using Rhino.Queues;
using Rhino.Queues.Model;
using Rhino.ServiceBus.Impl;
namespace Rhino.ServiceBus.RhinoQueues
{
[CLSCompliant(false)]
public class RhinoQueueCurrentMessageInformation : CurrentMessageInformation
{
public Uri ListenUri { get; set; }
public IQueue Queue { get; set; }
public Message TransportMessage { get; set; }
}
} | 26 | 80 | 0.710256 | [
"BSD-3-Clause"
] | EzyWebwerkstaden/rhino-esb | Rhino.ServiceBus.RhinoQueues/RhinoQueues/RhinoQueueCurrentMessageInformation.cs | 390 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceModel;
namespace Workday.Compensation
{
[GeneratedCode("System.ServiceModel", "4.0.0.0"), EditorBrowsable(EditorBrowsableState.Advanced), DebuggerStepThrough, MessageContract(IsWrapped = false)]
public class Get_Compensation_Scorecard_ResultsInput
{
[MessageHeader(Namespace = "urn:com.workday/bsvc")]
public Workday_Common_HeaderType Workday_Common_Header;
[MessageBodyMember(Namespace = "urn:com.workday/bsvc", Order = 0)]
public Get_Compensation_Scorecard_Results_RequestType Get_Compensation_Scorecard_Results_Request;
public Get_Compensation_Scorecard_ResultsInput()
{
}
public Get_Compensation_Scorecard_ResultsInput(Workday_Common_HeaderType Workday_Common_Header, Get_Compensation_Scorecard_Results_RequestType Get_Compensation_Scorecard_Results_Request)
{
this.Workday_Common_Header = Workday_Common_Header;
this.Get_Compensation_Scorecard_Results_Request = Get_Compensation_Scorecard_Results_Request;
}
}
}
| 36.931034 | 188 | 0.843137 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.Compensation/Get_Compensation_Scorecard_ResultsInput.cs | 1,071 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CodeMonkey.Utils;
public class SpawnEnemyOnKeyDown : MonoBehaviour {
[SerializeField] private Transform pfEnemyTransform;
private void Update() {
if (Input.GetKeyDown(KeyCode.M)) {
int spawnCount = 5;
Vector3 spawnPosition = Vector3.zero;
float radiusMin = 50f;
float radiusMax = 150f;
for (int i = 0; i < spawnCount; i++) {
Transform enemyTransform = Instantiate(pfEnemyTransform, spawnPosition + UtilsClass.GetRandomDir() * Random.Range(radiusMin, radiusMax), Quaternion.identity);
}
}
}
}
| 30.347826 | 174 | 0.644699 | [
"MIT"
] | Theunisv/StrategyGameDemo | Assets/ExtraPackages/_/Stuff/Scripts/SpawnEnemyOnKeyDown.cs | 700 | C# |
// Copyright (c) 2011 Morten Bakkedal
// This code is published under the MIT License.
using System;
using FuncLib.Optimization;
namespace FuncLib.Functions
{
public partial class Variable
{
public static VariableAssignment operator |(Variable variable, double value)
{
return new VariableAssignment(variable, value);
}
public static VariableConstraint operator <=(Variable variable, double value)
{
return new VariableConstraint(variable, double.NegativeInfinity, value);
}
public static VariableConstraint operator >=(Variable variable, double value)
{
return new VariableConstraint(variable, value, double.PositiveInfinity);
}
public static VariableConstraint operator <=(double value, Variable variable)
{
return variable >= value;
}
public static VariableConstraint operator >=(double value, Variable variable)
{
return variable <= value;
}
public static VariableEqualityConstraint operator ==(Variable variable, double value)
{
return new VariableEqualityConstraint(variable, value);
}
public static VariableEqualityConstraint operator !=(Variable variable, double value)
{
// This operator makes no sence in this context but is required by C#.
throw new InvalidOperationException();
}
public static VariableEqualityConstraint operator ==(double value, Variable variable)
{
return variable == value;
}
public static VariableEqualityConstraint operator !=(double value, Variable variable)
{
// This operator makes no sence in this context but is required by C#.
throw new InvalidOperationException();
}
public override int GetHashCode()
{
// The hash code from Object is fine, but want to get rid of a warning.
return base.GetHashCode();
}
public override bool Equals(object other)
{
// The equality from Object is fine, but want to get rid of a warning.
return base.Equals(other);
}
}
}
| 26.666667 | 87 | 0.738542 | [
"MIT"
] | lionpeloux/FuncLib | src/FuncLib/Functions/Variable.Operators.cs | 1,920 | C# |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tenancy_config/rpc/room_call_billing_rates_svc.proto
#pragma warning disable 1591
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;
namespace HOLMS.Types.TenancyConfig.RPC {
public static partial class RoomCallBillingRatesSvc
{
static readonly string __ServiceName = "holms.types.tenancy_config.rpc.RoomCallBillingRatesSvc";
static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.RoomCallBillingRates> __Marshaller_RoomCallBillingRates = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.RoomCallBillingRates.Parser.ParseFrom);
static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.TenancyConfig.RoomCallBillingRates> __Method_Get = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.TenancyConfig.RoomCallBillingRates>(
grpc::MethodType.Unary,
__ServiceName,
"Get",
__Marshaller_Empty,
__Marshaller_RoomCallBillingRates);
static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.RoomCallBillingRates, global::HOLMS.Types.TenancyConfig.RoomCallBillingRates> __Method_Set = new grpc::Method<global::HOLMS.Types.TenancyConfig.RoomCallBillingRates, global::HOLMS.Types.TenancyConfig.RoomCallBillingRates>(
grpc::MethodType.Unary,
__ServiceName,
"Set",
__Marshaller_RoomCallBillingRates,
__Marshaller_RoomCallBillingRates);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::HOLMS.Types.TenancyConfig.RPC.RoomCallBillingRatesSvcReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of RoomCallBillingRatesSvc</summary>
public abstract partial class RoomCallBillingRatesSvcBase
{
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.RoomCallBillingRates> Get(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.RoomCallBillingRates> Set(global::HOLMS.Types.TenancyConfig.RoomCallBillingRates request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for RoomCallBillingRatesSvc</summary>
public partial class RoomCallBillingRatesSvcClient : grpc::ClientBase<RoomCallBillingRatesSvcClient>
{
/// <summary>Creates a new client for RoomCallBillingRatesSvc</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public RoomCallBillingRatesSvcClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for RoomCallBillingRatesSvc that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public RoomCallBillingRatesSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected RoomCallBillingRatesSvcClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected RoomCallBillingRatesSvcClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::HOLMS.Types.TenancyConfig.RoomCallBillingRates Get(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Get(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.TenancyConfig.RoomCallBillingRates Get(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Get, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.RoomCallBillingRates> GetAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.RoomCallBillingRates> GetAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Get, null, options, request);
}
public virtual global::HOLMS.Types.TenancyConfig.RoomCallBillingRates Set(global::HOLMS.Types.TenancyConfig.RoomCallBillingRates request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Set(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::HOLMS.Types.TenancyConfig.RoomCallBillingRates Set(global::HOLMS.Types.TenancyConfig.RoomCallBillingRates request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_Set, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.RoomCallBillingRates> SetAsync(global::HOLMS.Types.TenancyConfig.RoomCallBillingRates request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return SetAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.RoomCallBillingRates> SetAsync(global::HOLMS.Types.TenancyConfig.RoomCallBillingRates request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_Set, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override RoomCallBillingRatesSvcClient NewInstance(ClientBaseConfiguration configuration)
{
return new RoomCallBillingRatesSvcClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(RoomCallBillingRatesSvcBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_Get, serviceImpl.Get)
.AddMethod(__Method_Set, serviceImpl.Set).Build();
}
}
}
#endregion
| 59.570313 | 296 | 0.758295 | [
"MIT"
] | PietroProperties/holms.platformclient.net | csharp/HOLMS.Platform/HOLMS.Platform/Types/out/RoomCallBillingRatesSvcGrpc.cs | 7,625 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace CodeKicker.BBCode.Core.SyntaxTree
{
public sealed class SequenceNode : SyntaxTreeNode
{
public SequenceNode()
{
}
public SequenceNode(SyntaxTreeNodeCollection subNodes)
: base(subNodes)
{
if (subNodes == null) throw new ArgumentNullException("subNodes");
}
public SequenceNode(IEnumerable<SyntaxTreeNode> subNodes)
: base(subNodes)
{
if (subNodes == null) throw new ArgumentNullException("subNodes");
}
public override string ToHtml()
{
return string.Concat(SubNodes.Select(s => s.ToHtml()).ToArray());
}
public override string ToBBCode()
{
return string.Concat(SubNodes.Select(s => s.ToBBCode()).ToArray());
}
public override string ToText()
{
return string.Concat(SubNodes.Select(s => s.ToText()).ToArray());
}
public override SyntaxTreeNode SetSubNodes(IEnumerable<SyntaxTreeNode> subNodes)
{
if (subNodes == null) throw new ArgumentNullException("subNodes");
return new SequenceNode(subNodes);
}
internal override SyntaxTreeNode AcceptVisitor(SyntaxTreeVisitor visitor)
{
if (visitor == null) throw new ArgumentNullException("visitor");
return visitor.Visit(this);
}
protected override bool EqualsCore(SyntaxTreeNode b)
{
return true;
}
}
}
| 30.730769 | 88 | 0.595119 | [
"MIT"
] | a-witkowski/BBCode.Core | BBCode.Core/SyntaxTree/SequenceNode.cs | 1,600 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace AppCenterSample.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
| 34.5625 | 98 | 0.679024 | [
"MIT"
] | KeiichiHara/AppCenterSample | AppCenterSample/AppCenterSample/AppCenterSample.iOS/AppDelegate.cs | 1,108 | C# |
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
namespace YamlDotNet.Core.Tokens
{
/// <summary>
/// Represents a flow entry event.
/// </summary>
[Serializable]
public class FlowEntry : Token
{
/// <summary>
/// Initializes a new instance of the <see cref="FlowEntry"/> class.
/// </summary>
public FlowEntry()
: this(Mark.Empty, Mark.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FlowEntry"/> class.
/// </summary>
/// <param name="start">The start position of the token.</param>
/// <param name="end">The end position of the token.</param>
public FlowEntry(Mark start, Mark end)
: base(start, end)
{
}
}
} | 39.764706 | 84 | 0.648422 | [
"MIT"
] | bayeslife/api-add-in | APIAddIn/YamlDotNet/Core/Tokens/FlowEntry.cs | 2,028 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using lm.Comol.Core.DomainModel;
namespace lm.Comol.Modules.Standard.Glossary.Domain
{
[Serializable]
public class GlossaryItem : DomainBaseObjectMetaInfo<long>
{
/// <summary>
/// Term.
/// Text Only.
/// </summary>
[Required(ErrorMessage = "*"), StringLength(100, ErrorMessage = "Must be under 100 characters")]
public virtual String Term { get; set; }
/// <summary>
/// Definition of term.
/// Html format, like all other text area.
/// </summary>
[Required(ErrorMessage = "*")]
public virtual String Definition { get; set; }
/// <summary>
/// First letter for filter.
/// To speed-up searches
/// </summary>
public virtual Char FirstLetter { get; set; }
///// <summary>
///// Link Id
///// To connect a term to community or other group of term (to define)
///// </summary>
//public virtual Int32 LinkId { get; set; }
/// <summary>
/// Is public.
/// If this term is visible to entire system (to define)
/// </summary>
public virtual Boolean IsPublic { get; set; }
/// <summary>
/// Group (Glossary)
/// </summary>
public virtual GlossaryGroup Group { get; set; }
/// <summary>
/// Partial link to this term
/// </summary>
public virtual String Link { get; set; }
public virtual Int32 ExportedStatus { get; set; }
public virtual void SetFirstLetter()
{
Char _firstLetter = Term.ToLower().ToCharArray(0, 1)[0];
if (!char.IsLetterOrDigit(_firstLetter))
{
_firstLetter = '_';
}
FirstLetter = _firstLetter;
}
}
}
| 28.376812 | 104 | 0.54954 | [
"MIT"
] | EdutechSRL/Adevico | 3-Business/3-Modules/lm.Comol.Modules.Standard/Glossary/Domain/GlossaryItem.cs | 1,960 | C# |
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet;
using System;
using System.Collections.Generic;
using System.Security.AccessControl;
namespace NtObjectManager.Provider
{
internal abstract class NtObjectContainer : IDisposable
{
private readonly NtObject _obj;
private protected NtObjectContainer(NtObject obj)
{
_obj = obj;
}
public string FullPath => _obj.FullPath;
public SecurityDescriptor SecurityDescriptor => _obj.SecurityDescriptor;
public abstract bool Exists(string path);
public abstract NtResult<NtObjectContainer> Duplicate(bool throw_on_error);
public abstract NtResult<NtObjectContainer> DuplicateForQuery(bool throw_on_error);
public abstract NtResult<NtObjectContainer> Open(string relative_path, bool throw_on_error);
public abstract NtResult<NtObjectContainer> OpenForQuery(string relative_path, bool throw_on_error);
public abstract bool QueryAccessGranted { get; }
public abstract IEnumerable<NtObjectContainerEntry> Query();
public abstract NtObjectContainerEntry GetEntry(string path);
public NtDirectoryEntry CreateEntry(string relative_path, string name, string typename)
{
if (typename.Equals("key", StringComparison.OrdinalIgnoreCase))
{
return new NtKeyEntry(_obj, relative_path, name);
}
return new NtDirectoryEntry(_obj, relative_path, name, typename);
}
public abstract GenericObjectSecurity GetSecurity(string relative_path, AccessControlSections includeSections);
public abstract void SetSecurity(string relative_path, GenericObjectSecurity obj_security);
public abstract NtObject NewItem(string relative_path, string item_type_name, object new_item_value);
public virtual void Dispose()
{
_obj?.Dispose();
}
}
}
| 35.194444 | 119 | 0.715075 | [
"Apache-2.0"
] | HiFiPhile/sandbox-attacksurface-analysis-tools | NtObjectManager/Provider/NtObjectContainer.cs | 2,536 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace AMEC.PCSoftware.RemoteConsole.CrazyHein.MitsubishiControllerWorks
{
/// <summary>
/// about.xaml 的交互逻辑
/// </summary>
public partial class About : Window
{
public About()
{
InitializeComponent();
DataContext = this;
}
public string AssemblyTitle { get; init; } = "Mcvein";
public string Description { get; init; } = "The container of SLMP based diagnostic tool for Mitsubishi PLC.";
public string AssemblyVersion { get; init; } = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
| 28.617647 | 134 | 0.699897 | [
"MIT"
] | CrazyHein/Weltuna | Mcvein/About.xaml.cs | 985 | C# |
using System.Runtime.CompilerServices;
using Microsoft.Gestures;
namespace GestureLibrary
{
public static class HandPoseHelper
{
private static string GetPoseName([CallerMemberName] string propertyName = null)
{
return propertyName;
}
public static HandPose ClosedFist => new HandPose(GetPoseName(),
new FingerPose(new AllFingersContext(),FingerFlexion.Folded));
public static HandPose OpenHand
{
get
{
var fingerContext = new AllFingersContext();
return new HandPose(GetPoseName(),
new PalmPose(Hand.RightHand, PoseDirection.Undefined, PoseDirection.Undefined),
new FingerPose(fingerContext, FingerFlexion.Open),
new FingertipDistanceRelation(fingerContext, RelativeDistance.NotTouching));
}
}
public static HandPose Victory => new HandPose(GetPoseName(),
new FingerPose(new[] { Finger.Index, Finger.Middle }, FingerFlexion.Open),
new FingertipDistanceRelation(Finger.Index, RelativeDistance.NotTouching, Finger.Middle),
new FingerPose(new[] { Finger.Thumb, Finger.Ring, Finger.Pinky }, FingerFlexion.Folded));
public static HandPose BoyScoutGreeting => new HandPose(GetPoseName(),
new FingerPose(new[] { Finger.Index, Finger.Middle }, FingerFlexion.Open),
new FingertipDistanceRelation(Finger.Index, RelativeDistance.Touching, Finger.Middle),
new FingerPose(new[] { Finger.Thumb, Finger.Ring, Finger.Pinky }, FingerFlexion.Folded));
public static HandPose Pinch
{
get
{
var fingerContext = new AllFingersContext();
return new HandPose(GetPoseName(),
new PalmPose(new[] { Hand.RightHand, Hand.LeftHand }, PoseDirection.Forward, PoseDirection.Up),
new FingerPose(fingerContext.Fingers, FingerFlexion.Open),
new FingertipPlacementRelation(new[] { Finger.Middle, Finger.Ring, Finger.Pinky }, RelativePlacement.Above, new[] { Finger.Index, Finger.Thumb }),
new FingertipPlacementRelation(Finger.Index, RelativePlacement.Above, Finger.Thumb),
new FingertipDistanceRelation(new[] { Finger.Index, Finger.Thumb }, RelativeDistance.Touching));
}
}
public static HandPose NotPinch => new HandPose(GetPoseName(),
new PalmPose(new[] { Hand.RightHand, Hand.LeftHand }, PoseDirection.Forward, PoseDirection.Up),
new FingerPose(new[] { Finger.Index, Finger.Thumb }, FingerFlexion.Open),
new FingertipDistanceRelation(new[] { Finger.Index, Finger.Thumb }, RelativeDistance.NotTouching));
public static HandPose RotateSet => new HandPose(GetPoseName(),
new FingerPose(new[] { Finger.Thumb, Finger.Index }, FingerFlexion.Open, PoseDirection.Forward),
new FingertipPlacementRelation(Finger.Index, RelativePlacement.Above, Finger.Thumb),
new FingertipDistanceRelation(Finger.Index, RelativeDistance.NotTouching, Finger.Thumb));
public static HandPose RotateGo => new HandPose(GetPoseName(),
new FingerPose(new[] { Finger.Thumb, Finger.Index }, FingerFlexion.Open, PoseDirection.Forward),
new FingertipPlacementRelation(Finger.Index, RelativePlacement.Right, Finger.Thumb),
new FingertipDistanceRelation(Finger.Index, RelativeDistance.NotTouching, Finger.Thumb));
}
}
| 62.623188 | 166 | 0.548021 | [
"MIT"
] | massimobonanni/ProjectPragueSamples | GestureLibrary/HandPoseHelper.cs | 4,323 | C# |
using System.Linq;
using AutoMapper;
using Abp.Authorization;
using Abp.Authorization.Roles;
using LibraryManagementProject.Authorization.Roles;
namespace LibraryManagementProject.Roles.Dto
{
public class RoleMapProfile : Profile
{
public RoleMapProfile()
{
// Role and permission
CreateMap<Permission, string>().ConvertUsing(r => r.Name);
CreateMap<RolePermissionSetting, string>().ConvertUsing(r => r.Name);
CreateMap<CreateRoleDto, Role>();
CreateMap<RoleDto, Role>();
CreateMap<Role, RoleDto>().ForMember(x => x.GrantedPermissions,
opt => opt.MapFrom(x => x.Permissions.Where(p => p.IsGranted)));
CreateMap<Role, RoleListDto>();
CreateMap<Role, RoleEditDto>();
CreateMap<Permission, FlatPermissionDto>();
}
}
}
| 29.333333 | 81 | 0.627273 | [
"MIT"
] | trailv18/DATN | aspnet-core/src/LibraryManagementProject.Application/Roles/Dto/RoleMapProfile.cs | 880 | C# |
using System;
using AngleSharp.Dom;
using Bunit.Mocking.JSInterop;
using Bunit.SampleComponents;
using Bunit.SampleComponents.Data;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
namespace Bunit.Rendering
{
public class RenderWaitingHelperExtensionsTest : ComponentTestFixture
{
[Fact(DisplayName = "Nodes should return new instance when " +
"async operation during OnInit causes component to re-render")]
[Obsolete("Calls to WaitForNextRender is obsolete, but still needs tests")]
public void Test003()
{
var testData = new AsyncNameDep();
Services.AddSingleton<IAsyncTestDep>(testData);
var cut = RenderComponent<SimpleWithAyncDeps>();
var initialValue = cut.Nodes.QuerySelector("p").TextContent;
var expectedValue = "Steve Sanderson";
WaitForNextRender(() => testData.SetResult(expectedValue));
var steveValue = cut.Nodes.QuerySelector("p").TextContent;
steveValue.ShouldNotBe(initialValue);
steveValue.ShouldBe(expectedValue);
}
[Fact(DisplayName = "Nodes should return new instance when " +
"async operation/StateHasChanged during OnAfterRender causes component to re-render")]
[Obsolete("Calls to WaitForNextRender is obsolete, but still needs tests")]
public void Test004()
{
var invocation = Services.AddMockJsRuntime().Setup<string>("getdata");
var cut = RenderComponent<SimpleWithJsRuntimeDep>();
var initialValue = cut.Nodes.QuerySelector("p").OuterHtml;
WaitForNextRender(() => invocation.SetResult("NEW DATA"));
var steveValue = cut.Nodes.QuerySelector("p").OuterHtml;
steveValue.ShouldNotBe(initialValue);
}
[Fact(DisplayName = "Nodes on a components with child component returns " +
"new instance when the child component has changes")]
[Obsolete("Calls to WaitForNextRender is obsolete, but still needs tests")]
public void Test005()
{
var invocation = Services.AddMockJsRuntime().Setup<string>("getdata");
var notcut = RenderComponent<Wrapper>(ChildContent<Simple1>());
var cut = RenderComponent<Wrapper>(ChildContent<SimpleWithJsRuntimeDep>());
var initialValue = cut.Nodes;
WaitForNextRender(() => invocation.SetResult("NEW DATA"), TimeSpan.FromSeconds(2));
Assert.NotSame(initialValue, cut.Nodes);
}
[Fact(DisplayName = "WaitForRender throws WaitForRenderFailedException when a render does not happen within the timeout period")]
[Obsolete("Calls to WaitForNextRender is obsolete, but still needs tests")]
public void Test006()
{
const string expectedMessage = "No render happened before the timeout period passed.";
var cut = RenderComponent<Simple1>();
var expected = Should.Throw<WaitForRenderFailedException>(() =>
WaitForNextRender(timeout: TimeSpan.FromMilliseconds(10))
);
expected.Message.ShouldBe(expectedMessage);
}
[Fact(DisplayName = "WaitForAssertion can wait for multiple renders and changes to occur")]
public void Test110()
{
// Initial state is stopped
var cut = RenderComponent<TwoRendersTwoChanges>();
var stateElement = cut.Find("#state");
stateElement.TextContent.ShouldBe("Stopped");
// Clicking 'tick' changes the state, and starts a task
cut.Find("#tick").Click();
cut.Find("#state").TextContent.ShouldBe("Started");
// Clicking 'tock' completes the task, which updates the state
// This click causes two renders, thus something is needed to await here.
cut.Find("#tock").Click();
cut.WaitForAssertion(
() => cut.Find("#state").TextContent.ShouldBe("Stopped")
);
}
[Fact(DisplayName = "WaitForAssertion throws verification exception after timeout")]
public void Test011()
{
const string expectedMessage = "The assertion did not pass within the timeout period.";
var cut = RenderComponent<Simple1>();
var expected = Should.Throw<WaitForAssertionFailedException>(() =>
cut.WaitForAssertion(() => cut.Markup.ShouldBeEmpty(), TimeSpan.FromMilliseconds(10))
);
expected.Message.ShouldBe(expectedMessage);
expected.InnerException.ShouldBeOfType<ShouldAssertException>();
}
[Fact(DisplayName = "WaitForState throws WaitForRenderFailedException exception after timeout")]
public void Test012()
{
const string expectedMessage = "The state predicate did not pass before the timeout period passed.";
var cut = RenderComponent<Simple1>();
var expected = Should.Throw<WaitForStateFailedException>(() =>
cut.WaitForState(() => string.IsNullOrEmpty(cut.Markup), TimeSpan.FromMilliseconds(100))
);
expected.Message.ShouldBe(expectedMessage);
expected.InnerException.ShouldBeOfType<TimeoutException>()
.Message.ShouldBe(expectedMessage);
}
[Fact(DisplayName = "WaitForState throws WaitForRenderFailedException exception if statePredicate throws on a later render")]
public void Test013()
{
const string expectedMessage = "The state predicate throw an unhandled exception.";
const string expectedInnerMessage = "INNER MESSAGE";
var cut = RenderComponent<TwoRendersTwoChanges>();
cut.Find("#tick").Click();
cut.Find("#tock").Click();
var expected = Should.Throw<WaitForStateFailedException>(() =>
cut.WaitForState(() =>
{
if (cut.Find("#state").TextContent == "Stopped")
throw new InvalidOperationException(expectedInnerMessage);
return false;
})
);
expected.Message.ShouldBe(expectedMessage);
expected.InnerException.ShouldBeOfType<InvalidOperationException>()
.Message.ShouldBe(expectedInnerMessage);
}
[Fact(DisplayName = "WaitForState can wait for multiple renders and changes to occur")]
public void Test100()
{
// Initial state is stopped
var cut = RenderComponent<TwoRendersTwoChanges>();
var stateElement = cut.Find("#state");
stateElement.TextContent.ShouldBe("Stopped");
// Clicking 'tick' changes the state, and starts a task
cut.Find("#tick").Click();
cut.Find("#state").TextContent.ShouldBe("Started");
// Clicking 'tock' completes the task, which updates the state
// This click causes two renders, thus something is needed to await here.
cut.Find("#tock").Click();
cut.WaitForState(() => cut.Find("#state").TextContent == "Stopped");
cut.Find("#state").TextContent.ShouldBe("Stopped");
}
}
}
| 44.035928 | 137 | 0.62211 | [
"MIT"
] | Siphonophora/bunit | tests/Rendering/RenderWaitingHelperExtensionsTest.cs | 7,356 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Avalonia.Data;
using Avalonia.PropertyStore;
using Avalonia.Utilities;
#nullable enable
namespace Avalonia
{
/// <summary>
/// Stores styled property values for an <see cref="AvaloniaObject"/>.
/// </summary>
/// <remarks>
/// At its core this class consists of an <see cref="AvaloniaProperty"/> to
/// <see cref="IValue"/> mapping which holds the current values for each set property. This
/// <see cref="IValue"/> can be in one of 4 states:
///
/// - For a single local value it will be an instance of <see cref="LocalValueEntry{T}"/>.
/// - For a single value of a priority other than LocalValue it will be an instance of
/// <see cref="ConstantValueEntry{T}"/>`
/// - For a single binding it will be an instance of <see cref="BindingEntry{T}"/>
/// - For all other cases it will be an instance of <see cref="PriorityValue{T}"/>
/// </remarks>
internal class ValueStore : IValueSink
{
private readonly AvaloniaObject _owner;
private readonly IValueSink _sink;
private readonly AvaloniaPropertyValueStore<IValue> _values;
private BatchUpdate? _batchUpdate;
public ValueStore(AvaloniaObject owner)
{
_sink = _owner = owner;
_values = new AvaloniaPropertyValueStore<IValue>();
}
public void BeginBatchUpdate()
{
_batchUpdate ??= new BatchUpdate(this);
_batchUpdate.Begin();
}
public void EndBatchUpdate()
{
if (_batchUpdate is null)
{
throw new InvalidOperationException("No batch update in progress.");
}
if (_batchUpdate.End())
{
_batchUpdate = null;
}
}
public bool IsAnimating(AvaloniaProperty property)
{
if (TryGetValue(property, out var slot))
{
return slot.Priority < BindingPriority.LocalValue;
}
return false;
}
public bool IsSet(AvaloniaProperty property)
{
if (TryGetValue(property, out var slot))
{
return slot.GetValue().HasValue;
}
return false;
}
public bool TryGetValue<T>(
StyledPropertyBase<T> property,
BindingPriority maxPriority,
out T value)
{
if (TryGetValue(property, out var slot))
{
var v = ((IValue<T>)slot).GetValue(maxPriority);
if (v.HasValue)
{
value = v.Value;
return true;
}
}
value = default!;
return false;
}
public IDisposable? SetValue<T>(StyledPropertyBase<T> property, T value, BindingPriority priority)
{
if (property.ValidateValue?.Invoke(value) == false)
{
throw new ArgumentException($"{value} is not a valid value for '{property.Name}.");
}
IDisposable? result = null;
if (TryGetValue(property, out var slot))
{
result = SetExisting(slot, property, value, priority);
}
else if (property.HasCoercion)
{
// If the property has any coercion callbacks then always create a PriorityValue.
var entry = new PriorityValue<T>(_owner, property, this);
AddValue(property, entry);
result = entry.SetValue(value, priority);
}
else
{
if (priority == BindingPriority.LocalValue)
{
AddValue(property, new LocalValueEntry<T>(value));
NotifyValueChanged<T>(property, default, value, priority);
}
else
{
var entry = new ConstantValueEntry<T>(property, value, priority, this);
AddValue(property, entry);
NotifyValueChanged<T>(property, default, value, priority);
result = entry;
}
}
return result;
}
public IDisposable AddBinding<T>(
StyledPropertyBase<T> property,
IObservable<BindingValue<T>> source,
BindingPriority priority)
{
if (TryGetValue(property, out var slot))
{
return BindExisting(slot, property, source, priority);
}
else if (property.HasCoercion)
{
// If the property has any coercion callbacks then always create a PriorityValue.
var entry = new PriorityValue<T>(_owner, property, this);
var binding = entry.AddBinding(source, priority);
AddValue(property, entry);
return binding;
}
else
{
var entry = new BindingEntry<T>(_owner, property, source, priority, this);
AddValue(property, entry);
return entry;
}
}
public void ClearLocalValue<T>(StyledPropertyBase<T> property)
{
if (TryGetValue(property, out var slot))
{
if (slot is PriorityValue<T> p)
{
p.ClearLocalValue();
}
else if (slot.Priority == BindingPriority.LocalValue)
{
var old = TryGetValue(property, BindingPriority.LocalValue, out var value) ? value : default;
// During batch update values can't be removed immediately because they're needed to raise
// a correctly-typed _sink.ValueChanged notification. They instead mark themselves for removal
// by setting their priority to Unset.
if (!IsBatchUpdating())
{
_values.Remove(property);
}
else if (slot is IDisposable d)
{
d.Dispose();
}
else
{
// Local value entries are optimized and contain only a single value field to save space,
// so there's no way to mark them for removal at the end of a batch update. Instead convert
// them to a constant value entry with Unset priority in the event of a local value being
// cleared during a batch update.
var sentinel = new ConstantValueEntry<T>(property, default, BindingPriority.Unset, _sink);
_values.SetValue(property, sentinel);
}
NotifyValueChanged<T>(property, old, default, BindingPriority.Unset);
}
}
}
public void CoerceValue<T>(StyledPropertyBase<T> property)
{
if (TryGetValue(property, out var slot))
{
if (slot is PriorityValue<T> p)
{
p.UpdateEffectiveValue();
}
}
}
public Diagnostics.AvaloniaPropertyValue? GetDiagnostic(AvaloniaProperty property)
{
if (TryGetValue(property, out var slot))
{
var slotValue = slot.GetValue();
return new Diagnostics.AvaloniaPropertyValue(
property,
slotValue.HasValue ? slotValue.Value : AvaloniaProperty.UnsetValue,
slot.Priority,
null);
}
return null;
}
void IValueSink.ValueChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
if (_batchUpdate is object)
{
if (change.IsEffectiveValueChange)
{
NotifyValueChanged<T>(change.Property, change.OldValue, change.NewValue, change.Priority);
}
}
else
{
_sink.ValueChanged(change);
}
}
void IValueSink.Completed<T>(
StyledPropertyBase<T> property,
IPriorityValueEntry entry,
Optional<T> oldValue)
{
// We need to include remove sentinels here so call `_values.TryGetValue` directly.
if (_values.TryGetValue(property, out var slot) && slot == entry)
{
if (_batchUpdate is null)
{
_values.Remove(property);
_sink.Completed(property, entry, oldValue);
}
else
{
_batchUpdate.ValueChanged(property, oldValue.ToObject());
}
}
}
private IDisposable? SetExisting<T>(
object slot,
StyledPropertyBase<T> property,
T value,
BindingPriority priority)
{
IDisposable? result = null;
if (slot is IPriorityValueEntry<T> e)
{
var priorityValue = new PriorityValue<T>(_owner, property, this, e);
_values.SetValue(property, priorityValue);
result = priorityValue.SetValue(value, priority);
}
else if (slot is PriorityValue<T> p)
{
result = p.SetValue(value, priority);
}
else if (slot is LocalValueEntry<T> l)
{
if (priority == BindingPriority.LocalValue)
{
var old = l.GetValue(BindingPriority.LocalValue);
l.SetValue(value);
NotifyValueChanged<T>(property, old, value, priority);
}
else
{
var priorityValue = new PriorityValue<T>(_owner, property, this, l);
if (IsBatchUpdating())
priorityValue.BeginBatchUpdate();
result = priorityValue.SetValue(value, priority);
_values.SetValue(property, priorityValue);
}
}
else
{
throw new NotSupportedException("Unrecognised value store slot type.");
}
return result;
}
private IDisposable BindExisting<T>(
object slot,
StyledPropertyBase<T> property,
IObservable<BindingValue<T>> source,
BindingPriority priority)
{
PriorityValue<T> priorityValue;
if (slot is IPriorityValueEntry<T> e)
{
priorityValue = new PriorityValue<T>(_owner, property, this, e);
if (IsBatchUpdating())
{
priorityValue.BeginBatchUpdate();
}
}
else if (slot is PriorityValue<T> p)
{
priorityValue = p;
}
else if (slot is LocalValueEntry<T> l)
{
priorityValue = new PriorityValue<T>(_owner, property, this, l);
}
else
{
throw new NotSupportedException("Unrecognised value store slot type.");
}
var binding = priorityValue.AddBinding(source, priority);
_values.SetValue(property, priorityValue);
priorityValue.UpdateEffectiveValue();
return binding;
}
private void AddValue(AvaloniaProperty property, IValue value)
{
_values.AddValue(property, value);
if (IsBatchUpdating() && value is IBatchUpdate batch)
batch.BeginBatchUpdate();
value.Start();
}
private void NotifyValueChanged<T>(
AvaloniaProperty<T> property,
Optional<T> oldValue,
BindingValue<T> newValue,
BindingPriority priority)
{
if (_batchUpdate is null)
{
_sink.ValueChanged(new AvaloniaPropertyChangedEventArgs<T>(
_owner,
property,
oldValue,
newValue,
priority));
}
else
{
_batchUpdate.ValueChanged(property, oldValue.ToObject());
}
}
private bool IsBatchUpdating() => _batchUpdate?.IsBatchUpdating == true;
private bool TryGetValue(AvaloniaProperty property, [MaybeNullWhen(false)] out IValue value)
{
return _values.TryGetValue(property, out value) && !IsRemoveSentinel(value);
}
private static bool IsRemoveSentinel(IValue value)
{
// Local value entries are optimized and contain only a single value field to save space,
// so there's no way to mark them for removal at the end of a batch update. Instead a
// ConstantValueEntry with a priority of Unset is used as a sentinel value.
return value is IConstantValueEntry t && t.Priority == BindingPriority.Unset;
}
private class BatchUpdate
{
private ValueStore _owner;
private List<Notification>? _notifications;
private int _batchUpdateCount;
private int _iterator = -1;
public BatchUpdate(ValueStore owner) => _owner = owner;
public bool IsBatchUpdating => _batchUpdateCount > 0;
public void Begin()
{
if (_batchUpdateCount++ == 0)
{
var values = _owner._values;
for (var i = 0; i < values.Count; ++i)
{
(values[i] as IBatchUpdate)?.BeginBatchUpdate();
}
}
}
public bool End()
{
if (--_batchUpdateCount > 0)
return false;
var values = _owner._values;
// First call EndBatchUpdate on all bindings. This should cause the active binding to be subscribed
// but notifications will still not be raised because the owner ValueStore will still have a reference
// to this batch update object.
for (var i = 0; i < values.Count; ++i)
{
(values[i] as IBatchUpdate)?.EndBatchUpdate();
// Somehow subscribing to a binding caused a new batch update. This shouldn't happen but in case it
// does, abort and continue batch updating.
if (_batchUpdateCount > 0)
return false;
}
if (_notifications is object)
{
// Raise all batched notifications. Doing this can cause other notifications to be added and even
// cause a new batch update to start, so we need to handle _notifications being modified by storing
// the index in field.
_iterator = 0;
for (; _iterator < _notifications.Count; ++_iterator)
{
var entry = _notifications[_iterator];
if (values.TryGetValue(entry.property, out var slot))
{
var oldValue = entry.oldValue;
var newValue = slot.GetValue();
// Raising this notification can cause a new batch update to be started, which in turn
// results in another change to the property. In this case we need to update the old value
// so that the *next* notification has an oldValue which follows on from the newValue
// raised here.
_notifications[_iterator] = new Notification
{
property = entry.property,
oldValue = newValue,
};
// Call _sink.ValueChanged with an appropriately typed AvaloniaPropertyChangedEventArgs<T>.
slot.RaiseValueChanged(_owner._sink, _owner._owner, entry.property, oldValue, newValue);
// During batch update values can't be removed immediately because they're needed to raise
// the _sink.ValueChanged notification. They instead mark themselves for removal by setting
// their priority to Unset. We need to re-read the slot here because raising ValueChanged
// could have caused it to be updated.
if (values.TryGetValue(entry.property, out var updatedSlot) &&
updatedSlot.Priority == BindingPriority.Unset)
{
values.Remove(entry.property);
}
}
else
{
throw new AvaloniaInternalException("Value could not be found at the end of batch update.");
}
// If a new batch update was started while ending this one, abort.
if (_batchUpdateCount > 0)
return false;
}
}
_iterator = int.MaxValue - 1;
return true;
}
public void ValueChanged(AvaloniaProperty property, Optional<object> oldValue)
{
_notifications ??= new List<Notification>();
for (var i = 0; i < _notifications.Count; ++i)
{
if (_notifications[i].property == property)
{
oldValue = _notifications[i].oldValue;
_notifications.RemoveAt(i);
if (i <= _iterator)
--_iterator;
break;
}
}
_notifications.Add(new Notification
{
property = property,
oldValue = oldValue,
});
}
private struct Notification
{
public AvaloniaProperty property;
public Optional<object> oldValue;
}
}
}
}
| 36.873541 | 120 | 0.497652 | [
"MIT"
] | 0x90d/Avalonia | src/Avalonia.Base/ValueStore.cs | 18,955 | C# |
using System;
using System.Web;
using System.Web.Routing;
using UserJourneyRecorderWebApp.Infrastructure;
namespace UserJourneyRecorderWebApp
{
public class UserJourneyRecorderWebApplication : HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
var routeHandler = new UserJourneyRecorderRouteHandler();
var route = new Route("stream", routeHandler);
RouteTable.Routes.Add(string.Empty, route);
}
}
}
| 27.944444 | 69 | 0.701789 | [
"MIT"
] | Azure-Samples/active-directory-b2c-advanced-policies | UserJourneyRecorder/UserJourneyRecorderWebApp/Global.asax.cs | 505 | C# |
using System;
namespace Nez
{
/// <summary>
/// Renderer that renders using its own Camera which doesnt move.
/// </summary>
public class ScreenSpaceRenderer : Renderer
{
public int[] renderLayers;
public ScreenSpaceRenderer( int renderOrder, params int[] renderLayers ) : base( renderOrder, null )
{
Array.Sort( renderLayers );
Array.Reverse( renderLayers );
this.renderLayers = renderLayers;
wantsToRenderAfterPostProcessors = true;
}
public override void render( Scene scene )
{
beginRender( camera );
for( var i = 0; i < renderLayers.Length; i++ )
{
var renderables = scene.renderableComponents.componentsWithRenderLayer( renderLayers[i] );
for( var j = 0; j < renderables.length; j++ )
{
var renderable = renderables.buffer[j];
if( renderable.enabled && renderable.isVisibleFromCamera( camera ) )
renderAfterStateCheck( renderable, camera );
}
}
if( shouldDebugRender && Core.debugRenderEnabled )
debugRender( scene, camera );
endRender();
}
public override void onSceneBackBufferSizeChanged( int newWidth, int newHeight )
{
base.onSceneBackBufferSizeChanged( newWidth, newHeight );
// this is a bit of a hack. we maybe should take the Camera in the constructor
if( camera == null )
camera = Core.scene.createEntity( "screenspace camera" ).addComponent<Camera>();
}
}
}
| 24.473684 | 102 | 0.690323 | [
"MIT"
] | Blucky87/Nez | Nez.Portable/Graphics/Renderers/ScreenSpaceRenderer.cs | 1,397 | C# |
#nullable disable
namespace NadekoBot.Modules.Games.Hangman;
public sealed class HangmanTerm
{
public string Word { get; set; }
public string ImageUrl { get; set; }
} | 21.875 | 42 | 0.731429 | [
"MIT"
] | StefanPuia/nadeko | src/NadekoBot/Modules/Games/Hangman/HangmanTerm.cs | 175 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Web.Areas.HelpPage.ModelDescriptions;
using Web.Areas.HelpPage.Models;
namespace Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config,
IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof (IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType,
string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator()
.ActionSamples.Add(
new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] {"*"}),
sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType,
string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator()
.ActionSamples.Add(
new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames),
sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample,
MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator()
.ActionSamples.Add(
new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] {"*"}),
sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample,
MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator()
.ActionSamples.Add(
new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName,
parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample,
MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType,
Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName,
string actionName)
{
config.GetHelpPageSampleGenerator()
.ActualHttpMessageTypes.Add(
new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] {"*"}), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName,
string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator()
.ActualHttpMessageTypes.Add(
new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName,
string actionName)
{
config.GetHelpPageSampleGenerator()
.ActualHttpMessageTypes.Add(
new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] {"*"}), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName,
string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator()
.ActualHttpMessageTypes.Add(
new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator) config.Properties.GetOrAdd(
typeof (HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config,
HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof (HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator) config.Properties.GetOrAdd(
typeof (ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription =
apiDescriptions.FirstOrDefault(
api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel) model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() {Documentation = "Required"});
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation()
{
Documentation =
"Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture)
});
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof (string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof (string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel,
ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof (HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel,
ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof (void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config,
out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null &&
p.ParameterDescriptor.ParameterType == typeof (HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof (HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
} | 48.694118 | 174 | 0.603044 | [
"MIT"
] | akaver/ASP.NET-WebApiDal | WebApiDal/Web/Areas/HelpPage/HelpPageConfigurationExtensions.cs | 24,834 | C# |
namespace DemandForecasting.Model
{
using DemandForecasting.Convertor;
using System.ComponentModel;
[TypeConverter(typeof(EnumDescriptionTypeConverter))]
public enum ForecastingTechniques
{
[Description("Simple moving average")]
SimpleMovingAverage,
[Description("Weighted moving average")]
WeightedMovingAverage,
[Description("Simple exponentiel smoothinh")]
SimpleExponentielSmoothinh,
[Description("Holt's procedure")]
HoltProcedure
}
}
/*
*
* 1/ Simple moving average = moyenne mobile simple
( in a moving average, the forecast would be calculated as the average of the last few observation
2/ Weighted moving average methods= Moyenne mobile pondérée
(This methods aims at forecasting the future value of sales on the basis of weights given to the most recent observations.)
3/Simple exponentiel smoothinh = lissage exponentiel simple
( A popular way to capture the benefit of the weighted moving average approach while keeping the forecasting procedure simple and easy to use is called exponential smoothing, or occasionally, the exponentially weighted moving average)
4/ Holt's procedure = Lissage de Holt
(Holt’s procedure is a popular technique that is also used to forecast demand data with asimple linear trend. The procedure works by separating the "temporary level", or currentheight of the series, from the trend in the data and developing a smoothed estimate of each component.)
*/ | 43.911765 | 280 | 0.762224 | [
"MIT"
] | hamdiChehdi/Demand-Forecasting | DemandForecasting/Model/ForecastingTechniques.cs | 1,499 | C# |
using System;
using System.Collections.Generic;
using Microsoft.Build.Logging.StructuredLogger;
namespace StructuredLogViewer
{
public class SearchResult
{
public BaseNode Node { get; }
public List<(string field, string match)> WordsInFields = new List<(string, string)>();
public bool MatchedByType { get; private set; }
public TimeSpan Duration { get; set; }
public SearchResult(BaseNode node, bool includeDuration = false)
{
Node = node;
if (includeDuration && node is TimedNode timedNode)
{
Duration = timedNode.Duration;
}
}
public void AddMatch(string field, string word, bool addAtBeginning = false)
{
if (addAtBeginning)
{
WordsInFields.Insert(0, (field, word));
}
else
{
WordsInFields.Add((field, word));
}
}
public void AddMatchByNodeType()
{
MatchedByType = true;
}
}
}
| 26.761905 | 96 | 0.525801 | [
"MIT"
] | laurenprinn/MSBuildStructuredLog | src/StructuredLogViewer.Core/SearchResult.cs | 1,126 | C# |
using System.Diagnostics;
using System.Threading;
using JetBlack.Diagnostics.Monitoring;
using NUnit.Framework;
namespace JetBlack.Diagnostics.Test.Monitoring
{
[TestFixture]
public class ElapsedTimeFixture
{
[Test]
public void Test()
{
const string categoryName = "TestCategory";
const string categoryHelp = "Test category help";
const PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.SingleInstance;
const string counterName = "TestElapsedTime";
const string counterHelp = "Test elapsed time";
if (!PerformanceCounterCategory.Exists(categoryName))
{
var counterCreationData = new CounterCreationDataCollection(ElapsedTime.CounterCreator.CreateCounterData(counterName, counterHelp));
var category = PerformanceCounterCategory.Create(categoryName, categoryHelp, categoryType, counterCreationData);
}
var elapsedTime = new ElapsedTime(PerformanceCounterFactory.Singleton, categoryName, "TestElapsedTime", false);
elapsedTime.Reset();
var count = 0;
while (++count < 10)
{
Thread.Sleep(1000);
var value = elapsedTime.NextValue();
Debug.Print("Value = {0}", value);
}
elapsedTime.Dispose();
PerformanceCounterCategory.Delete(categoryName);
}
}
}
| 35.928571 | 148 | 0.631544 | [
"MIT"
] | rob-blackbourn/JetBlack.Diagnostics | JetBlack.Diagnostics.Test/Monitoring/ElapsedTimeFixture.cs | 1,511 | C# |
/************************************************************************
AvalonDock
Copyright (C) 2007-2013 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at https://opensource.org/licenses/MS-PL
************************************************************************/
using System;
namespace WinIO.Themes
{
/// <inheritdoc/>
public class GenericTheme : Theme
{
/// <inheritdoc/>
public override Uri GetResourceUri()
{
return new Uri("/WinIO;component/Themes/Generic.xaml", UriKind.Relative);
}
}
} | 28.304348 | 85 | 0.499232 | [
"Apache-2.0"
] | sak9188/WinIO2 | WinIO/WinIO/Themes/GenericTheme.cs | 651 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
namespace ImportAndCompare
{
class Program
{
static void Main(string[] args)
{
try
{
ProcessBibleProtector();
//ProcessProjectGutenbergB();
//ProcessKjvRaw();
//ProcessIfbWeb();
//ProcessSwordSearcher();
//ProcessProjectGutenbergA();
Console.WriteLine("Done.");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadKey();
}
public static void ProcessBibleProtector()
{
var verses = BibleProtector.Import(File.ReadAllLines(@"..\..\..\BibleProtector\TEXT-PCE.txt", Encoding.GetEncoding(1252)));
verses.VerifyPunctuation();
Export(verses, "PCE");
Stats(verses);
//foreach (var word in verses.SelectMany(x => x.Words).Where(x => char.IsLetter(x[0])).Distinct())
//{
// if (!word.All(char.IsUpper) && !word.All(char.IsLower) && (!char.IsUpper(word[0]) || !word.Skip(1).All(char.IsLower)))
// Console.WriteLine(word);
//}
}
public static void ProcessKjvRaw()
{
var verses = KjvRaw.Import(File.ReadAllLines(@"..\..\..\Textfile 930105\kjv.raw.txt"));
Export(verses, "RAW");
Stats(verses);
}
public static void ProcessIfbWeb()
{
var verses = IfbWeb.Import(File.ReadAllLines(@"..\..\..\printkjv.ifbweb.com\AV1611Bible.txt"));
Export(verses, "IFB");
Stats(verses);
}
public static void ProcessProjectGutenbergA()
{
var verses = ProjectGutenbergA.Import(File.ReadAllLines(@"..\..\..\Gutenberg-A\pg10.txt"));
Export(verses, "PGA");
Stats(verses);
}
public static void ProcessProjectGutenbergB()
{
var verses = ProjectGutenbergA.Import(File.ReadAllLines(@"..\..\..\Gutenberg-B\bible13.txt"));
Export(verses, "PGB");
Stats(verses);
}
public static void ProcessSwordSearcher()
{
var verses = SwordSearcher.Import(File.ReadAllLines(@"..\..\..\SS5\SS5.txt"));
Export(verses, "SS5");
Stats(verses);
}
public static void Export(IReadOnlyList<Verse> verses, string prefix)
{
checked
{
File.WriteAllLines(prefix + ".standard.txt", verses.Select(x => x.Words.PunctuatedText()));
File.WriteAllLines(prefix + ".simple.txt", verses.Select(x => x.Words.Select(y => y.ToLower()).UnpunctuatedText()));
//File.WriteAllLines(prefix + ".full.txt", verses.Select(x => x.Book + " " + x.Chapter + ":" + x.VerseNumber + " " + x.Words.PunctuatedText()));
var utf8 = new UTF8Encoding(false);
var words = verses.SelectMany(x => x.Words).Where(x => char.IsLetter(x[0])).Select(x => x.ToLower()).Distinct().OrderBy(x => x).ToList();
var punctuation = verses.SelectMany(x => x.Words).Where(x => !char.IsLetter(x[0])).Distinct().OrderBy(x => x).ToList();
var punctuationJson = JsonConvert.SerializeObject(punctuation.Select(x => x.Replace("`", "'s")), Formatting.None);
File.WriteAllText("punctuation.js", "define(function () { return " + punctuationJson + "; });", utf8);
File.WriteAllText("Constants.Punctuation.cs", "namespace PewBibleKjv.Text {\npublic static partial class Constants {\npublic static readonly string[] Punctuation = " + CSharpSerialize(punctuation.Select(x => x.Replace("`", "'s"))) + ";\n}\n}");
var wordsJson = JsonConvert.SerializeObject(words, Formatting.None);
File.WriteAllText("words.js", "define(function () { return " + wordsJson + "; });", utf8);
File.WriteAllText("Constants.Words.cs", "namespace PewBibleKjv.Text {\npublic static partial class Constants {\npublic static readonly string[] Words = " + CSharpSerialize(words) + ";\n}\n}");
var structure = verses.Structure();
var jsonStructure = JsonConvert.SerializeObject(structure.Books, Formatting.None);
File.WriteAllText("structure.js", "define(function () { return " + jsonStructure + "; });", utf8);
File.WriteAllText("Structure.cs", "namespace PewBibleKjv.Text {\npublic static class Structure {\npublic static readonly Book[] Books = " + CSharpSerialize(structure) + ";\n}\n}");
var verseIndex = new List<int>();
using (var dataFile = new FileStream("verses.dat", FileMode.Create))
{
foreach (var verse in verses)
{
verseIndex.Add((int)(dataFile.Position / 2));
foreach (var word in verse.Words)
{
var wordIndex = words.BinarySearch(word.ToLower());
if (wordIndex >= 0)
{
int wordFlags = 0;
if (word.All(char.IsUpper))
wordFlags = 1;
else if (char.IsUpper(word[0]) && word.Skip(1).All(char.IsLower))
wordFlags = 2;
else if (char.IsUpper(word[0]) && char.IsUpper(word[1]) && word.Skip(2).All(char.IsLower))
wordFlags = 3;
else if (!word.All(char.IsLower))
throw new InvalidOperationException("Odd word " + word);
dataFile.Write(BitConverter.GetBytes((ushort)((wordFlags << 14) | wordIndex)), 0, 2);
}
else
{
var punctIndex = punctuation.BinarySearch(word);
if (punctIndex < 0)
throw new InvalidOperationException("Impossible things are happening every day!");
dataFile.Write(BitConverter.GetBytes((ushort)(words.Count + punctIndex)), 0, 2);
}
}
}
verseIndex.Add((int)(dataFile.Position / 2));
}
var verseIndexJson = JsonConvert.SerializeObject(verseIndex, Formatting.None);
File.WriteAllText("verseIndex.js", "define(function () { return " + verseIndexJson + "; });", utf8);
File.WriteAllBytes("verseIndex.dat", verseIndex.SelectMany(BitConverter.GetBytes).ToArray());
var concordance = new List<int>[words.Count];
for (var i = 0; i != concordance.Length; ++i)
concordance[i] = new List<int>();
for (var i = 0; i != verses.Count; ++i)
{
var verse = verses[i];
foreach (var word in verse.Words)
{
var wordIndex = words.BinarySearch(word.ToLower());
if (wordIndex < 0)
continue;
concordance[wordIndex].Add(i);
}
}
var cWordIndex = new List<int>();
using (var dataFile = new FileStream("concordance.dat", FileMode.Create))
{
foreach (var cWord in concordance)
{
cWordIndex.Add((int)(dataFile.Position / 2));
foreach (var verseNumber in cWord)
{
dataFile.Write(BitConverter.GetBytes((ushort)verseNumber), 0, 2);
}
}
cWordIndex.Add((int)(dataFile.Position / 2));
}
var cWordIndexJson = JsonConvert.SerializeObject(cWordIndex, Formatting.None);
File.WriteAllText("concordanceIndex.js", "define(function () { return " + cWordIndexJson + "; });", utf8);
}
}
public static void Stats(IReadOnlyList<Verse> verses)
{
Console.WriteLine("Books: " + verses.NumberOfBooks());
Console.WriteLine("Verses: " + verses.Count);
Console.WriteLine("Words: " + verses.NumberOfWords());
Console.WriteLine("CIWords: " + verses.NumberOfCaseInsensitiveWords());
Console.WriteLine("Punct: " + verses.NumberOfPunctuation());
Console.WriteLine("Total text: " + verses.SelectMany(x => x.Words).Count());
}
private static string CSharpSerialize(object obj)
{
if (obj is string || obj is int)
{
return JsonConvert.SerializeObject(obj);
}
if (obj is IEnumerable enumerable)
{
return "{\n" + string.Join(",\n", enumerable.Cast<object>().Select(CSharpSerialize)) + "\n}";
}
if (obj is Structure structure)
{
return $"{CSharpSerialize(structure.Books)}";
}
if (obj is Book book)
{
return $"new Book({book.Index}, {CSharpSerialize(book.Name)}, {book.BeginVerse}, {book.EndVerse}, new[] {CSharpSerialize(book.Chapters)})";
}
if (obj is Chapter chapter)
{
return $"new Chapter({chapter.Index}, {chapter.BeginVerse}, {chapter.EndVerse})";
}
throw new InvalidOperationException($"Can't serialize type {obj.GetType().Name} to C#");
}
}
}
| 46.934884 | 260 | 0.508275 | [
"MIT"
] | StephenClearyApps/PewBible | Import/ImportAndCompare/Program.cs | 10,093 | C# |
using System;
using System.Linq;
using Eto.Parse.Parsers;
using System.IO;
using System.CodeDom.Compiler;
using Eto.Parse.Writers;
using System.Globalization;
namespace Eto.Parse.Grammars
{
/// <summary>
/// Grammar to build a parser grammar using Gold Meta-Language
/// </summary>
/// <remarks>
/// See http://goldparser.org/doc/grammars/
///
/// This grammar is not thread-safe.
/// </remarks>
public class GoldGrammar : Grammar
{
GoldDefinition definition;
readonly Parser parameter;
readonly Parser ruleDecl;
readonly Parser handle;
readonly Parser symbol;
readonly Parser terminalDecl;
readonly Parser setDecl;
readonly Parser whitespace;
readonly Parser regExpItem;
readonly Parser regExp;
public GoldGrammar()
: base("gold")
{
var oldSeparator = Parser.DefaultSeparator;
// Special Terminals
var parameterCh = Terminals.Printable - Terminals.Set("\"'");
var nonterminalCh = Terminals.LetterOrDigit | Terminals.Set("_-. ");
var terminalCh = Terminals.LetterOrDigit | Terminals.Set("_-.");
var literalCh = Terminals.Printable - Terminals.Set('\'');
var setLiteralCh = Terminals.Printable - Terminals.Set("[]'");
var setNameCh = Terminals.Printable - Terminals.Set("{}");
var parameterName = ('"' & (+parameterCh).WithName("value") & '"').Separate();
var nonterminal = ('<' & (+nonterminalCh).WithName("value") & '>').Separate();
var terminal = ((+terminalCh).WithName("terminal") | ('\'' & (-literalCh).WithName("literal") & '\'')).Separate();
var setLiteral = ('[' & +(setLiteralCh.WithName("ch") | '\'' & (-literalCh).WithName("ch") & '\'') & ']').WithName("setLiteral");
var setName = ('{' & (+setNameCh).WithName("value") & '}').WithName("setName");
// Line-Based Grammar Declarations
var comments = new GroupParser("!*", "*!", "!");
var newline = Terminals.Eol;
whitespace = -(Terminals.SingleLineWhiteSpace | comments);
Parser.DefaultSeparator = whitespace;
var nlOpt = -newline;
var nl = +newline | Terminals.End;
// Parameter Definition
var parameterItem = parameterName | terminal | setLiteral | setName | nonterminal;
var parameterItems = +parameterItem;
var parameterBody = parameterItems & -(nlOpt & '|' & parameterItems);
parameter = (parameterName.Named("name") & nlOpt & '=' & parameterBody.WithName("body") & nl).WithName("parameter");
// Set Definition
var setItem = setLiteral | setName;
var setExp = new AlternativeParser { Name = "setExp" };
setExp.Add((setExp & nlOpt & '+' & setItem).WithName("add"),
(setExp & nlOpt & '-' & setItem).WithName("sub"),
setItem);
setDecl = (setName & nlOpt & '=' & setExp & nl).WithName("setDecl");
// Terminal Definition
var regExp2 = new SequenceParser();
var kleeneOpt = (~((Parser)'+' | '?' | '*')).WithName("kleene");
regExpItem = ((setLiteral & kleeneOpt)
| (setName & kleeneOpt)
| (terminal.Named("terminal") & kleeneOpt)
| ('(' & regExp2.Named("regExp2") & ')' & kleeneOpt)).WithName("regExpItem");
var regExpSeq = (+regExpItem).WithName("regExpSeq");
regExp2.Items.Add(regExpSeq);
regExp2.Items.Add(-('|' & regExpSeq));
regExp = (regExpSeq & -(nlOpt & '|' & regExpSeq)).WithName("regExp");
var terminalName = +terminal;
terminalDecl = (terminalName.Named("name") & nlOpt & '=' & regExp & nl).WithName("terminalDecl");
// Rule Definition
symbol = (terminal.Named("terminal") | nonterminal.Named("nonterminal")).WithName("symbol");
handle = (-symbol).WithName("handle");
var handles = handle & -(nlOpt & '|' & handle);
ruleDecl = (nonterminal.Named("name") & nlOpt & "::=" & handles & nl).WithName("ruleDecl");
// Rules
var definitionDecl = parameter | setDecl | terminalDecl | ruleDecl;
var content = -definitionDecl;
this.Inner = nlOpt & content & nlOpt;
Parser.DefaultSeparator = oldSeparator;
AttachEvents();
}
void AttachEvents()
{
// attach logic to parsers
parameter.PreMatch += m => {
var name = m["name"]["value"].Text;
var value = m["body"].Text;
definition.Properties[name] = value;
bool val;
if (string.Equals("Auto Whitespace", name, StringComparison.OrdinalIgnoreCase) && bool.TryParse(value, out val) && !val)
definition.Whitespace = null;
};
ruleDecl.Matched += m => {
var name = m["name"]["value"].Text;
bool addWhitespace = name == definition.GrammarName;
var parser = Alternative(m, "handle", r => Sequence(r, "symbol", Symbol, addWhitespace));
definition.Rules[name].Inner = parser;
};
ruleDecl.PreMatch += m => {
var name = m["name"]["value"].Text;
UnaryParser parser;
if (name == definition.GrammarName)
parser = new Grammar(name);
else
parser = new UnaryParser(name);
definition.Rules.Add(parser.Name, parser);
};
terminalDecl.Matched += m => {
var inner = Sequence(m, "regExp", RegExp);
var parser = m.Tag as UnaryParser;
if (parser != null)
parser.Inner = inner;
var groupParser = m.Tag as GroupParser;
var name = m["name"].Text;
if (groupParser != null)
{
if (name.EndsWith(" Start", StringComparison.Ordinal))
groupParser.Start = inner;
else if (name.EndsWith(" End", StringComparison.Ordinal))
groupParser.End = inner;
else if (name.EndsWith(" Line", StringComparison.Ordinal))
groupParser.Line = inner;
var count = name.EndsWith(" Start", StringComparison.Ordinal) ? 6 : name.EndsWith(" Line", StringComparison.Ordinal) ? 5 : name.EndsWith(" End", StringComparison.Ordinal) ? 4 : 0;
name = name.Substring(0, name.Length - count);
}
if (name.Equals("Comment", StringComparison.OrdinalIgnoreCase)
|| name.Equals("Whitespace", StringComparison.OrdinalIgnoreCase)
)
{
definition.ClearSeparator();
}
};
terminalDecl.PreMatch += m => {
var name = m["name"].Text;
if (name.EndsWith(" Start", StringComparison.Ordinal) || name.EndsWith(" End", StringComparison.Ordinal) || name.EndsWith(" Line", StringComparison.Ordinal))
{
Parser parser;
var count = name.EndsWith(" Start", StringComparison.Ordinal) ? 6 : name.EndsWith(" Line", StringComparison.Ordinal) ? 5 : name.EndsWith(" End", StringComparison.Ordinal) ? 4 : 0;
name = name.Substring(0, name.Length - count);
if (definition.Terminals.TryGetValue(name, out parser))
{
parser = parser as GroupParser ?? new GroupParser();
}
else
parser = new GroupParser();
m.Tag = definition.Terminals[name] = parser;
}
else
m.Tag = definition.Terminals[name] = new UnaryParser(name);
};
setDecl.PreMatch += m => {
var parser = SetMatch(m["setExp"]);
definition.Sets[m["setName"]["value"].Text] = parser;
m.Tag = parser;
};
}
static Parser Alternative(Match m, string innerName, Func<Match, Parser> inner)
{
var parsers = m.Find(innerName).Select(inner).ToArray();
if (parsers.Length > 1)
return new AlternativeParser(parsers);
return parsers.FirstOrDefault();
}
Parser Sequence(Match m, string innerName, Func<Match, Parser> inner, bool addWhitespace = false)
{
var parsers = m.Find(innerName).Select(inner).ToArray();
if (addWhitespace || parsers.Length > 1)
{
var sep = definition.Separator;
var seq = new SequenceParser(parsers) { Separator = sep };
if (addWhitespace && sep != null)
{
seq.Items.Insert(0, sep);
seq.Items.Add(sep);
}
return seq;
}
return parsers.FirstOrDefault();
}
Parser Symbol(Match m)
{
var child = m["nonterminal"];
if (child.Success)
{
var name = child["value"].Text;
UnaryParser parser;
if (!definition.Rules.TryGetValue(name, out parser))
throw new FormatException(string.Format("Nonterminal '{0}' not found", name));
return parser;
}
child = m["terminal"];
if (child)
return Terminal(child);
throw new FormatException("Invalid symbol");
}
Parser Terminal(Match m)
{
if (!m.Success)
return null;
var l = m["literal"];
if (l.Success)
return new LiteralTerminal(l.Text.Length > 0 ? l.Text : "'");
var t = m["terminal"];
if (t.Success)
return definition.Terminals[t.Text];
throw new FormatException("Invalid terminal");
}
Parser RegExp(Match m)
{
return Alternative(m, "regExpSeq", r => Sequence(r, "regExpItem", RegExpItem));
}
Parser RegExpItem(Match m)
{
if (!m.Success)
return null;
var item = RegExp(m["regExp2"]) ?? SetLiteralOrName(m, false) ?? Terminal(m["terminal"]);
var kleene = m["kleene"];
switch (kleene.Text)
{
case "+":
return new RepeatParser(item, 1);
case "*":
return new RepeatParser(item, 0);
case "?":
return new OptionalParser(item);
default:
return item;
}
}
Parser SetLiteralOrName(Match m, bool error = true)
{
var literal = m.Name == "setLiteral" ? m : m["setLiteral"];
if (literal.Success)
return Terminals.Set(literal.Find("ch").Select(r => r.Text.Length > 0 ? r.Text[0] : '\'').ToArray());
var name = m.Name == "setName" ? m["value"] : m["setName"]["value"];
if (name.Success)
{
Parser parser;
var nameText = name.Text;
if (definition.Sets.TryGetValue(nameText, out parser))
return parser;
var chars = nameText.Split(new [] { ".." }, StringSplitOptions.RemoveEmptyEntries);
if (chars.Length == 2)
{
// range of characters
return new CharRangeTerminal(Character(chars[0]), Character(chars[1]));
}
if (chars.Length == 1)
{
// single character
return new SingleCharTerminal(Character(chars[0]));
}
}
if (error)
throw new FormatException("Literal or set name missing or invalid");
return null;
}
static char Character(string charName)
{
int ch;
if (charName.StartsWith("&", StringComparison.Ordinal))
{
// hex value
if (int.TryParse(charName.Substring(1), NumberStyles.AllowHexSpecifier, null, out ch))
return (char)ch;
}
else if (charName.StartsWith("#", StringComparison.Ordinal))
{
// hex value
if (int.TryParse(charName.Substring(1), out ch))
return (char)ch;
}
throw new FormatException("Set characters are invalid");
}
Parser SetMatch(Match m)
{
Parser parser = null;
foreach (var child in m.Matches)
{
if (parser == null)
parser = SetLiteralOrName(child);
else if (child.Name == "add")
parser |= SetLiteralOrName(child);
else if (child.Name == "sub")
parser -= SetLiteralOrName(child);
}
return parser;
}
protected override int InnerParse(ParseArgs args)
{
definition = new GoldDefinition();
return base.InnerParse(args);
}
public GoldDefinition Build(string grammar)
{
var match = Match(grammar);
if (!match.Success)
throw new FormatException(string.Format("Error parsing gold grammar: {0}", match.ErrorMessage));
return definition;
}
public string ToCode(string grammar, string className = "GeneratedGrammar")
{
using (var writer = new StringWriter())
{
ToCode(grammar, writer, className);
return writer.ToString();
}
}
public void ToCode(string grammar, TextWriter writer, string className = "GeneratedGrammar")
{
var definition = Build(grammar);
definition.Grammar.Initialize();
var iw = new IndentedTextWriter(writer, " ");
iw.WriteLine("/* Date Created: {0}, Source:", DateTime.Now);
iw.Indent ++;
foreach (var line in grammar.Split('\n'))
iw.WriteLine(line);
iw.Indent --;
iw.WriteLine("*/");
var parserWriter = new CodeParserWriter
{
ClassName = className
};
parserWriter.Write(definition.Grammar, writer);
}
}
}
| 29.814721 | 184 | 0.642377 | [
"MIT"
] | DanielDavis5/Eto.Parse | Eto.Parse/Grammars/GoldGrammar.cs | 11,747 | C# |
using NServiceBus;
namespace Receiver
{
public class ReceiverConfiguration : EndpointConfiguration
{
public ReceiverConfiguration() : base("Receiver")
{
this.SendFailedMessagesTo("error");
this.UseTransport<LearningTransport>();
}
}
} | 22.769231 | 62 | 0.631757 | [
"Apache-2.0"
] | mauroservienti/NServiceBus.AttributeRouting | src/Receiver/ReceiverConfiguration.cs | 298 | 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.Graphics;
using osu.Framework.Platform;
using osu.Game.Configuration;
using osu.Game.Overlays;
using osu.Game.Overlays.Chat;
namespace osu.Game.Online.Chat
{
public class ExternalLinkOpener : Component
{
private GameHost host;
private DialogOverlay dialogOverlay;
private Bindable<bool> externalLinkWarning;
[BackgroundDependencyLoader(true)]
private void load(GameHost host, DialogOverlay dialogOverlay, OsuConfigManager config)
{
this.host = host;
this.dialogOverlay = dialogOverlay;
externalLinkWarning = config.GetBindable<bool>(OsuSetting.ExternalLinkWarning);
}
public void OpenUrlExternally(string url)
{
if (externalLinkWarning.Value)
dialogOverlay.Push(new ExternalLinkDialog(url, () => host.OpenUrlExternally(url)));
else
host.OpenUrlExternally(url);
}
}
}
| 33.081081 | 100 | 0.660131 | [
"MIT"
] | 123tris/osu | osu.Game/Online/Chat/ExternalLinkOpener.cs | 1,190 | C# |
using System.Net.Http;
namespace Legend.Onenet.Request.Topic
{
public class SearchSubscribeTopicDeviceRequest : RequestBase
{
public SearchSubscribeTopicDeviceRequest() : base(Constants.SearchSubscribeTopicDevice, HttpMethod.Get)
{
}
public SearchSubscribeTopicDeviceRequest(OnenetOptions onenetOptions) : base(Constants.SearchSubscribeTopicDevice, onenetOptions, HttpMethod.Get)
{
}
private string topic;
/// <summary>
/// 发布消息到指定的topic,只支持发布qos=0的消息
/// </summary>
public string Topic
{
get { return topic; }
set
{
PropertiesAdd(nameof(topic), value);
topic = value;
}
}
private int page;
/// <summary>
/// 指定页码
/// </summary>
public int Page
{
get { return page; }
set
{
PropertiesAdd(nameof(page), value.ToString());
page = value;
}
}
private int per_page;
/// <summary>
/// 指定每页输出设备个数,默认30,最多1000
/// </summary>
public int Per_page
{
get { return per_page; }
set
{
PropertiesAdd(nameof(per_page), value.ToString());
per_page = value;
}
}
}
} | 24.912281 | 153 | 0.496479 | [
"MIT"
] | myFirstway/Legend.OneNet | Legend.Onenet/Request/Topic/SearchSubscribeTopicDeviceRequest.cs | 1,496 | 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("SqlChangeTracker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("NGP VAN")]
[assembly: AssemblyProduct("SqlChangeTracker")]
[assembly: AssemblyCopyright("Copyright © NGP VAN 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("42b49a0d-345c-45eb-ae07-3512598d2e6e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.351351 | 84 | 0.74771 | [
"MIT"
] | NGPVAN/SqlChangeTracker | SqlChangeTracker/Properties/AssemblyInfo.cs | 1,422 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.